$(function() {

	var distrito = $('#district_').val();
	var city = $('#city_').val();

	
	var sl_distritos=document.getElementById('g_distrito');
  if( sl_distritos ){
		if( sl_distritos.length >= 0 ){
			for (var i = sl_distritos.length - 1; i>=0; i--) {
    			sl_distritos.remove(i);
			}
		}	
	
		$.ajax({
     		type:'GET',
			url:'gen.pl?p=geo',
			data:'table=districts',
			success:function(data){
				var d=data.split(",");
		    	addOption(sl_distritos, 'Seleccionar um distrito', '');
				for(var i=0; i < d.length - 1; i++) {
					var di = d[i].split(";");
					addOption(sl_distritos, di[1], di[0]);
				}

				if( distrito ){
					$('#g_distrito option:selected').removeAttr('selected','selected');
					$('#g_distrito option').each(function(){
						if($(this).val() == distrito ){
							$(this).attr('selected','selected');
							$("#g_distrito").trigger('change');
						}
					});
				}

			}
		});
	}

	$('#g_distrito').change(function() {
		var sl_concelhos=document.getElementById('g_concelho');
		if( sl_concelhos ) {
			if( sl_concelhos.length >= 0 ){
				for (var i = sl_concelhos.length - 1; i>=0; i--) {
					sl_concelhos.remove(i);
				}
		
				var distrito = $(this).val();
				$.ajax({
					type:'GET',
					url:'gen.pl?p=geo',
					data:'table=counties&district='+escape(distrito),
	       			success:function(data){
						var d=data.split(",");
						addOption(sl_concelhos, 'Seleccionar...', '');
						for(var i=0; i < d.length - 1; i++) {
							var c = d[i].split(";");
							addOption(sl_concelhos, c[1], c[0]);
						}

						if( city ){
							$('#g_concelho option:selected').removeAttr('selected','selected');
							$('#g_concelho option').each(function(){
								if($(this).val() == city ){
									$(this).attr('selected','selected');
								}
							});
						}


					}
				});
			}
		}	
	});
});
