function updateData(url, data, select, text) {
	progress.show(select);
	$.getJSON(url, data, function(data) {
			select = progress.hide();
			select.find("option").remove();
			select.append('<option value="0">'+text+'</option>');
			for (i=0; i<data.length; i++) {
				select.append('<option value="'+data[i]['id']+'">'+data[i]['name']+'</option>');
			}
		}
	);
}

function disableRegion() {
	$("#region_id").attr("disabled", "disabled");
	$("#region_id").find("option").remove();
	$("#region_id").append("<option>Сначала выберите страну</option>");
}

function disableCity(text) {
	$("#city_id").attr("disabled", "disabled");
	$("#city_id").find("option").remove();
	$("#city_id").append("<option>"+text+"</option>");
}
					
function updateRegions(country_id) {
	$("#region_id").removeAttr("disabled");
	disableCity("Сначала выберите регион");
	updateData("/geo/get-regions/", {country_id: country_id}, $("#region_id"), "- Выберите регион -");
}

function updateCities(region_id) {
	$("#city_id").removeAttr("disabled");
	updateData("/geo/get-cities/", {region_id: region_id}, $("#city_id"), "- Выберите город -");
}
	
	
function checkCountry(value) {
	if (value=="more") {
		updateData("/geo/get-countries/", {}, $("#country_id"), '- Выберите страну -');
	}
	if (value>0) {
		updateRegions(value);
	}
	if (value=="0" || value=="more") {
		disableRegion();
		disableCity("Сначала выберите страну");
	}
}

function checkRegion(value) {
		if (value>0) {
			updateCities(value);
		} else {
			disableCity("Сначала выберите регион");
		}
}

$(document).ready(function(){
	country = $("#country_id").val();
	region = $("#region_id").val();
	city = $("#city_id").val();
	if (country>0 && region==0 && city==0) {
		checkCountry(country);
	} else if (country>0 && region>0 && city==0) {
		checkRegion(region);
	}
});