// Funzioni per il controllo sintattico dei campi di form
// checkFormRequiredFields() - agosto 2006

// Controlla che i dati obbligatori siano inseriti.
// Riceve in ingresso l'elenco dei campi obbligatori separati da ;

function checkFormRequiredFields( ElencoCampi, nomeForm ) // 'campo1;campo2;campo3', "nomeForm"
{
   
   if (nomeForm=="")
   	nomeForm = "form";
   
   var oForm = eval('document.'+nomeForm);
   
   
   
   var length = oForm.elements.length;
 
   var name, value, lunghezzaCampo;  // contengono il nome, il valore e la lunghezza di ogni entry
   var index = 0;   // indice dei campi dell'intera form
   
   var count = 0;
   var errorLevel = 0;  
   var tipo;
   var messaggio = 'I campi con l\'asterisco (*) sono obbligatori!'
   
   var ElencoCampi_array = ElencoCampi.split(";")

   // per ogni elemento della form
  
 
  while (index < length)
   {      
       count++;
	
	for (loop=0; loop < ElencoCampi_array.length; loop++)
   	{
   	
	 // alert(ElencoCampi_array[loop])

         //legge il nome ed il suo valore
         name  = oForm.elements[index].name;
         
       	  //Controllo se il campo della form è nell'elenco dei campi obbligatori
	  if (name == ElencoCampi_array[loop])
	       
	       {
	       
	       	value = oForm.elements[index].value;
	       	lunghezzaCampo = oForm.elements[index].value.length;	
	       	if ((errorLevel == 0) && (lunghezzaCampo == 0) )  
	       	errorLevel = index+1;
		}
	}

	index++;
   }
   if (errorLevel > 0 ) { 
   		alert(messaggio); 
		return false;
	} 
   return true;
   
}

function checkRequiredFields(ElencoCampi) // 'campo1;campo2;campo3'
{
   return checkFormRequiredFields(ElencoCampi,"");
}


//                             IsNumber(num)
function IsNumber(num,ConsentiDecimali,ConsentiNegativi)
{
   var i = 0;
   var letter;

   while (i < num.length)
   {
      letter = num.charAt(i);
 
      if ((letter == '0') || (letter == '1') || (letter == '2') ||
          (letter == '3') || (letter == '4') || (letter == '5') ||
          (letter == '6') || (letter == '7') || (letter == '8') ||
          (letter == '9') || (ConsentiDecimali && letter == ',') || (ConsentiNegativi && letter== '-'))
      {
         i++;
      }
      else
      {
         return false;
      }
   }
   
   

   return true;
}

//                             isNumberField

// Controlla che la stringa inserita nella casella di testo sia composta
// da soli caratteri numerici. (NB accetta il valore nullo ("") ma non " ").
// La funzione mostra un messaggio di errore ed imposta un valore predefinito
function isNumberField(campo)
{
	 if (!IsNumber(campo.value,false))
	 {
	    alert("Il campo può contenere solamente cifre e non sono consentiti ne numeri negativi ne numeri con decimali!");
		campo.focus(); 
		campo.select();
		return false;
	}    
	else
	{
		return true;
	}
}

function isEuroField(campo)
{
	 if (!IsNumber(campo.value,true) || isNaN_Virgola(campo.value))
	 {
        alert("Il campo può contenere solamente cifre, gli eventuali decimali devono essere inseriti con l'utilizzo della virgola.");
		campo.focus(); 
		campo.select();
		return false;
	}    
	else
	{
		return true;
	}
}

function isEuroField2(campo)
{
	 campo.value = campo.value.replace(".",",");
	 if (!IsNumber(campo.value,true) || isNaN_Virgola(campo.value))
	 {
        alert("Il campo può contenere solamente cifre, gli eventuali decimali devono essere inseriti con l'utilizzo della virgola.");
		campo.focus(); 
		campo.select();
		return false;
	}    
	else
	{
		return true;
	}
}
 

function isFloatField(campo,ConsentiNegativi)
{
	 //if (!IsNumber(campo.value,true,true) || isNaN(campo.value) ) 
     if (!IsNumber(campo.value,true,true) || isNaN_Virgola(campo.value)) 
	 {
	    alert("Il campo può contenere solamente cifre, gli eventuali decimali devono essere inseriti con l'utilizzo della virgola.");
		campo.focus(); 
		campo.select();
		return false;
	}    
	else
	{
		
        return true;
	}
}

function isFloatField2(campo,ConsentiNegativi) // sostituisce anche i punti in virgole
{
	 campo.value = campo.value.replace(".",",");
	 
	 //if (!IsNumber(campo.value,true,true) || isNaN(campo.value) ) 
     if (!IsNumber(campo.value,true,true) || isNaN_Virgola(campo.value)) 
	 {
	    alert("Il campo può contenere solamente cifre, gli eventuali decimali devono essere inseriti con l'utilizzo della virgola.");
		campo.focus(); 
		campo.select();
		return false;
	}    
	else
	{
		
        return true;
	}
}

function isDateField(date_field, desc, CheckSQLServerDateTimeRange) {
		
	 if (!date_field.value)  
	 	return true;
	 var in_date = stripCharString(date_field.value," ");
	 
	 var date_is_bad = 0;  
	 if (!allowInString(in_date,"/0123456789"))
		date_is_bad = 1; // caratteri non validi

	 if (!date_is_bad) 
	 {
	         var date_pieces = new Array();
	         date_pieces = in_date.split("/");
			 //alert(date_pieces.length);
	         if (date_pieces.length == 2) {
	                 var d = new Date();
					 //alert(d+' '+d.getFullYear());
	                 in_date = in_date + "/" + d.getFullYear();
					 //alert(in_date);
	                 date_pieces = in_date.split("/");
	         }
	         if (date_pieces.length != 3 || parseInt(date_pieces[0],10) < 1 || parseInt(date_pieces[0],10) > 31 
	                         || parseInt(date_pieces[1],10) < 1 || parseInt(date_pieces[1],10) > 12 
	                         || (date_pieces[2].length != 2 && date_pieces[2].length != 4 && date_pieces[2].length != 3)) {
	                 date_is_bad = 6;  // data non nel formato g/m/a
	         }
	 }
	 if (date_is_bad) {
	         alert(desc + " deve essere nel formato gg/mm/aa oppure gg/mm/aaaa.");
	         date_field.focus();
	         return (false);
	 }
	// scambio il mese con l'anno per il parse
	 if (date_pieces[2].length<4)
	 {
	 	date_pieces[2] = eval(date_pieces[2])+2000;
	 }
	 in_date = date_pieces[1] + "/" + date_pieces[0] + "/" + date_pieces[2];
	 var ms = Date.parse(in_date);
	 var d = new Date();
	 d.setTime(ms);
	 //alert(d);
	var return_date = d.toLocaleString();
	//alert(return_date);
	var return_month = parseInt(d.getMonth() + 1).toString();
	return_month = (return_month.length==1 ? "0" : "") + return_month; 
	var return_date =  parseInt(d.getDate()).toString();
	return_date = (return_date.length==1 ? "0" : "") + return_date; 
	var anno =  d.getFullYear(); // get_full_year(d,date_pieces[2])
	return_date = return_date + "/" + return_month + "/" + anno;

	if ( !CheckSQLServerDateTimeRange || anno >= 1760  ) 
	{
		date_field.value = return_date;
	     return true;
	}
	else
	{
		alert(desc + " non può essere inferiore all'anno 1760.");		
		return (false);
	}
}


function get_full_year(d,AnnoInStringa) 
{
/*
	AnnoInStringa deve essere una stringa (non è obbligatorio ma se non viene specificato, non viene sistemato il bug 
	descritto successivamente (*)
*/
	var y = ""
	//	Estraggo l'anno scritto nella data (2 o 4 cifre)
	y = d.getYear();
	//alert('y:'+y);
	//alert('getfullyear:'+d.getFullYear());
	/*	
		(*) Si noti che se è stato scritto un numero compreso tra 1900 e 1999 la funzione ritorna il valore in modulo a 100 (00-99)
		pertanto si rende necessario il controllo successivo. 	
	*/
	if (y>=0 && y<100 && d.getFullYear() >= 1900 && d.getFullYear() < 2000 && AnnoInStringa.length==4 )
		y += 1900;

	// Sistemo il secolo per l'anno a due cifre
	if (y <= 69)
	{
		y += 2000;
	}
	else
		if (y > 69 && y < 100)
			y += 1900;
	
	// eseguo il padding a 4 cifre
	y = (y.length==1 ? "000" : "")+y;
	y = (y.length==2 ? "00" : "")+y;
	y = (y.length==3 ? "0" : "")+y;

	return y;
}

function stripCharString (InString, CharString)  {
	var OutString="";
   	for (var Count=0; Count < InString.length; Count++)
	{
    	var TempChar=InString.substring (Count, Count+1);
      	var Strip = false;
      	for (var Countx = 0; Countx < CharString.length; Countx++)
		{
        	var StripThis = CharString.substring(Countx, Countx+1)
         	if (TempChar == StripThis)
			{
            	Strip = true;
            	break;
         	}
      	}
      	if (!Strip)
        	OutString=OutString+TempChar;
   }
   return (OutString);
}
function allowInString (InString, RefString)  {
        if(InString.length==0) return (false);
        for (var Count=0; Count < InString.length; Count++)  {
        var TempChar= InString.substring (Count, Count+1);
      if (RefString.indexOf (TempChar, 0)==-1)  
        return (false);
   }
   return (true);
}

function ControllaLunghezzaMassima(x,l)
{
	 
	if (x.value.length > l)
	{
		alert( "Il campo non può contenere più di " + l + " caratteri!");
		x.value = x.value.substring(0,l);
		return false;
	}
	else
		return true;
}

/*
isNaN_Virgola esegue ha lo stesso funzionamento di isNaN prevista dal Javascript standard ma
              vuole in input un numero che utilizzi le virgole come separatore dei decimali.

              Esempio: isNaN_Virgola('1.0')  -> true
                       isNaN_Virgola('1,0')  -> false
                       isNaN_Virgola('1,,0') -> true
                       isNaN_Virgola('1354743,06') -> falso
*/
function isNaN_Virgola(numero)
{
    x = numero.replace('.','§');
    x = x.replace(',','.');
    x = x.replace('§',',');
    return isNaN(x);
}

// ++ 06-02-2002
function isEmailField(campo)
{
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
	
	if (filter.test(campo.value) || campo.value=='') 
		return true;
	else 
	{
	    alert("Un indirizzo di posta deve essere nel formato utente@dominio.ext");
		campo.focus(); 
		campo.select();
		return false;
	}    
}

function Punto2Virgola(campo)
{
	// esempio utilizzo: onKeyUp="javascript:Punto2Virgola(this)"
	campo.value = campo.value.replace(".",",");
}
