$(document).ready(function() {

    
    $('#u_country').change(function() {
        adjustregion('u');
    });

    $('#u_region').change(function() {
        adjustcity('u');
    });
    
    $('#h_country').change(function() {
        adjustregion('h');
    });

    $('#h_region').change(function() {
        adjustcity('h');
    });
    
    $('#p_country').change(function() {
        adjustregion('p');
    });

    $('#p_region').change(function() {
        adjustcity('p');
    });


});

function adjustregion(field_id) {
    if(field_id == '')
        field_id = 'u';
    
    var country_id = $('#'+field_id+'_country').val();
    var tmpSelect = $('#'+field_id+'_region');

    $.ajax({
        url: '/getajaxregions.php?country_id=' + country_id,
        dataType: "text",
        success: function(data) {
            json = eval("(" + data + ")");
            tmpSelect.fillSelect(json).attr('disabled', '');
        }
    });
}

function adjustcity(field_id) {
    if(field_id == '')
        field_id= 'u';
    
    var region_id = $('#'+field_id+'_region').val();
    var tmpSelect = $('#'+field_id+'_city');

    if ($('#u_city').attr('class') == 'noactive') {
        $('#u_city').attr('class', 'active');
        return false;
    }

    $.ajax({
        url: '/getajaxregions.php?region_id=' + region_id,
        dataType: "text",
        success: function(data) {
            json = eval("(" + data + ")");
            tmpSelect.fillSelect(json).attr('disabled', '');
        }
    });
}


(function($) {
    // очищаем select
    $.fn.clearSelect = function() {
        return this.each(function() {
            if (this.tagName == 'SELECT') {
                this.options.length = 0;
                $(this).attr('disabled', 'disabled');
            }
        });
    }
    // заполняем select
    $.fn.fillSelect = function(dataArray) {
        return this.clearSelect().each(function() {
            if (this.tagName == 'SELECT') {
                var currentSelect = this;
                $.each(dataArray, function(index, data) {
                    var option = new Option(data.text, data.value);
                    if ($.support.cssFloat) {
                        currentSelect.add(option, null);
                    } else {
                        currentSelect.add(option);
                    }
                });
            }
        });
    }
})(jQuery);
