$(document).ready(function(){

	function init(){
		if (isset(curr_continent)){	update_region(curr_continent); }
		if (isset(curr_region)){ update_city(curr_region); }
	}
	
	$('select#country').change(function(){ update_region($(this).val()); });
	$('select#region').change(function(){ update_subregion($(this).val()); });


	function update_subregion(ref){
		$.getJSON('/common/includes/region.php?a=s&p=' + ref, null, function(j){		
		
		var options = '<option>Nearest Appellation</option>';

		for (var i = 0; i < j.length; i++) {
			options += '<option value="' + j[i].value + '">' + j[i].name + '</option>';
		}

		$("select#subregion").html(options);
		$('select#subregion option:first').attr('selected', 'selected');

		if(j.length > 0){ 
			document.getElementById('appellation').style.display = 'block';
		} else{
			document.getElementById('appellation').style.display = 'none';
		}
			
		if (isset(curr_subregion) && curr_subregion != ''){
			$('select#subregion option[@value="' + curr_subregion + '"]').attr('selected', 'selected');
			curr_subregion = '';
		}
		})
	}

	function update_region(ref){
		$.getJSON('/common/includes/region.php?a=r&p=' + ref, null, function(j){
		
		var options = '<option>Choose a Region</option>';
	
		for (var i = 0; i < j.length; i++) {
			options += '<option value="' + j[i].value + '">' + j[i].name + '</option>';
		}

		document.getElementById('appellation').style.display = 'none';

		$("select#region").html(options);
		$('select#region option:first').attr('selected', 'selected');
		$("select#region").attr('disabled', false);

		if (isset(curr_region) && curr_region != ''){
			$('select#region option[@value="' + curr_region + '"]').attr('selected', 'selected');
			curr_region = '';
		}
		})
	}
	 
	init();
});
