// holds the remote server address 
var serverAddress = "lib/validator/validator.ajax.php";
// when set to true, display detailed error messages
var showErrors = true;
// initialize the validation requests cache 
var cache = new Array();

var htmlCacheContatti = '';
var htmlCacheSendButton = '';
var debug = false;


// the function handles the validation for any form field
function Validate(inputValue, fieldID)
{
    // if we received non-null parameters, we add them to cache in the
    // form of the query string to be sent to the server for validation
    if (fieldID)
    {
      // encode values for safely adding them to an HTTP request query string
      inputValue = encodeURIComponent(inputValue);
      fieldID = encodeURIComponent(fieldID);
      // add the values to the queue
      cache.push("validate=single&inputValue=" + inputValue + "&fieldID=" + fieldID);
    }
    // try to connect to the server
    try
    {
      // if the cache is not empty
      if( cache.length > 0)
      {
        // get a new set of parameters from the cache
        var cacheEntry = cache.shift();

		// SCRIPTACULOUS 
		/*var aj = new Ajax.Request(
			serverAddress,
				{
					method: 'post',
					parameters: cacheEntry,
					onComplete: ReadResponse
				}
			);*/
		
		//JQUERY
		$.ajax({
			   type: "POST",
			   url: serverAddress,
			   processData: false,
			   data: cacheEntry,
			   dataType: "xml",
			   success: ReadResponse
			   });
				
	  }
    }
    catch (e)
    {
		// display an error when failing to connect to the server
		if(debug)
	  		alert(e.toString());
    }
  
}

// read server's response 
function ReadResponse(data)
{
	//Nuovo oggetto DOM jquery
	var xmlData = $(data);
	
	// retrieve the server's response 
	var txtResponse = xmlData.text()
	
	if( debug )
		alert(txtResponse);
	
	// server error?
	if (txtResponse.indexOf("ERRNO") >= 0 || txtResponse.indexOf("error:") >= 0  || txtResponse.length == 0)
		throw(txtResponse.length == 0 ? "Server error." : txtResponse);
	
	// get the document element
	//xmlDoc = responseXml.documentElement;
	
	result = xmlData.find('result').text();
	fieldID = xmlData.find('fieldid').text();
	
	// find the HTML element that displays the error
	//message = document.getElementById(fieldID + "Failed");
	failed = $('#' + fieldID + 'Failed');
	
	// show the error or hide the error
	if(result == "0")
	{
		failed.removeClass("hidden");
		failed.addClass("error");
	}
	else
	{
		failed.removeClass("error");
		failed.addClass("hidden");
	}
	
	// call validate() again, in case there are values left in the cache
	setTimeout("Validate();", 500);
}

// sets focus on the first field of the form
function SetFocus()    
{	
  document.getElementById("txtName").focus();
}

//
//
// Convalida l'intero form
//
//

function ValidateAll()
{	
	var params = 'validate=all&sendmail=true';
	
	params += "&txtName="  		+ $('#txtName').val();
	params += "&txtSurname="  	+ $('#txtSurname').val();
	params += "&txtEmail="  	+ $('#txtEmail').val();
	params += "&txtRequest="  	+ $('#txtRequest').val();
	
	//Memorizza dati per nuova richiesta
	SaveCacheData();
	
	//Azzera testo pulsante invio richiesta
	SetSendButtonHtml('');
	
	//Imposta html invio informazioni
	SetFormContattiHtml('<p>Invio informazioni in corso </p> <img src="images/ajax-loader.gif" />');		
	

	
	try
	{
		// SCRIPTACULOUS
		/*var aj2 = new Ajax.Request(
						serverAddress,
							{
							method : 'post',
							parameters : "validationType=all" + params,
							onComplete: ReadFullResponse
							}
						);*/
		
				//JQUERY
		$.ajax({
			   type: "POST",
			   url: serverAddress,
			   processData: false,
			   data: params,
			   dataType: "text",
			   success: ReadFullResponse
			   });
	}
	catch(e)
	{
		if(debug)	
			alert(e.toString);
	}		
}

//
//
//	Risposta ricevuta al momento della validazione dell'intero form
//
//

function ReadFullResponse(textResponse)
{
	if(debug)
		alert(textResponse);
		
	if (textResponse.indexOf("ERRNO") >= 0 || textResponse.indexOf("error:") >= 0  || textResponse.length == 0)
		throw(textResponse.length == 0 ? "Server error." : textResponse);
	
	var divSendButton = '<div id="sendFormButton">';
	divSendButton += '<a href="#" onclick="ShowRequestForm();">Compila una nuova richiesta</a>';
	divSendButton += '</div>';
	
	$('#sendFormButton').html(divSendButton);
	
	
	switch(textResponse)
	{
		case 'OK':{
						$('#formContatti').html('<p>Richiesta inviata con successo. <br /> Grazie per averci contattato <br /> </p>');
					 }	
					 break;
						
		default: location.href = textResponse; break;
	}
}

function SaveCacheData()
{
	htmlCacheContatti = $('#formContatti').html();
	htmlCacheSendButton = $('#sendFormButton').html();
}

function SetSendButtonHtml(valHtml)
{
	$('#sendFormButton').html(valHtml);
}

function SetFormContattiHtml(valHtml)
{
	$('#formContatti').html(valHtml);	
}

function ShowRequestForm()
{
	SetFormContattiHtml( htmlCacheContatti );
	SetSendButtonHtml(htmlCacheSendButton);
}
