/**
* La funzione controlla che nel campo field ci sia un valore diverso da stringa
* vuota. Controlla, cioè, l'obbligatorietà del campo!!!
* Il campo può essere di tipo text, password, textarea, select, select mulitpla
* checkbox e radio.
* Riceve in input:
*   - field: contiene il nome del campo del form da controllare;
*   - fieldName: etichetta utilizzata per il campo nel form.
* Ritorna true se un valore significativo è impostato nel campo, 
* ritorna false altrimenti
*/
function checkNull( field , fieldName) {
  selected = 0;
  fieldIsNull = 0;

  if ( field.type == "text" || field.type == "password" || field.type == "textarea" )
  {
    trim(field);
    if ( field.value == "" )  fieldIsNull = 1;
  } 
  else if ( field.type == "select-one" ) 
  {
    if ( field.selectedIndex <= 0)  fieldIsNull = 1;
  } 
  else if ( field.type == "select-multiple" ) 
  {
    fieldIsNull = 1;
    for ( i = 0; i < field.length; i++ )
      if ( field.options[i].selected ) fieldIsNull = 0;
  } 
  else if ( typeof(field.type) == "undefined" || field.type == "checkbox" || field.type == "radio" ) 
  {
    fieldIsNull = 1;
      /*Se c'è una sola checkbox field.type è checkbox e field.length è undefined,
       *si verifica quindi se field.checked è true.
       *Se ci sono piu' checkbox con lo stesso nome typeof(field.type) è undefined,
       *ma field.length è realmente il numero delle checkbox, si verifica
       *quindi con il for se c'e' almeno un elemento selezionato
      */
    if (field.type == "checkbox") //Una sola checkbox
    {
      if (field.checked) fieldIsNull = 0;
    } 
 
    //Entra nel for solo se ci sono piu' checkbox con lo stesso nome
    for ( i = 0; i < field.length; i++ )
    {  
      if ( field[i].checked ) fieldIsNull = 0;
    }
  }
  if ( fieldIsNull ) 
  {
      if ( typeof(fieldName) == "undefined" )
       {
         alert( " Deve essere impostato." );
       }
      else
       {
         alert("Il campo <" + fieldName + "> deve essere impostato." );
       }         
      if ( field.type == "text" ||
           field.type == "textarea"  ||
           field.type == "password"  ||
           field.type == "select-one"  ||
           field.type == "select-multiple" )
           {
            field.focus();
           }
      else //Anche per checkbox e radio
        {
          if (field.length >0)
          {
            field[0].focus();
          }
          else field.focus();
        }
        //field.select();
     return false;
  }
  return true;
}

/**
* La funzione controlla che nel campo field ci sia un valore diverso da stringa
* vuota. Controlla, cioè, l'obbligatorietà del campo!!!
* Il campo può essere di tipo text, password, textarea, select, select mulitpla
* checkbox e radio.
* Riceve in input:
*   - field: contiene il nome del campo del form da controllare;
*   - fieldName: etichetta utilizzata per il campo nel form.
* Ritorna true se un valore significativo è impostato nel campo, 
* ritorna false altrimenti. NON STAMPA MESSAGGIO DI ERRORE.
*/
function checkNullNoMsg( field , fieldName) {
  selected = 0;
  fieldIsNull = 0;

  if ( field.type == "text" || field.type == "password" || field.type == "textarea" )
  {
    if ( field.value == "" )  fieldIsNull = 1;
  } 
  else if ( field.type == "select-one" ) 
  {
    if ( field.selectedIndex <= 0)  fieldIsNull = 1;
  } 
  else if ( field.type == "select-multiple" ) 
  {
    fieldIsNull = 1;
    for ( i = 0; i < field.length; i++ )
      if ( field.options[i].selected ) fieldIsNull = 0;
  } 
  else if ( typeof(field.type) == "undefined" || field.type == "checkbox" || field.type == "radio" ) 
  {
    fieldIsNull = 1;
    for ( i = 0; i < field.length; i++ )
    {  
      if ( field[i].checked ) fieldIsNull = 0;
    }
  }
  if ( fieldIsNull ) 
  {
      /*if ( typeof(fieldName) == "undefined" ) 
         alert( " Deve essere impostato." );
      else  
         alert("Il campo <" + fieldName + "> deve essere impostato." );*/
      if ( field.type == "text" ||
           field.type == "textarea"  ||
           field.type == "password"  ||
           field.type == "select-one"  ||
           field.type == "select-multiple" )
        field.focus();
        //field.select();
     return false;
  }
  return true;
}

/**
*	La funzione verifica che il valore del campo Field
*	sia costituito da caratteri numerici senza alcun altro segno.
*
*	Se il valore non è corretto allora:
*	1.	è visualizzato un messaggio (standard o specificato come
*		parametro)
*	2.	il Focus è applicato al campo
*/
function checkNoSignNumber(Field, Label, messaggio) 
{	
	//	Se nessun valore e' stato specificato il controllo e' assunto OK	
	if (Field.value == "") return true;

	//	Controllo formato
	//	Formato ammesso: stringa di caratteri numerici 
	//						Non sono ammessi spazi in qualsiasi posizione
	if (!checkNumber(Field, Label, messaggio))
	{
		Field.focus();
		return false;
	}
	
	if ( Field.value.match(/^[+-]?\d+$/) && Field.value.substr(0,1) != "+" && Field.value.substr(0,1) != "-"  )
	{
		//	Formato corretto
		return true;
	}
	else
	{
		//	Formato non corretto

		//	Visualizza messaggio
		if	(messaggio == null)
		{
				alert('Il valore del campo <' + Label +
								'> non deve contenere il segno');

		}
		else
		{
			alert(messaggio);
		}

		
		//	Posiziona il cursore sul campo
		Field.focus();
		return false;
	}
}

/**
*	La funzione verifica che il valore del campo Field
*	sia costituito da caratteri numerici.
*
*	NOTA	Sono ammessi numeri con segno (+ o -)
*
*			Non sono ammessi blank in qualunque posizione
*
*	Se il valore non è corretto allora:
*	1.	è visualizzato un messaggio (standard o specificato come
*		parametro)
*	2.	il Focus è applicato al campo
*/
function checkNumber(Field, Label, messaggio) 
{	
	//	Se nessun valore e' stato specificato il controllo e' assunto OK	
	if (Field.value == "") return true;

	//	Controllo formato
	//	Formato ammesso: stringa di caratteri numerici eventualmente
	//						preceduta da segno + oppure meno
	//						Non sono ammessi spazi in qualsiasi posizione
	if	(Field.value.match(/^[+-]?\d+$/))
		{
			//	Formato corretto
			return true;
		}
	else
		{
			//	Formato non corretto

			//	Visualizza messaggio
			if	(messaggio == null)
				{
					alert('Il valore del campo <' + Label +
								'> deve essere numerico');
				}
			else
				{
					alert(messaggio)
				}

	
			//	Posiziona il cursore sul campo
			Field.focus();
   			return false;
		}
}

/**
*	La funzione verifica che la lunghezza del valore del campo Field
*	sia uguale a lunghezza ricevuto in input.
*
*	Se il valore è stringa vuota allora:
*	1.	è visualizzato un messaggio (standard o specificato come
*		parametro)
*	2.	il Focus è applicato al campo
*/
function checkLength(Field, Label, lunghezza, messaggio) 
{	
	//	Se nessun valore e' stato specificato il controllo e' assunto OK
    
	if (Field.value == "") 
    return true;

	//	Controlla la lunghezza del valore del campo
	if (Field.value.length != lunghezza)
	{	
		//	Visualizza messaggio
		if	(messaggio == null)
		{
				alert('Il valore del campo <' + Label + 
						'> deve essere di ' + lunghezza + 
						' caratteri!');
		}
		else
		{
			alert(messaggio);
		}
		//	Posiziona il cursore sul campo
		Field.focus();
		return false;
	}

	return true;
}

/**
*	La funzione verifica che la lunghezza del valore del campo Field
*	sia minore o uguale a lunghezza ricevuto in input.
*
*	Se il valore è stringa vuota allora:
*	1.	è visualizzato un messaggio (standard o specificato come
*		parametro)
*	2.	il Focus è applicato al campo
*/
function checkMaxLength(Field, Label, lunghezza, messaggio) 
{	
	//	Se nessun valore e' stato specificato il controllo e' assunto OK
    
	if (Field.value == "") 
    return true;

	//	Controlla la lunghezza del valore del campo
	if (Field.value.length > lunghezza)
	{	
		//	Visualizza messaggio
		if	(messaggio == null)
		{
				alert('Il valore del campo <' + Label + 
						'> deve essere al massimo di ' + lunghezza + 
						' caratteri!');
		}
		else
		{
			alert(messaggio);
		}
		//	Posiziona il cursore sul campo
		Field.focus();
		return false;
	}

	return true;
}



/**
* La funzione verifica il formato di una data, nel senso che controlla:
* - la correttezza del formato in termini gg-mm-aaaa
* - la correzza dei mesi,giorni e anno
* Riceve in input:
*   - Field: contiene il nome del campo del form da controllare;
*   - Label: etichetta utilizzata per il campo nel form.
* Ritorna true se la data è corretta e significativa, 
* ritorna false altrimenti
*/
function verificaFormatoData(Field, Label)
{
	if (Field.value == '') return true; 
// se la data è obbligatoria sarà chiamata prima la isNull e quindi qui il controllo non va fatto
	errore = 0;
	//OLD: corretta =/^\d?\d[ /.-]\d?\d[ /.-]\d\d\d\d$/.test(Field.value);
	var t1 = /^\d?\d[ /.-]\d?\d[ /.-]\d\d\d\d$/;
	var reg1 = new RegExp(t1);

	corretta = reg1.test(Field.value);

	if	(!corretta)
	{
		errore = 1; // errore sul formato della data
	}
	else
	{
	dataInp = Field.value
	if	(dataInp.charAt(1) == ' ' || dataInp.charAt(1) == '/' ||
			dataInp.charAt(1) == '-' || dataInp.charAt(1) == '.')
				dataInp = '0' + dataInp 
		if (dataInp.charAt(4) == ' ' || dataInp.charAt(4) == '/' ||
			dataInp.charAt(4) == '-' || dataInp.charAt(4) == '.')
				dataInp = dataInp.substring(0,3) + '0' + dataInp.substring(3,9) 
		if (dataInp.charAt(2) != dataInp.charAt(5))
			errore = 2
		else
		{
			
      giorno	= dataInp.substring(0, 2)
			mese	= dataInp.substring(3, 5)
			anno	= dataInp.substring(6, 10)
      
      if (mese > 0 && mese < 13 && giorno > 0 && giorno < 32)
			{
				if (mese == 11 || mese == 4 || mese == 6 || mese == 9) 
				{
					if (giorno > 30) 
						errore = 2
				}
				if (mese == 2)
				{
					//resto = anno % 4;
					resto = 1;
					if (((anno % 4 == 0) && (anno % 100 != 0)) || (anno % 400 == 0))
					{// se è un anno bisestile imposto resto a zero altrimenti lo lascio a uno
						resto = 0;
					}
					
					if (resto == 0 && giorno > 29)
						errore = 2
					else
					{
						if (resto != 0 && giorno > 28)
						errore = 2
					}
				}
			}
			else 
				errore = 2
		}
	}
	if (errore!= 0)
	{
		if (errore == 1) 
		{
		msg = "Il valore del campo <"+Label+"> non contiene un formato valido di data.\nImmettere la data nel formato gg/mm/aaaa.";
		}
		else 
		{
		msg = "Il valore del campo <"+Label+"> non contiene una data valida.\nImmettere la data nel formato gg/mm/aaaa.";
		}
		alert(msg)
		Field.focus();
	return false;
	}
	else
	{ 
    //Imposto i delimitatori uguali a "/" in dataInp
    //per forzare il formato a gg/mm/aaaa nel campo del form
    dataInp = giorno + '/' + mese + '/' + anno
		Field.value = dataInp;
		return true;
	}
}

/**
* La funzione verifica che Ente di Appartenenza e Ruoli siano
* entrambi vuoti o entrambi pieni
* Riceve in input:
*   - Field1: nome del campo del form corrispondente all'Ente di Appartenenza;
*   - Field2: nome del campo del form corrispondente ai ruoli;
*   - Label1: etichetta utilizzata per il campo nel form relativo alla all'Ente di Appartenenza;
*   - Label2: etichetta utilizzata per il campo nel form relativo alla ai ruoli;
* Se la verifica ha successo ritorna true, altrimenti ritorna false.

*/

function verificaEnteRuoli(field1, field2,field1Name, field2Name)
{
  if ((checkNullNoMsg( field1 , field1Name) && checkNullNoMsg( field2, field2Name)) ||
      (!checkNullNoMsg( field1 , field1Name) && !checkNullNoMsg( field2, field2Name)))
      
      //msg = "Field1.value= "+Field1.value + "Field2.value= "+Field2.value;
      //alert(msg);
      //if (((Field1.value == '') && (Field2.value == '')) ||((Field1.value != '') && (Field2.value != ''))) 
      return true;
  else
    if (!checkNullNoMsg( field1 , field1Name))
      {
      msg = "Ente di Appartenenza obbligatorio nel caso di attribuzione di ruoli di Sistema";
      alert(msg);
      field1.focus();
      return false;
      }
     else 
      {
      msg = "Selezionare almeno un ruolo di Sistema";
      alert(msg);
      //field2.focus();
      return false;
      }

}





/**
* La funzione verifica che la data contenuta nel campo Field1 sia diversa da quella
* contenuta nel campo Field2.
* Riceve in input:
*   - Field1: nome del campo del form corrispondente alla prima data;
*   - Field2: nome del campo del form corrispondente alla seconda data;
*   - Label1: etichetta utilizzata per il campo nel form relativo alla 1° data;
*   - Label2: etichetta utilizzata per il campo nel form relativo alla 2° data;
* Se la verifica ha successo ritorna true, altrimenti ritorna false.
* La funzione da per scontato che le date siano nel formato
* gg/mm/aaaa, per cui prima bisogna chiamare sempre la verificadata!!!
*/

function verificaDataDiversaDa(Field1, Field2, Label1, Label2)
{
	if ((Field1.value == '') || (Field2.value == '')) return true;
	if (Field1.value == Field2.value)
		{
		msg = "La data immessa nel campo <"+ Label1 +"> non può essere uguale a quella immessa nel campo <"+Label2+">";
		alert(msg);
		Field1.focus();
		return false;
		}
	return true;

}


/**
* La funzione verifica che la data contenuta nel campo Field1 sia minore o uguale di quella
* contenuta nel campo Field2.
* Riceve in input:
*   - Field1: nome del campo del form corrispondente alla prima data;
*   - Field2: nome del campo del form corrispondente alla seconda data;
*   - Label1: etichetta utilizzata per il campo nel form relativo alla 1° data;
*   - Label2: etichetta utilizzata per il campo nel form relativo alla 2° data;
* Se la verifica ha successo ritorna true, altrimenti ritorna false.
* La funzione da per scontato che le date siano nel formato
* gg-mm-aaaa, per cui prima bisogna chiamare sempre la verificadata!!!
*/
function verificaDataMinoreUgualeDi(Field1, Field2, Label1, Label2)
{
	if ((Field1.value == '') || (Field2.value == '')) return true;
	dataInp1 = Field1.value
	dataInp2 = Field2.value
	giorno1	= dataInp1.substring(0, 2)
	mese1	= dataInp1.substring(3, 5)
	anno1	= dataInp1.substring(6, 10)
	giorno2	= dataInp2.substring(0, 2)
	mese2	= dataInp2.substring(3, 5)
	anno2	= dataInp2.substring(6, 10)
	if (anno1 < anno2) 
		return true;
	else
		if	(anno1 == anno2) // Anni uguali: controllo sui mesi
			if (mese1 < mese2)
				return true;
			else
				if (mese1 == mese2) // Anni e mesi uguali: controllo sui giorni
					if (giorno1 <= giorno2)
						return true;
		msg = "La data immessa nel campo <"+ Label1 +"> non può essere successiva a quella immessa nel campo <"+Label2+">";
		alert(msg);
	Field1.focus();
	return false;
}
  

/**
* La funzione verifica che la stringa contenuta nel campo Field1 sia uguale a quella
* contenuta nel campo Field2 ignorando eventuali maiuscole o minuscole!
* Riceve in input:
*   - Field1: nome del campo del form corrispondente alla prima stringa;
*   - Field2: nome del campo del form corrispondente alla seconda stringa;
*   - Label1: etichetta utilizzata per il campo nel form relativo alla 1° stringa;
*   - Label2: etichetta utilizzata per il campo nel form relativo alla 2° stringa;
* Se la verifica ha successo ritorna true, altrimenti ritorna false.
*/
function verificaStringa1UgualeStringa2(Field1, Field2, Label1, Label2)
{
	  //Carico in variabili temporanee i valori dei campi in UpperCase
    //per controllare che le stringhe siano uguali a prescindere dal case!!!
    campo1 = Field1.value.toUpperCase();
    campo2 = Field2.value.toUpperCase();

    if	(campo1 != campo2) // stringhe diverse
		{
      msg = "Il valore immesso nel campo <"+ Label1 +"> non può essere diverso da quello immesso nel campo <"+Label2+">";
      alert(msg);
      Field1.focus();
      return false;
    }
    return true;
}

/**
* La funzione verifica che la stringa contenuta nel campo Field1 sia diversa 
* da quella contenuta nel campo Field2 ignorando eventuali maiuscole o minuscole!
* Riceve in input:
*   - Field1: nome del campo del form corrispondente alla prima stringa;
*   - Field2: nome del campo del form corrispondente alla seconda stringa;
*   - Label1: etichetta utilizzata per il campo nel form relativo alla 1° stringa;
*   - Label2: etichetta utilizzata per il campo nel form relativo alla 2° stringa;
* Se la verifica ha successo ritorna true, altrimenti ritorna false.
*/
function verificaStringa1DiversoStringa2(Field1, Field2, Label1, Label2)
{
	//Carica in variabili temporanee i valori dei campi in UpperCase
    //per controllare che le stringhe siano diverse a prescindere dal case.
    campo1 = Field1.value.toUpperCase();
    campo2 = Field2.value.toUpperCase();

    if	(campo1 == campo2) 
	{//stringhe uguali
      msg = "Il valore immesso nel campo <"+ Label1 +"> non può essere uguale a quello immesso nel campo <"+Label2+">";
      alert(msg);
      Field1.focus();
      return false;
    }
    return true;
}


/**
* La funzione verifica che l'estensione di un file sia ammessa rispetto alla tipologia file
* contenuta in TipoFile.
* Ritorna true se l'estensione è ammessa, altrimenti ritorna false
*/
function Verifica_Estensione_File(Field, Label, TipoFile){

var estensioniImmaginiAmmesse = new Array("gif", "jpg", "bmp", "jpeg", "pjpeg");
var estensioniVideoAmmesse = new Array("avi", "asf", "wmv", "mpg", "mpeg");
var estensioniAudioAmmesse = new Array("wav", "mp3", "wma", "midi", "au");
//Eliminate per ora zip, htm e rtf perche' non FUNZIONANO!!!
//var estensioniTestoAmmesse = new Array("doc", "xls", "ppt", "pdf", "zip", "html", "htm", "rtf");
var estensioniTestoAmmesse = new Array("doc", "xls", "ppt", "pdf", "zip", "html", "txt");

	if (Field.value == " ") return true;
	var estensione = Field.value.substring(Field.value.lastIndexOf(".") + 1);
	estensioneNonAmmessa = true;
 if (TipoFile == "Immagine")
 {for ( i = 0 ; i < estensioniImmaginiAmmesse.length ; i++)
  {
		if ( estensioniImmaginiAmmesse[i] == estensione.toLowerCase())
		{
			estensioneNonAmmessa = false;
			break;
		}
  }
 }
 if (TipoFile == "Audio")
 {for ( i = 0 ; i < estensioniAudioAmmesse.length ; i++)
  {
		if ( estensioniAudioAmmesse[i] == estensione.toLowerCase())
		{
			estensioneNonAmmessa = false;
			break;
		}
  }
 }
 if (TipoFile == "Video")
 {for ( i = 0 ; i < estensioniVideoAmmesse.length ; i++)
  {
		if ( estensioniVideoAmmesse[i] == estensione.toLowerCase())
		{
			estensioneNonAmmessa = false;
			break;
		}
  }
 }
 if (TipoFile == "Testo")
 {for ( i = 0 ; i < estensioniTestoAmmesse.length ; i++)
  {
		if ( estensioniTestoAmmesse[i] == estensione.toLowerCase())
		{
			estensioneNonAmmessa = false;
			break;
		}
  }
 }
	if ( estensioneNonAmmessa )
	{
		alert("Formato file non ammesso per il campo <" + Label +">.");
		Field.focus();
     //Field.select(); 
		return false;
	} 
	return true;
}

/**
* La funzione verifica che un URL sia sintatticamente corretto,
* o meglio che almeno inizi con http://<stringa>
* Riceve in input:
*   - Field: contiene il nome del campo del form da controllare;
*   - Label: etichetta utilizzata per il campo nel form.
* Ritorna true se la verifica ha successo, 
* ritorna false altrimenti
*/
function VerificaURL(Field, Label){
  var url = /\w+:\/\/\w+/;    
  if (!Field.value.match(url)) {                           
    alert("Il campo <" + Label + "> non contiene un URL sintatticamente corretto." );
    Field.focus();
    return false;
  }
  return true;
}

/**
* La funzione verifica che un indirizzo di eMail sia sintatticamente corretto
* Riceve in input:
*   - Field: contiene il nome del campo del form da controllare;
*   - Label: etichetta utilizzata per il campo nel form.
* Ritorna true se la verifica ha successo, 
* ritorna false altrimenti
*/
function emailCheck (Field, Label) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=Field.value.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

alert("Il campo <" + Label + "> contiene un indirizzo di Mail sintatticamente non corretto.(Controllare @ e .)");
Field.focus();
return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("Nel campo <" + Label +"> il nome utente contiene caratteri non validi!");
Field.focus();
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Nel campo <" + Label +"> il nome del dominio contiene caratteri non validi!");
Field.focus();
return false;
   }
}

// See if "user" is valid 

if (user.match(userPat)==null) {

// user is not valid

alert("Nel campo <" + Label +"> il nome utente non sembra essere un nome valido!");
Field.focus();
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Nel campo <" + Label +"> l'indirizzo IP non e' valido!");
Field.focus();
return false;
   }
}
return true;
}

// Domain is symbolic name.  Check if it's valid.
 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("Nel campo <" + Label +"> il nome del dominio sembra non essere valido!");
Field.focus();
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 && 
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("L'indirizzo del campo <" + Label +"> deve terminare con un dominio conosciuto (o con le due lettere della Nazione)!");
Field.focus();
return false;
}

// Make sure there's a host name preceding the domain.

if (len<2) {
alert("Nel campo <" + Label +"> manca il nome dell'host!");
Field.focus();
return false;
}

// If we've gotten this far, everything's valid!
return true;
}

/**
*	La funzione elimina i blank (in testa e in coda) nel value del 
* campo Field ricevuto in input
*/
function trim(Field)
{
	while(''+Field.value.charAt(Field.value.length-1)==' ')Field.value=Field.value.substring(0,Field.value.length-1); 
	while(''+Field.value.charAt(0)==' ')Field.value=Field.value.substring(1,Field.value.length);
	
}

/**
* La funzione visualizza il rollover su la riga 'idRiga'
*/
function my_rollover(idGif,idRiga) {
	eval('document.punto'+idRiga+'.src="/apulie/img/remark'+idGif+'.gif"');
}

sortitems = 1;  // Automatically sort items within lists? (1 or 0)

function move(fbox,tbox) {
		for(var i=0; i<fbox.options.length; i++) 
    {
		 if(fbox.options[i].selected && fbox.options[i].value != "") 
     {
		  var no = new Option();
		  no.value = fbox.options[i].value;
		  no.text = fbox.options[i].text;
		  tbox.options[tbox.options.length] = no;
		  fbox.options[i].value = "";
		  fbox.options[i].text = "";
		 }
		}
		BumpUp(fbox);
		if (sortitems) SortD(tbox);
}
    
function BumpUp(box)  {
		for(var i=0; i<box.options.length; i++) 
    {
		  if(box.options[i].value == "")  
      {
		    for(var j=i; j<box.options.length-1; j++)  
        {
		      box.options[j].value = box.options[j+1].value;
		      box.options[j].text = box.options[j+1].text;
		    }
		  var ln = i;
		  break;
		  }
		}
		if(ln < box.options.length)  
    {
		  box.options.length -= 1;
		  BumpUp(box);
		}
}

function SortD(box)  {
		var temp_opts = new Array();
		var temp = new Object();
		for(var i=0; i<box.options.length; i++)  
    {
		  temp_opts[i] = box.options[i];
		}
		for(var x=0; x<temp_opts.length-1; x++)  
    {
		  for(var y=(x+1); y<temp_opts.length; y++)  
      {
		   if(temp_opts[x].text > temp_opts[y].text)  
       {
		    temp = temp_opts[x].text;
		    temp_opts[x].text = temp_opts[y].text;
		    temp_opts[y].text = temp;
		    temp = temp_opts[x].value;
		    temp_opts[x].value = temp_opts[y].value;
		    temp_opts[y].value = temp;
			 }
		  }
		}
		for(var i=0; i<box.options.length; i++)  
    {
		  box.options[i].value = temp_opts[i].value;
		  box.options[i].text = temp_opts[i].text;
		}
}
/**************************************
    Controllo del Codice Fiscale
    Linguaggio: JavaScript
***************************************/

function ControllaCF(Field)
{
    cf = Field.value;
    var validi, i, s, set1, set2, setpari, setdisp;
    //if( cf == '' )  return '';
    cf = cf.toUpperCase();
    if( cf.length != 16 )
        {
            msg = "La lunghezza del codice fiscale non è "
                  +"corretta: il codice fiscale deve essere lungo\n"
                  +"esattamente 16 caratteri.\n";
            alert(msg);
            Field.focus();
            return false;
         }
    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for( i = 0; i < 16; i++ )
    {
        if( validi.indexOf( cf.charAt(i) ) == -1 )
            {
            msg = "Il codice fiscale contiene un carattere non valido: '" +cf.charAt(i) +"'.\nI caratteri validi sono le lettere e le cifre.\n";
            alert(msg);
            Field.focus();
            return false;
            }
    }
    set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
    s = 0;
    for( i = 1; i <= 13; i += 2 )
        s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    for( i = 0; i <= 14; i += 2 )
        s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
        {
        msg = "Codice fiscale non corretto:\n"+
            "il codice di controllo non corrisponde.\n";
        alert(msg);
        Field.focus();
        return false;
        }
    return true;
}

/*****************************************
    Controllo della Partita I.V.A.
    Linguaggio: JavaScript
******************************************/

function ControllaPIVA(Field)
{
pi = Field.value;
    if( pi == '' )  return '';
    if( pi.length != 11 )
        {
            msg = "La lunghezza della partita IVA non è " +
            "corretta: la partita IVA dovrebbe essere lunga\n" +
            "esattamente 11 caratteri.\n";
            alert(msg);
            Field.focus();
            return false;
         }

    validi = "0123456789";
    for( i = 0; i < 11; i++ )
    {
        if( validi.indexOf( pi.charAt(i) ) == -1 )
          {
            msg =  "La partita IVA contiene un carattere non valido `" +
                pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n";
            alert(msg);
            Field.focus();
            return false;
         }
    }
    s = 0;
    for( i = 0; i <= 9; i += 2 )
        s += pi.charCodeAt(i) - '0'.charCodeAt(0);
    for( i = 1; i <= 9; i += 2 ){
        c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
        if( c > 9 )  c = c - 9;
        s += c;
    }
    if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
        {
            msg =  "Partita IVA non valida:\n" +
            "il codice di controllo non corrisponde.\n";
            alert(msg);
            Field.focus();
            return false;
         }
  return true;
}

/*****************
Restituisce la data odierna nel formato GG/MM/YYYY
*****************/
function getDataSistema()
{
    var dataSys = new Date();
    anno   = dataSys.getFullYear();
    mese   = (dataSys.getMonth() + 1);
    giorno = dataSys.getDate();
    
    meseFull =  mese;
    if (mese < 10) meseFull = "0" + mese; 
    giornoFull = giorno;
    if (giorno < 10) giornoFull = "0" + giorno;
    oggi = giornoFull + "/" + meseFull + "/" + anno;
    
    return oggi
}

/**
* La funzione verifica che la data contenuta nel campo Field1 
* sia maggiore della data di sistema (data odierna).
* Riceve in input:
*   - Field1: nome del campo del form corrispondente alla data da verificare;
*   - Label1: etichetta utilizzata per il campo nel form relativo alla data da verificare;
* Se la verifica ha successo ritorna true, altrimenti ritorna false.
* La funzione da per scontato che la data sia nel formato
* gg-mm-aaaa, per cui prima bisogna chiamare sempre la verificadata!!!
*/
function verificaDataMaggioreDiSysdate(Field1, Label1)
{
	if (Field1.value == '')  return true;
	dataInp1 = getDataSistema()
	dataInp2 = Field1.value 
	giorno1	= dataInp1.substring(0, 2)
	mese1	= dataInp1.substring(3, 5)
	anno1	= dataInp1.substring(6, 10)
	giorno2	= dataInp2.substring(0, 2)
	mese2	= dataInp2.substring(3, 5)
	anno2	= dataInp2.substring(6, 10)
    
    if (anno1 < anno2) 
		return true;
	else
		if	(anno1 == anno2) // Anni uguali: controllo sui mesi
			if (mese1 < mese2)
				return true;
			else
				if (mese1 == mese2) // Anni e mesi uguali: controllo sui giorni
					if (giorno1 < giorno2)
						return true;
		msg = "La data immessa nel campo <"+ Label1 +"> deve essere successiva alla data odierna.";
		alert(msg);
	Field1.focus();
	return false;
}

/**
* La funzione verifica che la data contenuta nel campo Field corrisponda alla data di
* nascita di un utente maggiorenne.
* Riceve in input:
*   - Field1: nome del campo del form corrispondente alla data di nascita;
* La funzione calcola la differenza tra gli anni della data di nascita e della
* data di sistema, poi verifica se giorno e mese della data attuale sono inferiori alla 
* data di nascita. In caso positivo un anno dev'essere detratto dagli anni appena
* calcolati, altrimenti tale differenza rappresenta già l'età corrispondente alla
* data di nascita ricevuta in input.
* Se l'età cosi' calcolata risulta inferiore a 18 allora la funzione ritorna false,
* altrimenti ritorna true.
* La funzione da per scontato che le date siano nel formato
* gg-mm-aaaa, per cui prima bisogna chiamare sempre la verificadata!!!
*/
function verificaMaggioreEta(Field)
{

	dataNascita   = Field.value
	giornoNascita	= dataNascita.substring(0, 2)
	meseNascita	= dataNascita.substring(3, 5)
	annoNascita	= dataNascita.substring(6, 10)	

	dataOdierna = getDataSistema()
	
	giornoOdierno	= dataOdierna.substring(0, 2)
	meseOdierno	= dataOdierna.substring(3, 5)
	annoOdierno	= dataOdierna.substring(6, 10)
	
	anni= annoOdierno - annoNascita
	detr=0
	if (meseOdierno < meseNascita) detr=-1
	else
		if (meseOdierno == meseNascita)
		{
		 if (giornoOdierno < giornoNascita) detr=-1
		}
	anni=anni + detr	
	if(anni<18) 
  {
  	msg = "Per registrarsi al Portale dei Servizi Apulie è necessario essere maggiorenni";
    alert(msg);
    Field.focus();
    return false;
	}
	else 
  {
		//alert("Hai "+anni+ " anni")
    return true;
	}
}

/**
* La funzione controlla se viene dato il consenso al trattamento dei
* dati personali secondo la normativa sulla Privacy.
* Riceve in input:
*   - field: contiene il nome del campo del form da controllare (lista di "radio button")
*   - valueOfACCETTO: valore stringa indicante l'assenso al trattamento dei dati personali
* Ritorna true se il valore significativo (assenso accordato) è impostato nel campo field 
* ritorna false altrimenti
*/
function checkConsensoTrattamentoDati(field, valueOfACCETTO) {
    consensoAccordato = 0
    for (i = 0; i < field.length; i++)
    {  
        if (field[i].checked&&field[i].value==valueOfACCETTO) consensoAccordato = 1;
    }
    if (!consensoAccordato) 
    {
        alert("Prima di proseguire è necessario ACCETTARE gli estremi della legge sulla Privacy ed autorizzare il trattamento dei dati.");
        return false;
    }
    return true;
}

/*La funzione setta il focus sul campo ricevuto in input */
function setFocus(fieldName)
{
      var field = document.getElementsByName(fieldName);
      
      field[0].focus();
}


//___________________________________________________________________________
//  Visualizza messaggio di conferma su richiesta cancellazione Record (FORM)
//____________________________________________________________________________

function get_confirm_on_form(messaggio)
{ 
return confirm(messaggio);
}