(function($) {
    $.Region = {
        country : null,
        region :null,
        init : function (reset_region) {
            if (reset_region == 1) {
                this.region.val(0);
            }
            this.country = $("#frmsearchForm-country");
            this.region = $("#frmsearchForm-region");
            if (this.country.length) {
                $("#region_container").empty();
                $.get("?do=initregion", {"country_id": this.country.val(), "region_id": this.region.val()}, function (data) {
                    $("#region_container").append(data);
                });
            }
        },
        change : function (region) {
            var new_value = $(region).val();
            this.region.val(new_value);

            var id = $(region).attr('id').toString();
            var last = id.lastIndexOf('_');
            var level = parseInt(id.substr(last + 1));

            var field_level = level + 1;

            // ak ex. region s vacsim cislom tak ich najprv zrusim
            while ($("#frm-region_" + field_level).length) {
                $("#frm-region_" + field_level).remove();
                field_level = field_level + 1;
            }

            if (new_value) {
                $.get("?do=loadregions", {"country_id": this.country.val(),  "region_id": region.value, "level": level}, function (data) {
                    $("#region_container").append(data);
                });
            } else {
                var higher_value = $("#frm-region_" + parseInt(level - 1)).val();
                this.region.val(higher_value);
            }
        }
    };
})(jQuery);

$(document).ready(function(){
        $.Region.init();
});

