var citySelect;
var regionSelect;
$(document).ready(function(){
	
	$('.zend_form label.required').append('<span style="color:red;font-weight:bold">*</span>');
	
	citySelect = document.getElementById('city_id');
	regionSelect = document.getElementById('region_id');

	$.datepicker.regional['ru'];
	$('#inquiry-date_end, #date_end').attr('readonly', 'readonly');
    $('#inquiry-date_end, #date_end').datepicker({
    	inline: true,
    	altFormat: 'dd-mm-yy',
    	dateFormat: 'yy-mm-dd',
    	maxDate: '+1m',
    	minDate: '+1w',
    	iframe: true
    });

    $('#country').change(function(){
    	emptySelectInput('region_id');
    	emptySelectInput('city_id');
      
        urlParams = null;
        if(this.value != ''){
        	regionSelect.disabled = true;
        	citySelect.disabled = true;
            urlParams = 'country=' + this.value;
            $.get(urlBase + 'geography/region/get-list', urlParams, fillSelectInput, 'json');
        }
    });
    
    $('#region_id').change(function(target){
    	citySelect = document.getElementById('city_id');
    	regionSelect = document.getElementById('region_id');
 
    	citySelectRefill(this, 'city_id');
    });
    $('#inquiry-region_id').change(function(target){
    	//alert(target.toSource());
    	citySelect = document.getElementById('inquiry-city_id');
    	regionSelect = document.getElementById('inquiry-region_id');

    	citySelectRefill(this, 'inquiry-city_id');
    });
    
    $('#category_id_description').css('top', $('#category_id-label').offset().top);
    $('#category_id_description').css('left', $('#category_id-label').offset().left + 400);
});

function citySelectRefill(target, idx){
	emptySelectInput(idx);
    urlParams = null;
    if(target.value != ''){
    	$('#'+idx).attr('disabled', true);
        urlParams = 'region_id=' + target.value;
        $.get(urlBase + 'geography/city/get-list', urlParams, fillSelectInput, 'json');
    }
	
}

function emptySelectInput(idx){
    selectInput = document.getElementById(idx);
    for(i = selectInput.length-1; i > 0; i--){
    	selectInput.options[i] = null;
    }
}

function fillSelectInput(data){
	if(this.url.search(/region\/get-list/gi) != -1){
	    selectInput = regionSelect;
	}else{
	    selectInput = citySelect;
	}
    roi = 1;
    for(i in data){
    	selectInput.options[roi] = new Option(data[i], i);
        roi++;
    }
    regionSelect.disabled = false;
    citySelect.disabled = false;
}

