﻿// --------------------------------------------------------------------------------
// Clears a select list.
// --------------------------------------------------------------------------------
$.fn.clearSelect = function () {

    return this.each(function () {

        if (this.tagName == 'SELECT') {
            this.innerHTML = '';
        }
    });
}

// --------------------------------------------------------------------------------
// Switches the element's classes
// --------------------------------------------------------------------------------
$.fn.switchClasses = function (class1, class2) {
    return this.each(function () {
        if ($(this).hasClass(class2)) {
            $(this).addClass(class1);
            $(this).removeClass(class2);
        }
        else {
            $(this).addClass(class2);
            $(this).removeClass(class1);
        }
    });
}

// --------------------------------------------------------------------------------
// Sets the css class.
// --------------------------------------------------------------------------------
$.fn.cssClass = function (cssClassName) {
    this.each(function () {
        this.className = cssClassName;
    });
}

// --------------------------------------------------------------------------------
// Fills the select list with JSON data.
// --------------------------------------------------------------------------------
$.fn.fillSelect = function (data) {
    return this.clearSelect().each(function () {
        if (this.tagName == 'SELECT') {
            var DropdownList = this;

            $.each(data, function (index, optionData) {

                if (optionData.Text != undefined && optionData.Value != undefined) {
                    var option = new Option(optionData.Text, optionData.Value);
                    option.selected = optionData.Selected;

                    if ($.browser.msie) {
                        DropdownList.add(option);
                    }
                    else {
                        DropdownList.add(option, null);
                    }
                }
                else if (optionData.Items != undefined) {
                    var Html = '<optgroup label="' + optionData.Label + '">';

                    for (var Key in optionData.Items) {
                        var Selected = '';

                        if (optionData.Items[Key].Selected) {
                            Selected = ' selected="selected"';
                        }

                        Html += '<option value="' + optionData.Items[Key].Value + '"' + Selected + '>' + optionData.Items[Key].Text + '</option>';
                    }

                    Html += '</optgroup>';

                    DropdownList.innerHTML += Html;
                }
            });
        }
    });
}
