
$(document).ready(function(){

	function init(){

		if (isset(curr_continent)){

			update_region(curr_continent);
		}

		if (isset(curr_region)){

			update_city(curr_region);
		}

	}
	
	$('select#continent').change(function(){ update_region($(this).val()); });

	$('select#region').change(function(){ update_city($(this).val()); });

	function update_city(ref){

		$.getJSON('/cities/find_all_for_region/' + ref + '/' + $('select#continent').val() + '/', null, function(j){
		
			var options = '<option>Choose The Nearest City</option>';

			for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
			}

			$("select#city-id").html(options);
			$('select#city-id option:first').attr('selected', 'selected');
			$("select#city-id").removeAttr('disabled');
			
			if (isset(curr_city) && curr_city != ''){

				$('select#city-id option[@value="' + curr_city + '"]').attr('selected', 'selected');
				curr_city = '';
			}
		})
	}

	function update_region(ref){

		$.getJSON('/cities/find_parents_for_continent/' + ref + '/', null, function(j){
		
			var options = '<option>Choose A Region</option>';

			for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i] + '">' + j[i] + '</option>';
			}

			$("select#region").html(options);
			$('select#region option:first').attr('selected', 'selected');
			$("select#region").removeAttr('disabled');
			// $("select#city-id").attr('disabled', true);

			if (isset(curr_region) && curr_region != ''){

				$('select#region option[@value="' + curr_region + '"]').attr('selected', 'selected');
				curr_region = '';
			}
		})
	}
	 
	init();
});
