//FUNZIONI DI VALIDAZIONE JAVASCRIPT


/**
*	checkNull 			( theField, errorMessage );
*	checkNumeric 			( theField, doTrim, isInteger, canBeNegative, canZeroBeFirstChar, notNumberErrorMessage, negativeErrorMessage, firstZeroErrorMessage );
*	checkAlphanumeric 		( theField, isBlankSpaceAllowed, errorMessage );
*	checkThreeFieldsDate 		( dayField, monthField, yearField, yearFieldLength, yearLowerLimit, isDateBeforeToday );
*	TBD checkSingleFieldDate 	( dateField, yearFieldLength, yearLowerLimit, isDateBeforeToday );
*	checkLength 			( theField, minLength, maxLength, errorMessage );
*	checkEmail			( theField, errorMessage);
*
*
*	Utilities
*
*	Trim(inString);
*	annoBisestile(anno);
*	maiuscolo(theField);
*	minuscolo(theField);
*	formToUpperCase( theForm, exceptThoseFields[]);
*
*	-------------------------------------------------------------------------------------------------------------------------------
*
*	Esempio di utilizzo nella validazione di un form HTML:
*
*	function validateForm(theForm)
*	{
*		theForm.zip.value = Trim(theForm.zip.value);
*		checkLength 	( theForm.zip, 5, 5, 'Il CAP deve essere lungo 5 caratteri' );
*		checkNull 	( theForm.nome, '' );
*		checkNumeric 	( theForm.telefono, false, true, '', 'Il numero di telefono deve essere > 0', '' );	
*		...
*			
*		if ( isFormCorrect == false)
*		{
*			//reset control flag for a new check
*			isFormCorrect = true;
*			return false;
*		}
*	
*		return true;	
*	}	
*
*	...nella dichiarazione del form....
*
*	<FORM name="myForm" action="targetPage.jsp" method="post" onSubmit="return validateForm(this)">
**/

///////////////////////////////////////////////////////////////////////////////////////////////
//////////////////// VARIABILE GLOBALE DI CONTROLLO VALIDAZIONE ///////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

var isFormCorrect = true;

///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////// MESSAGGI D'ERRORE //////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

var ERROR_PREFIX 				= "ATTENZIONE. ";

/*STRING ERRORS*/
var ERROR_IS_NULL 				= ERROR_PREFIX + "Il campo non può essere vuoto.";
var ERROR_IS_NOT_EXACT_LENGTH 			= ERROR_PREFIX + "Il campo deve essere lungo ";
var ERROR_IS_NOT_IN_RANGE_LENGTH 		= ERROR_PREFIX + "La lunghezza del campo deve essere compresa tra  ";

/*NUMERIC ERRORS*/
var ERROR_IS_NOT_A_NUMBER 			= ERROR_PREFIX + "Il campo deve essere un numero.";
var ERROR_IS_NOT_AN_INTEGER 			= ERROR_PREFIX + "Il campo deve essere un numero intero.";
var ERROR_IS_STARTING_WITH_ZERO 		= ERROR_PREFIX + "Il campo non può iniziare per zero. Fornire un numero valido.";
var ERROR_IS_NEGATIVE 				= ERROR_PREFIX + "Il campo deve essere un numero maggiore di zero.";

/*ALPHANUMERIC ERRORS*/
var ERROR_IS_NOT_ALPHANUMERIC 			= ERROR_PREFIX + "Il campo deve essere alfanumerico (a-z,A-Z,0-9).";
var ERROR_IS_NOT_ALPHANUMERIC_INCLUDING_SPACE 	= ERROR_PREFIX + "Il campo deve essere alfanumerico (a-z,A-Z,0-9) e non può contenere spazi.";

/*DATE ERRORS*/
var ERROR_IS_NOT_4_DIGIT_YEAR 			= ERROR_PREFIX + "L\'ANNO deve essere di 4 cifre (es. 2001).";
var ERROR_IS_BEFORE_LOWER_YEAR 			= ERROR_PREFIX + "L\'ANNO deve essere successivo al ";
var ERROR_IS_NOT_NUMERIC_YEAR 			= ERROR_PREFIX + "L\'ANNO deve essere numerico.";
var ERROR_IS_NEGATIVE_YEAR 			= ERROR_PREFIX + "L\'ANNO deve essere maggiore di zero.";
var ERROR_IS_NOT_2_DIGIT_MONTH 			= ERROR_PREFIX + "Il MESE deve essere di 2 cifre (es. 05).";
var ERROR_IS_OUT_OF_RANGE_MONTH 		= ERROR_PREFIX + "Il MESE deve essere compreso tra 01 e 12.";
var ERROR_IS_NOT_NUMERIC_MONTH 			= ERROR_PREFIX + "Il MESE deve essere numerico.";
var ERROR_IS_NEGATIVE_MONTH 			= ERROR_PREFIX + "Il MESE deve essere maggiore di zero.";
var ERROR_IS_NOT_2_DIGIT_DAY 			= ERROR_PREFIX + "Il GIORNO deve essere di 2 cifre (es. 09).";
var ERROR_IS_OUT_OF_RANGE_DAY 			= ERROR_PREFIX + "Il GIORNO deve essere compreso tra 01 e 31.";
var ERROR_IS_NOT_NUMERIC_DAY 			= ERROR_PREFIX + "Il GIORNO deve essere numerico.";
var ERROR_IS_NEGATIVE_DAY 			= ERROR_PREFIX + "Il GIORNO deve essere maggiore di zero.";
var ERROR_IS_30_DAYS_MONTH 			= ERROR_PREFIX + "Il MESE specificato non ha 31 giorni.";
var ERROR_IS_29_DAYS_MONTH 			= ERROR_PREFIX + "Il MESE specificato non ha più di 29 giorni.";
var ERROR_IS_28_DAYS_MONTH 			= ERROR_PREFIX + "Il MESE specificato non ha più di 28 giorni.";
var ERROR_IS_GREATER_THAN_TODAY 		= ERROR_PREFIX + "La DATA immessa non può essere maggiore della data odierna.";

/*EMAIL ERRORS*/
ERROR_IS_BAD_EMAIL 				= ERROR_PREFIX + "L\'indirizzo EMAIL fornito non è valido.";


///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// CAMPO NOT NULL /////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
function checkNull(theField,errorMessage)
{
	if ( isFormCorrect == false)
	{
		//someone else failed so I don't need any further validation!
		return true;
	}
	        
        o = theField;
	if (typeof o == "object" && o.value == "")
	{
		if ( errorMessage == "" )
			alert( ERROR_IS_NULL );
		else
			alert(errorMessage);
			
		o.focus();
		isFormCorrect = false;
		return false;
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// LUNGHEZZA CAMPO ////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
function checkLength ( theField, 
			minLength, 
			maxLength, 
			errorMessage )
{
	if ( isFormCorrect == false)
	{
		//someone else failed so I don't need any further validation!
		return true;
	}
	
	o = theField;
	
	if ( typeof o != 'object' )
		return true;
		
	lunghezza = o.value.length;
	
	if ( minLength == maxLength )
	{
		if (lunghezza > 0 && lunghezza != minLength)
		{
			if ( errorMessage == "" )
				alert( ERROR_IS_NOT_EXACT_LENGTH + minLength + ' caratteri.');
			else
				alert(errorMessage);
							
			o.focus();
			isFormCorrect = false;
			return false;
		}
	}
	else
	{
		if (lunghezza > 0 && (lunghezza < minLength || lunghezza > maxLength) )
		{
			if ( errorMessage == "" )
				alert( ERROR_IS_NOT_IN_RANGE_LENGTH + minLength + ' e ' + maxLength + ' caratteri.');
			else
				alert(errorMessage);
							
			o.focus();
			isFormCorrect = false;
			return false;
		}		
	}
		
	
}

///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// CAMPO NUMERICO /////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
function checkNumeric( theField, 
			doTrim, 
			isInteger, 
			canBeNegative, 
			canZeroBeFirstChar, 
			notNumberErrorMessage, 
			negativeErrorMessage, 
			firstZeroErrorMessage )
{
	if ( isFormCorrect == false)
	{
		//someone else failed so I don't need any further validation!
		return true;
	}

        o = theField;
	var valore = "";
	
	if (typeof o == "object")
	{
      		valore = o.value;
	}
	else
	{
		return true;
	}

	if ( doTrim == true )
	{
		valore = Trim(valore);
		o.value = valore;
	}
		
	if (isInteger == true)
	{
		if ( valore.indexOf(".") != -1 )
		{
			alert( ERROR_IS_NOT_AN_INTEGER );
		        o.focus();
		        isFormCorrect = false;
	        	return false;
		}
	}
	
	if (isNaN(valore) || valore.indexOf(' ') != -1  || valore.indexOf('e') != -1  || valore.indexOf('E') != -1 )
	{
	        if ( notNumberErrorMessage == "" )
	        {
		        alert( ERROR_IS_NOT_A_NUMBER );
		        o.focus();
	        }
	        else
	        {
		        alert(notNumberErrorMessage);
		        o.focus();
	        }
	        isFormCorrect = false;
	        return false;
	}

	if (canZeroBeFirstChar == false )
	{
		if (valore.substring(0,1) == '0')
		{
		        if ( firstZeroErrorMessage == "" )
		        {		        
			        alert( ERROR_IS_STARTING_WITH_ZERO );
			        o.focus();
		        }
		        else
		        {
			        alert(firstZeroErrorMessage);
			        o.focus();
		        }
		        isFormCorrect = false;
		        return false;		        
		}
	}

	if (canBeNegative == false )
	{
		if ( o != null && ( isNaN(o.value) || o.value < 0 ) )
		{
		        if ( negativeErrorMessage == "" )
		        {			
				alert( ERROR_IS_NEGATIVE );
				o.focus();
		        }
		        else
		        {
			        alert(negativeErrorMessage);  
			        o.focus();      	
		        }
		        isFormCorrect = false;
		        return false;			
		}
	}
	
	return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////// CAMPO ALFANUMERICO /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

function checkAlphanumeric (theField, isBlankSpaceAllowed, errorMessage)
{
	if ( isFormCorrect == false)
	{
		//someone else failed so I don't need any further validation!
		return true;
	}
	
	o = theField;
	var str = new String();
	
	if ( isBlankSpaceAllowed == true)
		var reAlphanumeric = /^[ a-zA-Z0-9]+$/;
	else
		var reAlphanumeric = /^[a-zA-Z0-9]+$/;

	if (typeof o == "object")
	{
	    str = o.value;

		if ( str != "" && reAlphanumeric.test(str)==false ) //|| str.indexOf(" ") != -1)
		{
			if (errorMessage == "")
			{
				if ( isBlankSpaceAllowed == true)
					alert(ERROR_IS_NOT_ALPHANUMERIC);
				else
					alert(ERROR_IS_NOT_ALPHANUMERIC_INCLUDING_SPACE);
					
				o.focus();
			}
			else
			{
				alert(errorMessage);
				o.focus();
			}
			
			isFormCorrect = false;
			return false;
		}
	}
	else
		return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////// CAMPO DATA (3 input distinti) ////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

function checkThreeFieldsDate( dayField, 
				monthField, 
				yearField, 
				yearFieldLength, 
				yearLowerLimit, 
				isDateBeforeToday )
{
	if ( isFormCorrect == false)
	{
		//someone else failed so I don't need any further validation!
		return true;
	}
	
	gg = dayField;
	mm = monthField;
	aa = yearField;
	
	if ( typeof gg != 'object' || typeof mm != 'object' || typeof aa != 'object' )
	{
		return true;
	}
	
	if (  gg.value == '' &&  mm.value == '' &&  aa.value == '' )
	{
		return true;
	}
	
	///////////validazione anno /////////////
	
	checkNumeric(aa,false,false,true, ERROR_IS_NOT_NUMERIC_YEAR, ERROR_IS_NEGATIVE_YEAR,'');
	
	if ( aa.value.length != yearFieldLength )
	{
		alert(ERROR_IS_NOT_4_DIGIT_YEAR );
		isFormCorrect = false;
		aa.focus();
		return false;
	}
		
	if ( yearFieldLength == 4 && yearLowerLimit != "" )
	{
		if (aa.value < yearLowerLimit)
		{
			alert( ERROR_IS_BEFORE_LOWER_YEAR + yearLowerLimit + '. ');
			isFormCorrect = false;
			aa.focus();
			return false;			
		}
	}
	
	///////////validazione mese /////////////
	
	checkNumeric(mm,false,false,true,ERROR_IS_NOT_NUMERIC_MONTH ,ERROR_IS_NEGATIVE_MONTH ,"");
	
	if ( mm.value.length != 2)
	{
		alert(ERROR_IS_NOT_2_DIGIT_MONTH);
		isFormCorrect = false;
		mm.focus();
		return false;		
	}
	
	if ( mm.value < 1 || mm.value > 12)
	{
		alert(ERROR_IS_OUT_OF_RANGE_MONTH );
		isFormCorrect = false;
		mm.focus();
		return false;		
	}
		
	///////////validazione giorno /////////////
	
	checkNumeric(gg,false,false,true,ERROR_IS_NOT_NUMERIC_DAY ,ERROR_IS_NEGATIVE_DAY,"");
	
	if ( gg.value.length != 2)
	{
		alert(ERROR_IS_NOT_2_DIGIT_DAY );
		isFormCorrect = false;
		gg.focus();
		return false;		
	}
	
	
	giorno = gg.value;
	mese = mm.value;
	
	if (giorno > 31 ) //here!!!!!
	{
		alert(ERROR_IS_OUT_OF_RANGE_DAY);
		isFormCorrect = false;
		gg.focus();
		return false;
	}
			
	if (giorno == 31 && (mese == 4 || mese == 6 || mese == 9 || mese == 11)) //here!!!!!
	{
		alert(ERROR_IS_30_DAYS_MONTH);
		isFormCorrect = false;
		gg.focus();
		return false;
	}
		
	//* Controllo anno bisestile *//
	anno = aa.value;

	if (annoBisestile(anno))
	{
		if (giorno >= 30 && mese == 2)
		{
			alert(ERROR_IS_29_DAYS_MONTH);
			isFormCorrect = false;
			gg.focus();
			return false;
		}
	}
	else
	{
		if (giorno >= 29 && mese == 2)
		{
			alert(ERROR_IS_28_DAYS_MONTH );
			isFormCorrect = false;
			gg.focus();
			return false;
		}
	}
	
	//* Controllo che la data sia minore o uguale alla data odierna *//
	
	if ( isDateBeforeToday == true && yearFieldLength == 4 )
	{
		Data_Nascita = new Date(aa.value, (mm.value - 1), gg.value);
		Data_Corrente = new Date();
		
		meseNascita   = Data_Nascita.getMonth();
		giornoNascita = Data_Nascita.getDate();
		meseCorrente  = Data_Corrente.getMonth();
		giornoCorrente = Data_Corrente.getDate();
		
		if ( parseInt(meseNascita) < 10 )
			meseNascita = "0" + meseNascita;
			
		if ( parseInt(giornoNascita) < 10 )
			giornoNascita = "0" + giornoNascita;		
			
		if ( parseInt(meseCorrente) < 10 )
			meseCorrente = "0" + meseCorrente;
			
		if ( parseInt(giornoCorrente) < 10 )
			giornoCorrente = "0" + giornoCorrente;
			
				
		nascita  = Data_Nascita.getYear().toString() + meseNascita + giornoNascita;
		corrente = Data_Corrente.getYear().toString() + meseCorrente + giornoCorrente;
		
		if ( parseInt(nascita) > parseInt(corrente) )
		{
			alert(ERROR_IS_GREATER_THAN_TODAY);
			isFormCorrect = false;
			gg.focus();
			return false;
		}
	}
			
}



///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////// CAMPO EMAIL /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////

function checkEmail( theField, errorMessage)
{
	if ( isFormCorrect == false)
	{
		//someone else failed so I don't need any further validation!
		return true;
	}
	
	o = theField;
	
	if ( typeof o != 'object' )
		return true;
		
	if ( o.value == "" )
		return true;
		
	var eLunghezza = o.value.length;
	var ePosChiocciola = o.value.indexOf('@');
	var ePosUltimaChiocciola = o.value.lastIndexOf('@');
	var ePosPunto = o.value.indexOf('.');
	var ePosUltimoPunto = o.value.lastIndexOf('.');
	var ePosPenultimoPunto = -1;
	
	//alert( o.value.charAt(ePosUltimoPunto) );
	
	
	i = ePosUltimoPunto-1;
	
	while ( i > ePosChiocciola )
	{
		if ( o.value.charAt( i ) == '.' )
		{
			ePosPenultimoPunto = i;
			break;
		}
		i--;
		
	}
	
	//alert(ePosUltimoPunto - ePosPenultimoPunto);
	var reEmailAlphanumeric = /^[._@a-zA-Z0-9]+$/;
	
	if ( 
		(eLunghezza < 7 || ePosChiocciola == -1 || ePosUltimoPunto == -1 ) 	||
		(ePosChiocciola > ePosUltimoPunto ) 					||
		(ePosChiocciola != ePosUltimaChiocciola ) 				||
		( o.value.substring(ePosUltimoPunto,eLunghezza).length < 3 ) 		||
		( ePosChiocciola == 0 ) 						||
		( ( ePosUltimoPunto - ePosChiocciola ) < 3 )				||
		( ( ePosUltimoPunto - ePosPenultimoPunto ) < 3 )			||
		( o.value.indexOf(' ') != -1 )						||
		( reEmailAlphanumeric.test(o.value)==false )
	   ) 
	{
		if ( errorMessage == "" )
			alert(ERROR_IS_BAD_EMAIL);
		else
			alert(errorMessage);
			
		isFormCorrect = false;
		o.focus();
		return false;		
	}
		
}




















/////////////////////////////////UTILITIES /////////////////////////////////////////////

function Trim(inString)
{
  var retVal = "";
  var start = 0;
  while ((start < inString.length) && (inString.charAt(start) == ' ')) {
    ++start;
  }
  var end = inString.length;
  while ((end > 0) && (inString.charAt(end - 1) == ' ')) {
    --end;
  }
  retVal = inString.substring(start, end);
  return retVal;
}


////////////////////////////////////////////////////////////////////////////////////////////////////

function annoBisestile(anno)
{
    div004 = anno % 4;
    
    div100 = anno % 100;
    
    div400 = anno % 400;
    
    if (div400 == 0) // è divisibile anche per 4
        return true;
    
    if(div004 == 0 && div100 >0 ) // se è divisibile per 4 ma non per 100 allora è bisestile
        return true;
    
    return false;
}


////////////////////////////////////////////////////////////////////////////////////////////////////

function maiuscolo(theField)
{
    if ( typeof theField == 'object' )
    {
    	newval = theField.value.toUpperCase();
    	theField.value = newval;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////

function minuscolo(theField)
{
    if ( typeof theField == 'object' )
    {
    	newval = theField.value.toLowerCase();
    	theField.value = newval;
    }
}


////////////////////////////////////////////////////////////////////////////////////////////////////
/*
function formToUpperCase( theForm, exceptThoseFields[])
{
	for (i=0;i<theForm.elements.length;i++)
	{
		o = theForm[i]
		
		if ( exceptThoseFields == null)
		{
			maiuscolo(o);
		}
		else
		{
			for (j=0;j < exceptThoseFields.length; j++ )
			{
				if(  o != theForm.exceptThoseFields[j]  )
					maiuscolo(o);
			}
		}
	}
	
}
*/