(function($) {
    // definition
    $.fn.asyncSelect = function(options) {

        var mSel = $(this);

        var opts = $.extend({}, $.fn.asyncSelect.defaults, options);

        mSel.attr('disabled', 'disabled');

        var populate = function() {
            var txt = mSel.find('option:eq(0)').text();
            mSel.find('option:eq(0)').text(opts.searchTxt);
            mSel.attr('disabled', 'disabled');
            mSel.find('option:gt(0)').remove();

            var pieces = [];
            $(opts.params).each(function(i, el) {
                pieces.push(el.key + '=' + el.value);
            })
            var jsonCall = opts.jsonURL + '?' + pieces.join('&');
            if (typeof (opts.buildOwnJsonCall) == "function") {
                jsonCall = opts.buildOwnJsonCall();
            }
            $.getJSON(jsonCall, function(jsonObj) {
                if (jsonObj.errCode == 0) {
                    if (jsonObj.data != '') {
                        mSel.find('option:gt(0)').remove();
                        $(jsonObj.data).each(function(i, el) {
                            mSel.append('<option value="' + el.value + '">' + el.label + '</option>');
                        })
                        mSel.removeAttr('disabled');
                    } else {
                        mSel.trigger('change');
                    }
                } else {
                    //console.error(jsonObj.error);
                    // haremos como si nada pues...
                    mSel.trigger('change');
                }
                mSel.find('option:eq(0)').text(txt);
                //mSel.removeAttr('disabled');
                if ($.qs[mSel.attr('name')] != null && (opts.syncQueryString || opts.syncQueryStringOnce)) {
                    if (mSel.find('option[value=' + $.qs[mSel.attr('name')] + ']').length > 0) {
                        mSel.find('option[value=' + $.qs[mSel.attr('name')] + ']').attr('selected', 'selected');
                        mSel.trigger('change');
                    }
                    if (opts.syncQueryStringOnce) {
                        opts.syncQueryStringOnce = false;
                    }
                }
                typeof (opts.onJsonLoadedOnce) == "function" ? opts.onJsonLoadedOnce(mSel) : false;
                opts.onJsonLoadedOnce = null;
                typeof (opts.onJsonLoaded) == "function" ? opts.onJsonLoaded(mSel) : false;

            })
            //typeof (opts.populateEnd) == "function" ? opts.populateEnd() : false;
        }
        //if ($(opts.nodeTriggerer).val() != opts.nullValue) {
        $(opts.nodeTriggerer).bind(opts.populateEvent, populate);
        if (opts.populateEvent.match(/load/)) {
            populate();
        }
        //}
        return mSel;
    }

    $.fn.asyncSelect.defaults = {
        buildOwnJsonCall: {},
        onJsonLoaded: {},
        nodeTriggerer: $(document),
        syncQueryString: false,
        syncQueryStringOnce: false,
        populateEvent: 'change',
        jsonURL: 'asyncSelectJson.aspx',
        nullValue: '-1',
        params: [],
        mainLabel: ' -- select -- ',
        searchTxt: ' Searching... '
    }
})(jQuery);
/*var sleep = function (delay){
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}
$.log = function(msg) {
    $('.debug').html($('.debug').html() + msg + "<br />");
}
$(document).ready(function() {
    $('<div class="debug"></div>').appendTo('body');
    $('.debug').css({ overflow:'scroll',position:'absolute',top:'0px',left:'0px', textAlign:'left', width: '100%', height: '300px', background:'white' })
})*/
