(function($){
    $.fn.countryBox = function (opts){
        opts = $.extend({}, $.fn.countryBox.defaults, opts);

        return this.each(function(){
            new CountryBox(this, opts);
        });
    };
    var CountryBox = function(context, opts) {
        $('#'+opts.countrySelect).change(function(){
            if ($('#'+opts.countrySelect).val()!=''){
                process($('#'+opts.countryLoader),{
                    xaction: 'ajaxCountryBox',
                    field: 'country',
                    country: $('#'+opts.countrySelect).val()
                });
            }
        });
        function process(loader, args){
            loader.addClass('loading');
            $('#'+opts.countrySelect).attr('disabled',true);
            var ajaxReq={
                type: 'POST',
                dataType: 'text',
                data: args,
                success: function(html){
                    eval('data='+html+';');
                    if (data.phoneCode!==undefined){
                        $('#'+opts.phoneCode).val('+'+data.phoneCode);
                    }
                    loader.removeClass('loading');
                    $('#'+opts.countrySelect).removeAttr('disabled');
                    forceOperaRepaint();
                }
            };
            if (opts.url){
                ajaxReq.url=opts.url;
            }
            $.ajax(ajaxReq);
        }
        function insertOption(select, value, text){
            newOption = document.createElement("OPTION");
            newOption.text = text;
            newOption.value = value;
            select.options.add(newOption);
        }
        function updateSelect(id, options, isCity){
            var select = document.getElementById(id);
            select.innerHTML = '';
            if (!isCity) insertOption(select, '', ' ');
            for (optId in options){
                insertOption(select, options[optId].value, options[optId].text);
            }
            if (isCity) insertOption(select, '!!!other!!!', ' --- ������ --- ');
        }
    }
    $.fn.countryBox.defaults = {
        phoneCode: 'phoneCode',
        countrySelect: 'countrySelect',
        countryLoader: 'countryLoader',
        regionSelect: 'regionSelect',
        regionHolder: 'regionHolder',
        regionLoader: 'regionLoader',
        filialsHolder: 'filialsHolder',
        filialsBox: 'filialsBox',
        citySelect: 'citySelect',
        cityInput: 'cityInput',
        citySelectHolder: 'citySelectHolder',
        cityInputHolder: 'cityInputHolder',
        cityLoader: 'cityLoader',
        adSourceSelect: 'adSourceSelect',
        adSourceHolder: 'adSourceHolder',
        adSourceLoader: 'adSourceLoader',
        adListSelect: 'adListSelect',
        adListHolder: 'adListHolder',
        useAdSource: true,
        countryOnly: false,
        url: ''
    }
})(jQuery);
