$(document).ready(function(){
	// Blur for IE (v.7) to activate autocomplete on focus! (on refresh the element saves the focus)
	// This should be before binding focus/blur events for the input fields
	$("#citta").blur();
	$("#via").blur();
	
	// This can be used only for IE6 - for the hover effect
	$('.button_cerca').hover(function() {
		$(this).addClass('button_cerca_over');
	}, function() {
		$(this).removeClass('button_cerca_over');
	});
	
	// Disable only if JS is enabled
	$("#via").attr("disabled", true);
	$("#citta_via_submit").attr("disabled", true);
});

$(function() {
	var array_citta = "";
	var array_via = "";
	var citta_focus = 0;
	var via_focus = 0;
	
	function formatCity(text) {
		return text.value; // do not show KEY
	}
	// Specify the width!
	$("#citta")
		.autocomplete(
			"server_script_citta_3.php"
			,{
				selectFirst: true
				,minChars: 2
				,multiple: false
				,scrollHeight: 340
				,width: 370
				//,max: 3 // Limit users
				//,mustMatch: true
					//,matchContains: false // do not match everywhere??? ot what? - http://groups.google.com/group/jquery-en/browse_thread/thread/1421c4dd456bd124
				//,autoFill: true
				,highlightItem: false
				,parse: function(data) {
					/*
					eval("data="+data);
					
					//console.log(array_citta);
					if( data!=0 || data!="0" ) { // skip data=0
						if( array_citta.length>0 ) {
							array_citta = array_citta.concat(data);
						} else {
							array_citta = data;
						}
					} else {
						//console.log(data);
					}
					//console.log(array_citta);
					*/
					return $.map(eval(data), function(row) {
						return {
							data: row, // may be this is used 
							value: row.value, // This is the value, which is used in the input field
							result: row.value // do not show KEY // This is showed in the autocomplete list
						}
					});
				}
				,formatItem: function(item) {
					return formatCity(item);
				}
			}
		)
		.keyup(function(){
			checkValidCittaVia();
		})
		.change(function(){
			checkValidCittaVia();
		})
		.focus(function(){
			citta_focus = 1;
		})
		.blur(function(){
			citta_focus = 0;
		})
	;
	$("#via")
		.autocomplete(
			"server_script_via_3.php"
			,{
				selectFirst: true
				,minChars: 2
				,multiple: false
				,scrollHeight: 340
				,width: 370
				//,max: 3 // Limit users
				//,mustMatch: true
					//,matchContains: false // do not match everywhere??? ot what? - http://groups.google.com/group/jquery-en/browse_thread/thread/1421c4dd456bd124
				//,autoFill: true
				,highlightItem: false
				,parse: function(data) {
					/*
					eval("data="+data);
					//console.log(array_citta);
					if( data!=0 || data!="0" ) { // skip data=0
						if( array_via.length>0 ) {
							array_via = array_via.concat(data);
						} else {
							array_via = data;
						}
					} else {
						//console.log(data);
					}
					//console.log(array_citta);
					*/
					return $.map(eval(data), function(row) {
						return {
							data: row, // may be this is used 
							value: row.value, // This is the value, which is used in the input field
							result: row.value // do not show KEY // This is showed in the autocomplete list
						}
					});
				}
				,formatItem: function(item) {
					return formatCity(item);
				}
			}
		)
		.keyup(function(){
			checkValidCittaVia();
		})
		.change(function(){
			checkValidCittaVia();
		})
		.focus(function(){
			via_focus = 1;
		})
		.blur(function(){
			via_focus = 0;
		})
	;
	
	$("#hint_div")
		.mousedown(function(){
			checkChooseCittaViaData();
		})
	;
	function checkChooseCittaViaData()
	{
		// wait before checking to allow the Autocomplete script to fill the selected data
		setTimeout(function(){
			checkValidCittaVia();
		}, 200);
		return;
	}
	
	// Final Check to the server - this enables submit button
	function checkValidCittaVia(){
		//alert($("#citta").val());
		var citta_value = $("#citta").val();
		var via_value = $("#via").val();
		//alert(citta_value.length);
		
		// citta_focus = 1;
		// via_focus = 1;
		
		// if values are less than 2 signs:
		if( citta_focus==1 ) {
			if( citta_value.length<2 ) {
				hideWarningCitta();
				correctCitta();
				disableVia();
				disableCittaViaSubmit();
				return;
			}
		}
		if( via_focus==1 ) {
			if( via_value.length<2 ) {
			
				hideWarningVia();
				correctVia();
				disableCittaViaSubmit();
				return;
			}
			
			
			
			
		}
		
		
		$.get(
			"server_script_validate_3.php"
			,{	
				"action": "validate_data"
				,"citta": citta_value
				,"via": via_value
				,"citta_focus": citta_focus
				,"via_focus": via_focus
			}
			,function(data){	//Callback function
				//alert("Data Loaded: " + data);
				
				// convert string to json object (or array?)! - use Type option for .GET or this row
				//eval("data="+data); // used "JSON" type of "$.GET" to skip that!
				
				if( data.result==1 )
				{
					//console.log("OK");
					//console.log(data);
					// Make sure the values are not changed. If changed, the new verification has been started - stop this OLD script
					if( data.citta != $("#citta").val() ) {
						return;
					}
					if( data.via != $("#via").val() ) {
						return;
					}
					
					if( data.citta_focus==1 ) {
						checkCittaData(data);
						/*
						// No need to check this value as every change to 
						if( data.citta_found == 1 ) {
							checkViaData(data);
						}
						*/
					}
					
					if( data.via_focus==1 ) {
						checkViaData(data);
					}
					
					
					
					
				} else {
					//console.log("NOT OK");
				}
				
			}
			,"json"
		);
	}
	
	function checkCittaData(data)
	{
		if( data.citta_found == 1 ) { // found
			hideWarningCitta();
			correctCitta();
			enableVia();
			caricaCoordinate($("#citta").val(), "citta", 0);
			//alert("a");
			
		} else if( data.citta_found == 2 ) { // in progress
			hideWarningCitta();
			correctCitta();
			clearVia();
			disableVia();
			disableCittaViaSubmit();
		} else { // not exists
			hideWarningVia();
			showWarningCitta();
			wrongCitta();
			clearVia();
			disableVia();
			disableCittaViaSubmit();
		}
	}
	
	function checkViaData(data)
	{
		if( data.via_found == 1 ) { // found
			hideWarningVia();
			correctVia();
			enableCittaViaSubmit();
			caricaCoordinate($("#via").val(), "via", data.viaID);
			
		} else if( data.via_found == 2 ) { // in progress
			hideWarningVia();
			correctVia();
			disableCittaViaSubmit();
		} else { // not exists
			hideWarningCitta(); // just double sure
			showWarningVia();
			wrongVia();
			disableCittaViaSubmit();
		}
	}
	function showWarningCitta()
	{
		$("#warning_citta").show();
	}
	function hideWarningCitta()
	{
		$("#warning_citta").hide();
	}
	function showWarningVia()
	{
		$("#warning_via").show();
	}
	function hideWarningVia()
	{
		$("#warning_via").hide();
	}
	
	function correctCitta()
	{
		$("#citta").removeClass("notFoundText");
	}
	function wrongCitta()
	{
		$("#citta").addClass("notFoundText");
	}
	
	function enableVia()
	{
		$("#via").removeAttr("disabled");
		$("#via").removeClass("itext2").addClass("itext");
		$("#via").removeClass("notFoundText");
	}
	function clearVia()
	{
		$("#via").val("");
	}
	function disableVia()
	{
		$("#via").val("");
		$("#via").attr("disabled", true);
		$("#via").removeClass("itext").addClass("itext2");
		$("#via").removeClass("notFoundText");
	}
	function correctVia()
	{
		$("#via").removeClass("notFoundText");
	}
	function wrongVia()
	{
		$("#via").addClass("notFoundText");
	}
	
	function enableCittaViaSubmit()
	{
		$('#citta_via_submit').removeAttr("disabled").addClass("button_cerca").removeClass("button_cerca_disabled");
	}
	function disableCittaViaSubmit()
	{
		$('#citta_via_submit').attr("disabled", true).addClass("button_cerca_disabled").removeClass("button_cerca");
	}
});
