﻿/// <reference path="~/jQuery/jquery.js" />
(function($) {
    jQuery.fn.extend({

        loadSelect: function(options) {
            var $t = $(this);

            var defaults = {
                idx: 0,
                data: '{}',
                url: '/services/PowerEquipmentService.asmx/GetBrochureCodesBySourceCd'
            };
            // Extend our default options with those provided.

            var opts = $.extend(defaults, options);

            if (this.is('select')) {
                if (opts.key && $(document).data(opts.key)) {
                    loadSelectData(this, $(document).data(opts.key), opts.idx);
                }
                else {
                    getSelectData(this, opts);
                }
            }
            return this;
        } // loadSelect

    }); // jQuery.fn.extend

    function getSelectData(select, opts) {
        jQuery.ajax({
            type: "POST",
            url: opts.url,
            data: opts.data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            global: false,
            success: function(msg) {
                if (opts.key)
                    $(document).data(opts.key, msg);
                loadSelectData(select, msg, opts.idx);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {

            }
        }); //ajax
    }
    function loadSelectData(select, data, selectedIndex) {
        $(select).removeOption(/./).addOption(JSON.parse(data), false);
    }
})(jQuery);