// Funzioni di supporto

function EvidenziaCampo(nomeEstesoCampo){	//Matteo 18-01-10
	nomeEstesoCampo.focus();
	//nomeEstesoCampo.style.background = "#FFE1E1";
	nomeEstesoCampo.style.borderColor="#FF0000";
	nomeEstesoCampo.style.borderWidth="3px";
}

function TogliEvidenziaCampo(nomeEstesoCampo){	//Matteo 19-01-10
	nomeEstesoCampo.style.borderColor="#CCC";
	nomeEstesoCampo.style.borderWidth="1px";
}

var cifre = '0123456789';
var telefono = '-+/.0123456789 ';

function check_num(stringa){
  i=0
  buona=true
  while(i<stringa.length){
    car=stringa.substring(i,i+1);
    if(cifre.indexOf (car) == -1)
      {buona=false; break;}
  i++}
  return(buona);
}

function check_obbl(campo,nome_campo,lungh)
{
if (campo.value == "")
{
	alert("Sezione 1:\ninserire un valore per il campo " + nome_campo);
	campo.focus();
	return (false);
}
ok=WordCount(campo);
if (ok==0) return(false);
	if (campo.value.length > lungh)
	{
		alert("Sezione 1:\ninserire al massimo " + lungh + " caratteri nel campo "+ nome_campo);
		campo.focus();
		return (false);
	}
	return true;
}

function imgerr(idimg,opt) {
if (opt=="M") {
	document.getElementById('img_' + idimg).style.display = 'block';
	document.getElementById('img_' + idimg).style.visibility= 'visible';
}
if (opt=="N") {
	//document.getElementById('img_' + idimg).style.display = 'none';
	document.getElementById('img_' + idimg).style.visibility= 'hidden';
}

}

function check_prov(campo,nome_campo)
{
	prov= "AOTOVCNOATCNALMICRSOBSBGPVMNCOVATSGOUDPNPDVEVRVIBLROTVFEPCPRREMOBOFORAIMSVGESPMSLUPTFILIPIARSIGRTRPGPSANAPMCPECHAQTERMRIVTLTFRCENAAVSABNCBISFGBABRLETAPZMTCSCZRCSRPATNSSNUCAORBZTPMEAGCLENCTRGSMLOPORNLCVVBIVBKR";

	if (campo.value.length != 2)
	{  
		alert("Sezione 1:\nil campo relativo alla " + nome_campo + " deve essere pari a 2 caratteri.");
		campo.focus();
		return (false);
	}  
	else
	{
		/*CONTROLLO ESISTENZA IN TABELLA*/
		for (var i=0,cp=0; i<prov.length; i=i+2)
		{
			thischar=prov.substring(i,i+2);
			if (thischar==campo.value.toUpperCase())
			cp=1;
		}
		if (cp==0)
		{
			alert("Sezione 1:\nil valore inserito nel campo " +nome_campo+ " non è la sigla di nessuna provincia italiana.");
			campo.focus();
			return (false);
		}
	}
	return true;
}

function check_data(campog,campom,campoa)
{
  var tod=new Date();
 
  if (campog.value.length != 2)
  {  
    //alert("Sezione A:\nil campo relativo al 'Giorno' deve essere 2 cifre.");
    //campog.focus();
    return (false);
  }  
  else
  {
    if (!isanum(campog.value)) 
    {
      //alert("Sezione A:\nil campo 'Giorno' non è valido")
      //campog.focus();
      return (false);  
     }
 
  }   
  if ((campog.value>31)||(campog.value<1))
  {  
    //alert("Sezione A:\nil valore del campo relativo al 'Giorno' non è corretto.");
    //campog.focus();
    return (false);
  }  

  /*MESE*/
  if (campom.value != "")
  {
    if (campom.value.length != 2)
    {  
      //alert("Sezione A:\nil campo relativo al 'Mese' deve essere 2 cifre.");
      //campom.focus();
      return (false);
    }  
    else
    {
      if (!isanum(campom.value)) 
      {
        //alert("Sezione A:\nil campo 'Mese' non è valido");
        //campom.focus();
        return (false);
       }
    }   
    if ((campom.value>12)||(campom.value<1))
    {  
      //alert("Sezione A:\nil valore del campo relativo al 'Mese' non è corretto.");
      //campom.focus();
      return (false);
    }  
  }

 /*ANNO*/
  if (campoa.value != "")
  {
    if (campoa.value.length != 4)
    {  
      //alert("Sezione A:\nil campo relativo all' 'Anno' deve essere 4 cifre.");
      //campoa.focus();
      return (false);
    }  
    else
    {
      if (!isanum(campoa.value))
      {
        //alert("Sezione A:\nil campo 'Anno' non è valido");
        //campoa.focus();
        return (false);
      }

      year=tod.getYear();
      var2000=946598400
      var1970=tod.getTime()/1000;
      if (var1970<var2000)
        year="19"+year;

//      if (campoa.value>year)
//      {
//        alert("Il campo relativo all' ANNO non è corretto.");
//        campoa.focus();
//        return (false);
//      }
    }   
  }
  /*ACCORPAMENTO VALORI DATA */
 
  if((campog.value!="")&&(campom.value!="")&&(campoa.value!=""))
  {
    // campoc.value=campog.value+"/"+campom.value+"/"+campoa.value;
  }
  else if((campog.value!="")||(campom.value!="")||(campoa.value!=""))
  {

    //alert("Sezione A:\nla 'Data' è incompleta.");
    //campog.focus();
    return (false);
  }
  else
  {
    // campoc.value="";
  }

return true;

}

function check_data_ipo(gg,mm,aaaa)
{

dataok=true;

//controllo che siano tutti numeri
	if(! ( check_num(gg) && check_num(mm) && check_num(aaaa) ) )
		dataok = false;

//controllo Giorno (compreso fra 1 e 31)
	if (! (gg>0) && (gg<32))
		dataok = false;
	   	
//controllo Mese (compreso fra 1 e 12)
	if (! (mm>0) && (mm<13))
		dataok = false;
	   	
	   	
//controllo Anno (maggiore di 1900)
	if (!(aaaa>1899))
		dataok = false;

//controllo Anno (minore di 1999)
	if (!(aaaa<9999))
		dataok = false;


  return(dataok);


}

function isanum(campo)
{

  for (var i=0,counter=0; i<campo.length; i++)
    {
      thischar=campo.substring(i,i+1);
     if (thischar=='0' || thischar=='1' || thischar=='2' || thischar=='3' || thischar=='4' || thischar=='5' || thischar=='6' || thischar=='7' || thischar=='8' || thischar=='9') counter++;
    }
  if (counter!=campo.length)
    {
      return (false);
    }
return true;
}

function WordCount(campo)
{
	
	var pos = 0;
	var count = 0;
	
	while (campo.value.charAt(pos)==" ")
	{
    	pos++;
	}
	
  	while ((pos < campo.value.length)&&(pos>=0)) 
	{
		pos = campo.value.indexOf(" ", pos);
		while ((campo.value.charAt(pos)==" ")&&(pos>=0))
		{
			pos++; 
		}
		count++;
	}
	
	return count;
}

function trim(sString) {
	while (sString.substring(0,1) == ' ')
		{
			sString = sString.substring(1, sString.length);
		}
	while (sString.substring(sString.length-1, sString.length) == ' ')
		{
			sString = sString.substring(0,sString.length-1);
		}
	return sString;
}

function codiceFISCALE(cfins)
   {
   var cf = cfins.toUpperCase();
   var cfReg = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
   if (!cfReg.test(cf))
      return false;
   var set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   var set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
   var setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   var setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
   var 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) )
      return false;
   return true;
   }

function partitaIVA(iva) {
    var DUB;
    var DAB = new Array(2);
    var NUMO = new Array(11);
    var i;
    var TOTDIS = 0;
    var TOTPAR = 0;
    var NUMERO;
    var tmp;
    var n;
    
    for (i=0;i<=10;i=i+1) {    
    	NUMO[i] = parseInt(iva.charAt(i));
    }
    
    for (i=0;i<=8;i=i+2) {    
    	TOTDIS = TOTDIS + NUMO[i];
    }

    for (i=1;i<=9;i=i+2) {    
    	DUB = NUMO[i];
    	DUB = DUB * 2;
    	if (DUB<10) {
	    	TOTPAR = TOTPAR + DUB;    	
    	} else {
    		TOTPAR = TOTPAR + (DUB-10) + 1;    	
    	}
    }
	DUB = TOTPAR + TOTDIS;   
	
	tmp = DUB + "";
	if (DUB <= 10) {
		n=DUB; }
	else {
		n=parseInt(tmp.charAt(1))
	}
	NUMERO = 10 - n;    

    tmp = NUMERO + "";
    
	if (NUMERO <= 9) {
		n=NUMERO; }
	else {
		n=parseInt(tmp.charAt(1))
	}
    
    if (n == NUMO[10]) {
    	return true; } 
    else {
    	return false;
    }    	
}

function codiceFISCALE2(cfins, C, N) {
   var cf = cfins.toUpperCase();
   var Cog = C.toUpperCase();
   var Nom = N.toUpperCase();
   var strcognome;
   var strnome;
   var tmpcf;

strcognome = '';
strnome = '';
	
// verifico se il cod. fiscale inserito è congruo con cognome e nome

    for (i=0; i< Cog.length; i++) 
        {
         switch (Cog.charAt(i)) 
                {
                  case 'A':
                  case 'E':
                  case 'I':
                  case 'O':
                  case 'U': break;            
                  default : 
                  if((Cog.charAt(i)<='Z')&& (Cog.charAt(i)>'A'))
                   strcognome = strcognome + Cog.charAt(i);
                }
        }
    if (strcognome.length < 3) 
      {
       for (i=0; i<Cog.length; i++) 
          {
           switch (Cog.charAt(i)) 
                 {
                  case 'A':
                  case 'E':
                  case 'I':
                  case 'O':
                  case 'U': strcognome = strcognome + Cog.charAt(i);
                 }
          }
       if (strcognome.length < 3) 
         {
          for (i=strcognome.length; i<=3; i++) 
             { strcognome = strcognome + 'X'; }
         }
      }
   strcognome = strcognome.substring(0,3);
 //------------------------------------------------------------    
   
   
  // processa il nome
  //----------------------------------------------------------------
    for (i=0; i<Nom.length; i++) 
       {
        switch (Nom.charAt(i)) 
              {
               case 'A':
               case 'E':
               case 'I':
               case 'O':
               case 'U': break;
               default:
 if((Nom.charAt(i)<='Z')&& (Nom.charAt(i)>'A'))
                  strnome = strnome + Nom.charAt(i);
              }
       }
    if (strnome.length > 3) 
      {
        strnome = strnome.substring(0,1) + strnome.substring(2,4);
      } 
    else {
          if (strnome.length < 3) 
            {
             for (i=0; i<Nom.length; i++) 
                {
                  switch (Nom.charAt(i)) 
                        {
                         case 'A':
                         case 'E':
                         case 'I':
                         case 'O':
                         case 'U': strnome = strnome + Nom.charAt(i);
                        }
                }
             if (strnome.length < 3) 
               {
                for (i=strnome.length; i<=3; i++) 
                   {strnome = strnome + 'X';}
               }
            }
          strnome = strnome.substring(0,3);
         }
 //--------------------------------------- Fine processa nome   
   tmpcf = strcognome + strnome;
   
   if (tmpcf != cf.substring(0,6)) {   		
   		return false;
   }	
	
	
	return true;
}

function check_len(stringa,max) {
  return (stringa.length < max);} // falso se ko
  
function check_iva(stringa){
  i=0
  buona=true
  if(stringa.length != 11)
   {return(!buona);}
  while(i<=10){
    car=stringa.substring(i,i+1);
    if(cifre.indexOf (car) == -1)
      {buona=false; break;}
  i++}
  return(buona);
}

function check_letter(stringa){
  i=0
  buona=true
  while(i<stringa.length){
  	car=stringa.substring(i,i+1);
	if(cifre.indexOf (car) != -1){
		buona=false;
		break;
	}
  	i++
  }
  return(buona);
}


function check_tel(stringa)
{  
  i=0
  buona = true
  
  while(i<stringa.length)
  {
    car=stringa.substring(i,i+1);
    if(telefono.indexOf (car) == -1)
    {
      buona=false;
      alert("Sezione B\nCarattere '" + car + "' non valido nel campo 'Telefono'");
      break;
    }
    i++
  }
  //if (stringa.substring(0,1) != '0') {
  //	buona=false;
  //}
  
    return(buona);
}

function check_piva(campo, tipo)
{
      var mese="ABCDEHLMPRST"
      if (tipo=="pi") stringa="PARTITA IVA.";
      if (tipo=="pc") stringa="CODICE FISCALE/PARTITA IVA.";
      if (tipo=="cf") stringa="CODICE FISCALE.";

      if (campo.value == "")
      {
        alert("Sezione A\nInserire un valore per il campo "+stringa );
        campo.focus();
        return (false);
      }

      if ((campo.value.length == 11) && ((tipo=="pi") || (tipo=="pc")))
      { 
      /*CONTROLLO CHE SIA NUMERICO*/
      
        if (!partitaIVA(campo.value))
        {
         if (tipo=="pc")
         {
     	    alert("Sezione A\nIl CODICE FISCALE non è valido");
         }
         else
         {     	
     	    alert("Sezione A\nLa PARTITA IVA non è valida");
         }
         campo.focus
         return (false);
        }
          
      }
      else
      {
        if ((campo.value.length == 16) && ((tipo=="cf")||(tipo=="pc")))
     
        {
          flag=true;

        /*   CONTROLLO NOME E COGNOME     */

          for (var i=0; i<6; i++)
     
            if ((campo.value.charAt(i).toUpperCase()<'A')||(campo.value.charAt(i).toUpperCase()>'Z')) flag=false;
     
        /*   CONTROLLO A_D_N   */

          anno=campo.value.substring(6,8);
          if (!isanum(anno)) flag=false;

        /*   CONTROLLO MESE */

          cmese=campo.value.charAt(8).toUpperCase();
          if (mese.indexOf(cmese)==-1) flag=false;

        /*   CONTROLLO GIORNO  1,31; 41,71  */

          giorno=campo.value.substring(9,11);
          if (!isanum(giorno))
            flag=false;
          else
            if ((giorno<1) || ((giorno>31)&&(giorno<41)) || (giorno>71)) flag=false;

        /*  CONTROLLO CARATTERI RIMANENTI   */

          if ((campo.value.charAt(11).toUpperCase()<'A')||(campo.value.charAt(11).toUpperCase()>'Z')) flag=false;

          if ((campo.value.charAt(15).toUpperCase()<'A')||(campo.value.charAt(15).toUpperCase()>'Z')) flag=false;

          num=campo.value.substring(12,15);

          if (!isanum(num))
            flag=false;

          if (!flag)
          {
            alert("Sezione A\nIl CODICE FISCALE presenta caratteri non validi.");
            campo.focus();
            return (false);
          }
          else
          {      
            if (codiceFISCALE(campo.value)==false)
            {
	            if (!confirm("Sezione A\nIl CODICE FISCALE non è formalmente corretto.\nCliccare su 'Annulla' per correggere il dato oppure\nsu 'OK' per procedere con la richiesta del servizio."))
	            {
		            campo.focus();
		            return (false);
		        }
            }
          }
          
        }

        if ((campo.value.length != 16)&&(campo.value.length != 11) && tipo=="pc")
        {
          alert("Sezione A\nIl campo relativo alla PARTITA IVA / CODICE FISCALE deve essere pari ad 11 o 16 caratteri.");
          campo.focus();
          return (false);
        }
      }

      if ((campo.value.length != 11)&&(tipo=="pi")) 
      {  
        alert("Sezione A\nIl campo relativo alla PARTITA IVA deve essere pari ad 11 caratteri.");
        campo.focus();
        return (false);
      }

      if ((campo.value.length != 16)&&(tipo=="cf")) 
      {
        alert("Sezione A\nIl campo relativo al CODICE FISCALE deve essere pari a 16 caratteri.");
        campo.focus();
        return (false);
      }

    return true;
}

function check_empty(testo)
{
    //falso se vuoto
    return (testo.length>0);
}


/*************************************************************
******** NUOVE FUNZIONI DI SUPPORTO **************************
**************************************************************/

function check_piva2(campo, tipo)
{
      var res = '';
      var mese = 'ABCDEHLMPRST'
      
      try
      {
      if (tipo=='pi') stringa = 'PARTITA IVA.';
      if (tipo=='pc') stringa = 'CODICE FISCALE/PARTITA IVA.';
      if (tipo=='cf') stringa = 'CODICE FISCALE.';

      if (campo.value == "")
      {
        res = 'Inserire un valore per il campo ' + stringa;
        campo.focus();
        return res;
      }

      if ((campo.value.length == 11) && ((tipo=='pi') || (tipo=='pc')))
      { 
      /*CONTROLLO CHE SIA NUMERICO*/
      
        if (!partitaIVA(campo.value))
        {
         if (tipo=='pc')
         {
     	    res = 'Il CODICE FISCALE non è valido';
         }
         else
         {     	
     	    res = 'La PARTITA IVA non è valida'
         }
         campo.focus
         return res;
        }
          
      }
      else
      {
        if ((campo.value.length == 16) && ((tipo=='cf')||(tipo=='pc')))
     
        {
          flag=true;

        /*   CONTROLLO NOME E COGNOME     */

          for (var i=0; i<6; i++)
     
            if ((campo.value.charAt(i).toUpperCase()<'A')||(campo.value.charAt(i).toUpperCase()>'Z')) flag=false;
     
        /*   CONTROLLO A_D_N   */

          anno=campo.value.substring(6,8);
          if (!isanum(anno)) flag=false;

        /*   CONTROLLO MESE */

          cmese=campo.value.charAt(8).toUpperCase();
          if (mese.indexOf(cmese)==-1) flag=false;

        /*   CONTROLLO GIORNO  1,31; 41,71  */

          giorno=campo.value.substring(9,11);
          if (!isanum(giorno))
            flag=false;
          else
            if ((giorno<1) || ((giorno>31)&&(giorno<41)) || (giorno>71)) flag = false;

        /*  CONTROLLO CARATTERI RIMANENTI   */

          if ((campo.value.charAt(11).toUpperCase()<'A')||(campo.value.charAt(11).toUpperCase()>'Z')) flag=false;

          if ((campo.value.charAt(15).toUpperCase()<'A')||(campo.value.charAt(15).toUpperCase()>'Z')) flag=false;

          num = campo.value.substring(12,15);

          if (!isanum(num))
            flag = false;

          if (!flag)
          {
            res = 'Il CODICE FISCALE presenta caratteri non validi.';
            return res;
          }
          else
          {      
            if (codiceFISCALE(campo.value)==false)
            {
                res = 'Il CODICE FISCALE non è formalmente corretto.';
                return res;
            }
          }
          
        }

        if ((campo.value.length != 16)&&(campo.value.length != 11) && tipo=='pc')
        {
          res = 'Il campo relativo alla PARTITA IVA / CODICE FISCALE deve essere pari ad 11 o 16 caratteri.';
          return res;
        }
      }

      if ((campo.value.length != 11)&&(tipo=='pi')) 
      {  
        res = 'Il campo relativo alla PARTITA IVA deve essere pari ad 11 caratteri.';
        return res;
      }

      if ((campo.value.length != 16)&&(tipo=='cf')) 
      {
        res = 'Il campo relativo al CODICE FISCALE deve essere pari a 16 caratteri.';
        return res;
      }

        return '';
    }
    catch(err)
    {
        err.message = 'check_piva2(' + campo + '' + tipo + ') :: ' + err.message;
        throw(err);
    }
}

function check_tel2(stringa)
{  
    try
    {
        i=0;
        var res = '';

        while(i < stringa.length)
        {
        car = stringa.substring(i,i+1);
        if (telefono.indexOf (car) == -1)
        {
              res = 'Carattere ' + car + ' non valido nel campo \'Telefono\'';
              break;
        }
        i++
    }
      
    return res;
    
    }
    catch(err)
    {
        err.message = 'check_tel2(' + stringa + ') :: ' + err.message;
        throw(err);
    }
}

function check_tel3(stringa)
{  
    try
    {
        i=0;
        var res = true;

        while(i < stringa.length)
        {
	        car = stringa.substring(i, i+1);
	        
	        if (telefono.indexOf (car) == -1)
	        {
	              res = false;
	              break;
	        }
	        i++;
	    }
      
    	return res;
    
    }
    catch(err)
    {
        err.message = 'check_tel3(' + stringa + ') :: ' + err.message;
        throw(err);
    }
}


function check_data2(campog, campom, campoa)
{
    try
    {
        if( (campog == '') || (campom == '') || (campoa == '') )
        {
            return false;
        }
        
        //CONTROLLO GIORNO
        if (campog.length < 2)
        {
            return false;
        }  
        else
        {
            if (!isanum(campog)) 
            {
                return false;  
            }
            if ( (campog > 31) || (campog < 1) )
            {
                return false;
            }
        }
        
        //CONTROLLO MESE
        if (campom.length < 2)
        {
            return false;
        }  
        else
        {
            if (!isanum(campom)) 
            {
                return false;
            }
            
            if ( (campom > 12) || (campom < 1) )
            {
                return false;
            }
        }   
        
        var CurrData = new Date();

        //CONTROLLO ANNO
        if (campoa.length < 4)
        {
            return false;
        }  
        else
        {
            if (!isanum(campoa))
            {   
                return false;
            }

            if (campoa < 1900 || campoa > CurrData.getFullYear())
            {
                return false;
            }
        }

        return true;
    }
    catch(err)
    {
        err.message = 'check_data2(' + campog + ', ' + campom + ', ' + campoa + ') :: ' + err.message;
        throw(err);
    }
}


function ReplaceAcc(valstr)
{
	var tmpstr = '';
	tmpstr = valstr.value;
	
	var rr1 = /[\xE0]/g;
	var rr11 = /[\xE1]/g;	
	var rr2 = /[\xE8]/g;
	var rr22 = /[\xE9]/g;	
	var rr3 = /[\xEC]/g;
	var rr33 = /[\xED]/g;	
	var rr4 = /[\xF2]/g;
	var rr44 = /[\xF3]/g;	
	var rr5 = /[\xF9]/g;
	var rr55 = /[\xFA]/g;

	tmpstr = tmpstr.replace(rr1, "a\'");
	tmpstr = tmpstr.replace(rr11, "a\'");	
	tmpstr = tmpstr.replace(rr2, "e\'");
	tmpstr = tmpstr.replace(rr22, "e\'");			
	tmpstr = tmpstr.replace(rr4, "o\'");
	tmpstr = tmpstr.replace(rr44, "o\'");	
	tmpstr = tmpstr.replace(rr3, "i\'");
	tmpstr = tmpstr.replace(rr33, "i\'");	
	tmpstr = tmpstr.replace(rr5, "u\'");
	tmpstr = tmpstr.replace(rr55, "u\'");

	valstr.value = tmpstr;
}

function Replace4Log(valstr)
{
	var tmpstr = "";

	tmpstr = valstr;
	
	var rr1 = /[\xE0]/g;
	var rr11 = /[\xE1]/g;	
	var rr2 = /[\xE8]/g;
	var rr22 = /[\xE9]/g;	
	var rr3 = /[\xEC]/g;
	var rr33 = /[\xED]/g;	
	var rr4 = /[\xF2]/g;
	var rr44 = /[\xF3]/g;	
	var rr5 = /[\xF9]/g;
	var rr55 = /[\xFA]/g;
	var rr8 = /[\x26]/g;
	var rr9 = /[\xb0]/g;

	tmpstr = tmpstr.replace(rr1, "a\'");
	tmpstr = tmpstr.replace(rr11, "a\'");	
	tmpstr = tmpstr.replace(rr2, "e\'");
	tmpstr = tmpstr.replace(rr22, "e\'");			
	tmpstr = tmpstr.replace(rr4, "o\'");
	tmpstr = tmpstr.replace(rr44, "o\'");	
	tmpstr = tmpstr.replace(rr3, "i\'");
	tmpstr = tmpstr.replace(rr33, "i\'");	
	tmpstr = tmpstr.replace(rr5, "u\'");
	tmpstr = tmpstr.replace(rr55, "u\'");
	tmpstr = tmpstr.replace(rr8, ' _amp; ');
	tmpstr = tmpstr.replace(rr9, ' _deg; ');

	return tmpstr;
}

function CStr(ValueToConvertInString) { 
	return String(ValueToConvertInString); 
}

//function Left(StringToLeft, EndOfCount) { 
//	return StringToLeft.substr(0, EndOfCount); 
//}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function Mid(String, Start, Length)
{
    if (String == null)
        return (false);
    
    if (Start > String.length)
        return '';
    
    if (Length == null || Length.length == 0)
        return (false);
    
    return String.substr((Start - 1), Length);
}

function FormatNumber(pnumber,decimals){
	if (isNaN(pnumber)) { return 0};
	if (pnumber=='') { return 0};
	
	var snum = new String(pnumber);
	var sec = snum.split('.');
	var whole = parseFloat(sec[0]);
	var result = '';
	
	if(sec.length > 1){
		var dec = new String(sec[1]);
		dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals)));
		dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
		var dot = dec.indexOf('.');
		if(dot == -1){
			dec += '.'; 
			dot = dec.indexOf('.');
		}
		while(dec.length <= dot + decimals) { dec += '0'; }
		result = dec;
	} else{
		var dot;
		var dec = new String(whole);
		dec += '.';
		dot = dec.indexOf('.');		
		while(dec.length <= dot + decimals) { dec += '0'; }
		result = dec;
	}	
	return result;
}

function DateDiff(date1,date2) {
	return date1.getDay() - date2.getDay();
} 

function InStr(String1, String2) {
	var a = 0;
	if (String1 == null || String2 == null)
	    return (false);
	    String1 = String1.toLowerCase();
	    String2 = String2.toLowerCase();
	    a = String1.indexOf(String2);
	if (a == -1)
	    return 0;
	else
	    return a + 1;
}

function Len(string) {
	if (string == null)
		return (false);
		return String(string).length;
}

function lz(numero, cifre) {
	n = String(numero);
	while (n.length<cifre) { 
		n="0"+n 
	}
	return n;
}


function dateFormat(data, formato) { 

	var giorni = new Array("Domenica", "Lunedi'", "Martedi'", "Mercoledi'", "Giovedi'", "Venerdi'", "Sabato");
	var mesi = new Array("Gennaio", "Febbraio", "marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre");

// preparo la data...  verificare di passarla corretta!
	var adesso = new Date(data); 
	var anno = adesso.getFullYear();
	var mese = adesso.getMonth()+1;
	var giorno = adesso.getDate();
	var settim = adesso.getDay()
	var ore = adesso.getHours()
	var minuti = adesso.getMinutes()
	var secondi = adesso.getSeconds()

// preparo la stringa di risposta
	var rVal = '';

	if (formato.length==0) { 
// assenza del secondo parametro
		return String(adesso); 
	} else {

	// inizio loop
		while (formato.length>0) {

	// verifico se c'e' qualche separatore e lo aggiungo
			while (formato.length>0 && String("ymdphnst").indexOf(formato.charAt(0).toLowerCase())<0) {
				rVal += formato.charAt(0);
				formato = formato.substr(1);
			}


	// Separo il gruppo
			if (formato.length>0) {
				ff = formato.charAt(0);
				formato = formato.substr(1);
				while (formato.length>0 && formato.charAt(0).toLowerCase()==ff.charAt(0).toLowerCase()) {
					ff += formato.charAt(0);
					formato = formato.substr(1);
				}

	// espando il formato nella stringa corrispondente
				ff = ff.toLowerCase();	 // operazione preliminare... tutto in minuscolo
				switch (ff) 	{ 
					case "yy" : 
						rVal += String(anno).substr(2); 
						break; 
					case "yyyy" : 
						rVal += String(anno); 
						break; 
					case "m" : 
						rVal += String(mese); 
						break; 
					case "mm" : 
						rVal += lz(mese,2);
						break; 
					case "mmm" : 
						rVal += mesi[mese-1].substr(0,3);
						break; 
					case "mmmm" : 
						rVal += mesi[mese-1];
						break; 
					case "d" : 
						rVal += String(giorno); 
						break; 
					case "dd" : 
						rVal += lz(giorno,2); 
						break; 
					case "ddd" : 
						rVal += giorni[settim].substr(0,3);
						break; 
					case "dddd" : 
						rVal += giorni[settim];
						break; 
					case "p" : 
						var inizio = new Date(anno, 0, 0); 
						rVal += Math.floor((adesso - inizio) / 86400000);
						break; 
					case "ppp" : 
						var inizio = new Date(anno, 0, 0); 
						rVal += lz(Math.floor((adesso - inizio) / 86400000),3);
						break; 
					case "h" : 
						rVal += String(ore); 
						break; 
					case "hh" : 
						rVal += lz(ore,2); 
						break; 
					case "n" : 
						rVal += String(minuti); 
						break; 
					case "nn" : 
						rVal += lz(minuti,2); 
						break; 
					case "s" : 
						rVal += String(secondi); 
						break; 
					case "ss" : 
						rVal += lz(secondi,2); 
						break; 
					case "t" : 
						rVal += lz(ore,2)+":"+lz(minuti,2)+":"+lz(secondi,2); 
						break; 
					default :  // il numero dei caratteri del formato non e' permesso
						rVal += ff.replace(/./gi,"?");
				} 

			}

		} // fine loop principale

		return rVal;
	}
}

function CheckPagaIva() {
	//Controllo Paga Iva per clienti esteri *** Matteo 30-09-11
    MioForm = document.f;
    if (MioForm.codserv.value != 'POS') {			
		if ((MioForm.IVA4.value == '') && ((MioForm.Stato4.selectedIndex == 18) || (MioForm.Stato4.selectedIndex == 25) || (MioForm.Stato4.selectedIndex == 36) || (MioForm.Stato4.selectedIndex == 58) || (MioForm.Stato4.selectedIndex == 60) || (MioForm.Stato4.selectedIndex == 70) || (MioForm.Stato4.selectedIndex == 75) || (MioForm.Stato4.selectedIndex == 76) || (MioForm.Stato4.selectedIndex == 83) || (MioForm.Stato4.selectedIndex == 224) || (MioForm.Stato4.selectedIndex == 86) || (MioForm.Stato4.selectedIndex == 104) || (MioForm.Stato4.selectedIndex == 118) || (MioForm.Stato4.selectedIndex == 124) || (MioForm.Stato4.selectedIndex == 125) || (MioForm.Stato4.selectedIndex == 133) || (MioForm.Stato4.selectedIndex == 152) || (MioForm.Stato4.selectedIndex == 172) || (MioForm.Stato4.selectedIndex == 173) || (MioForm.Stato4.selectedIndex == 59) || (MioForm.Stato4.selectedIndex == 177) || (MioForm.Stato4.selectedIndex == 189) || (MioForm.Stato4.selectedIndex == 190) || (MioForm.Stato4.selectedIndex == 194) || (MioForm.Stato4.selectedIndex == 204) || (MioForm.Stato4.selectedIndex == 98))) {
			//paga iva
			document.f.PagaIva.value = 'si';										
		}else{
			//non paga iva					
			document.f.PagaIva.value = 'no';
		}
	}
}

function CheckMenuDx() {
	if (document.f.CodCliente.value=='') {		
		if (document.f.PagaIva.value == 'si') {
			document.getElementById('tabNorm').style.visibility = 'visible';
			document.getElementById('tabNorm').style.display = 'block';		
			document.getElementById('tabSc').style.visibility = 'hidden';
			document.getElementById('tabSc').style.display = 'none';
			document.getElementById('tabNormSenzaIva').style.visibility = 'hidden';
			document.getElementById('tabNormSenzaIva').style.display = 'none';
			document.getElementById('tabScSenzaIva').style.visibility = 'hidden';
			document.getElementById('tabScSenzaIva').style.display = 'none';
		}else{
			document.getElementById('tabNorm').style.visibility = 'hidden';
			document.getElementById('tabNorm').style.display = 'none';		
			document.getElementById('tabSc').style.visibility = 'hidden';
			document.getElementById('tabSc').style.display = 'none';
			document.getElementById('tabNormSenzaIva').style.visibility = 'visible';
			document.getElementById('tabNormSenzaIva').style.display = 'block';
			document.getElementById('tabScSenzaIva').style.visibility = 'hidden';
			document.getElementById('tabScSenzaIva').style.display = 'none';
		}	
	}
	if (document.f.CodCliente.value!='') {			
		if (document.f.PagaIva.value == 'si') {
			document.getElementById('tabNorm').style.visibility = 'hidden';
			document.getElementById('tabNorm').style.display = 'none';		
			document.getElementById('tabSc').style.visibility = 'visible';
			document.getElementById('tabSc').style.display = 'block';
			document.getElementById('tabNormSenzaIva').style.visibility = 'hidden';
			document.getElementById('tabNormSenzaIva').style.display = 'none';
			document.getElementById('tabScSenzaIva').style.visibility = 'hidden';
			document.getElementById('tabScSenzaIva').style.display = 'none';	
		}else{
			document.getElementById('tabNorm').style.visibility = 'hidden';
			document.getElementById('tabNorm').style.display = 'none';		
			document.getElementById('tabSc').style.visibility = 'hidden';
			document.getElementById('tabSc').style.display = 'none';
			document.getElementById('tabNormSenzaIva').style.visibility = 'hidden';
			document.getElementById('tabNormSenzaIva').style.display = 'none';
			document.getElementById('tabScSenzaIva').style.visibility = 'visible';
			document.getElementById('tabScSenzaIva').style.display = 'block';
		}
	}
}

function StringToBool(value)
{
	if (value == '' || value == null)
		return value;		
	else if (value == true || value == 'true' || value == 'True' || value == 'TRUE')
		return true;		
	else if (value == false || value == 'false' || value == 'False' || value == 'FALSE')
		return false;
}

function GetComuniFromComIstat(provincia, comuni)
{
	param = new Array(provincia.value);
	var xmlDoc = SendByGetAndBack(param, 'http://www.catastoinrete.it/includes/selectComuniFromComIstat.asp')
	
	if (xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'ko' && xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'no data found')
	{
		//Svuoto la combo comuni prima di inserire i nuovi valori..
		for (var i = comuni.length; i >= 0; i--)
		{
			comuni.options[i] = null;
		}
		
		//..e inserisco il '-->'
		var newOption = new Option('-->','');
		comuni.options[comuni.options.length] = newOption;
		
		//Carico i nuovi valori
		for (i=0; i < xmlDoc.getElementsByTagName("comune").length; i++)
		{
			currComune = xmlDoc.getElementsByTagName("comune")[i].childNodes[0].nodeValue;
			
			var newOption = new Option(currComune, currComune);
			comuni.options[comuni.options.length] = newOption;
		}
	}
}

function GetComuniFromComIstatExceptMandamenti(provincia, comuni)
{
	param = new Array(provincia.value);
	var xmlDoc = SendByGetAndBack(param, 'http://www.catastoinrete.it/includes/selectComuniFromComIstatExceptMandamenti.asp')
	
	if (xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'ko' && xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'no data found')
	{
		//Svuoto la combo comuni prima di inserire i nuovi valori..
		for (var i = comuni.length; i >= 0; i--)
		{
			comuni.options[i] = null;
		}
		
		//..e inserisco il '-->'
		var newOption = new Option('-->','');
		comuni.options[comuni.options.length] = newOption;
		
		//Carico i nuovi valori
		//for (i=0; i < xmlDoc.getElementsByTagName("comune").length; i++)
		//{
		//	currComune = xmlDoc.getElementsByTagName("comune")[i].childNodes[0].nodeValue;
			
		//	var newOption = new Option(currComune, currComune);
		//	comuni.options[comuni.options.length] = newOption;
		//}
		
		for (i=0; i < xmlDoc.getElementsByTagName("dato").length; i++)
		{
			var currCodComune	= xmlDoc.getElementsByTagName("dato")[i].childNodes[0].childNodes[0].nodeValue;
			var currComune		= xmlDoc.getElementsByTagName("dato")[i].childNodes[1].childNodes[0].nodeValue;

			var newOption = new Option(currComune, currCodComune);
			comuni.options[comuni.options.length] = newOption;
		}
	}
}

function GetComuniFromElencoComuni(provincia, comuni)
{
	param = new Array(provincia.value);
	var xmlDoc = SendByGetAndBack(param, 'http://www.catastoinrete.it/includes/selectComuniFromElencoComuni.asp')
	
	if (xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'ko' && xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'no data found')
	{
		//Svuoto la combo comuni prima di inserire i nuovi valori..
		for (var i = comuni.length; i >= 0; i--)
		{
			comuni.options[i] = null;
		}
		
		//..e inserisco il '-->'
		var newOption = new Option('-->','');
		comuni.options[comuni.options.length] = newOption;
			
		//Carico i nuovi valori
		for (i=0; i < xmlDoc.getElementsByTagName("dato").length; i++)
		{
			var currCodComune	= xmlDoc.getElementsByTagName("dato")[i].childNodes[0].childNodes[0].nodeValue;
			var currComune		= xmlDoc.getElementsByTagName("dato")[i].childNodes[1].childNodes[0].nodeValue;

			var newOption = new Option(currComune, currCodComune);
			comuni.options[comuni.options.length] = newOption;
		}
	}
}


function GetNews(bList)
{	
	var xmlDoc = SendByGetAndBack('marino', 'http://www.catastoinrete.it/includes/selectFromNewsOnWebSite.asp')

	if (xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'ko' && xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'no data found')
	{
		var ul = document.getElementById(bList);
		
		//Carico i nuovi valori
		for (i=0; i < xmlDoc.getElementsByTagName("news").length; i++)
		{
			var currUrl			= xmlDoc.getElementsByTagName("news")[i].childNodes[0].childNodes[0].nodeValue;
			var currTitolo		= xmlDoc.getElementsByTagName("news")[i].childNodes[1].childNodes[0].nodeValue;
			var currAbstract	= xmlDoc.getElementsByTagName("news")[i].childNodes[2].childNodes[0].nodeValue;			
	
			//La struttura del nodo é la seguente:
			//	"<span><p class="tit"><b><font color"#336699">" + currTitolo + "</font></b></p></span><a href="currUrl"><p class="10">" + currAbstract + "</p></a>"
			
			
			//Creo il Font interno al B
			fItem = document.createElement("font");
			fItem.setAttribute("color", "#336699");
			fText = document.createTextNode(currTitolo);
			fItem.appendChild(fText);			
			
			
			//creo il B interno al P
			
			bItem = document.createElement("b");
			bItem.appendChild(fItem)
			
			//creo il P interno allo SPAN
			pItem = document.createElement("p");
			pItem.setAttribute("class", "tit2");
			pItem.appendChild(bItem);
			
			//creo lo SPAN
			spanItem = document.createElement("span");
			spanItem.appendChild(pItem);
			
			//creo il P interno allo A
			pItem2 = document.createElement("p");
			pItem2.setAttribute("class", "10");

			pText2 = document.createTextNode(currAbstract);
			pItem2.appendChild(pText2);

			//creo lo A
			aItem = document.createElement("a");
			aItem.setAttribute("href", currUrl);
			aItem.appendChild(pItem2);
			
			//appendo il tutto al nodo
			currItem = document.createElement("li");
			currItem.appendChild(spanItem);
			currItem.appendChild(aItem);
						
			//inserisco il nodo
			ul.appendChild(currItem);			
		}
	}
}

function GetAllNews(placeholder)
{
	var xmlDoc = SendByGetAndBack('marino', 'http://www.catastoinrete.it/includes/selectAllFromNewsOnWebSite.asp')

	if (xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'ko' && xmlDoc.getElementsByTagName("res")[0].childNodes[0].nodeValue != 'no data found')
	{
		var td = document.getElementById(placeholder);
		
		//Carico i nuovi valori
		for (i=0; i < xmlDoc.getElementsByTagName("news").length; i++)
		{
			var currUrl				= xmlDoc.getElementsByTagName("news")[i].childNodes[0].childNodes[0].nodeValue;
			var currTitolo			= xmlDoc.getElementsByTagName("news")[i].childNodes[1].childNodes[0].nodeValue;
			var currAbstract		= xmlDoc.getElementsByTagName("news")[i].childNodes[2].childNodes[0].nodeValue;			
			var currDataInserimento	= xmlDoc.getElementsByTagName("news")[i].childNodes[3].childNodes[0].nodeValue;
			
			//<p>&#8226;  News del 18|10|2011</p>
			pItem1 = document.createElement("p");
			pText1 = document.createTextNode("• News del " + currDataInserimento);
			pItem1.appendChild(pText1);

			//<p><a class="link4" href="/news/riutilizzo_commerciale.asp">Abolita....</a></p>
			
			fItem = document.createElement("font");
			fItem.setAttribute("color", "#336699");
			fText = document.createTextNode(currAbstract);
			fItem.appendChild(fText);				
			
			aItem = document.createElement("a");
			aItem.setAttribute("class", "link4");
			aItem.setAttribute("href", currUrl);
			//pText2 = document.createTextNode(currAbstract);
			//aItem.appendChild(pText2);
			aItem.appendChild(fItem);
			
			pItem2 = document.createElement("p");
			pItem2.appendChild(aItem);
			
			//<img src="../images/LINEA635.gif" width="635" height="1" alt="linea" />
			imgItem = document.createElement("img");
			imgItem.setAttribute("src", "../images/LINEA635.gif");
			imgItem.setAttribute("width", "635px");
			imgItem.setAttribute("height", "1px");
			imgItem.setAttribute("alt", "linea");
			
			//inserisco il tutto
			td.appendChild(pItem1);
			td.appendChild(pItem2);
			td.appendChild(imgItem);
		}
	}
}


function Pasqua(yyyy)
{
	//RITORNA DATA DELLA PASQUA fra il 1800 e il 2199

	if (yyyy < 100)
	{
		yyyy = 2000 + yyyy;
	}
	
	var M = 0;
	var N = 0;
	var Ap = (yyyy % 19);
	var Bp = (yyyy % 4);
	var Cp = (yyyy % 7);
	
	if (yyyy >= 1800 && yyyy <= 1899)
	{
		M = 23;
		N = 4;
	}
	if (yyyy >= 1900 && yyyy <= 2099)
	{
		M = 24;
		N = 5;
	}
	if (yyyy >= 2100 && yyyy <= 2199)
	{
		M = 24;
		N = 6;
	}

	Dp = ((19*Ap + M) % 30);
	Ep = ((2*Bp + 4*Cp + 6*Dp + N) % 7);

	//Calcolo temporaneo
	if ((Dp + Ep) < 10)
	{
		tmpPasqua = (Dp + Ep + 22) + '/3/' + yyyy;
	}
	else
	{
		tmpPasqua = (Dp + Ep -9) + '/4/' + yyyy;
	}
	
	//Eccezioni:
	//	'Se la data risultante dalla formula è il 26 aprile, allora la Pasqua cadrà il giorno 19 aprile;
	//	'Se la data risultante dalla formula è il 25 aprile e contemporaneamente d = 28, e = 6 e a > 10, allora la Pasqua cadrà il 18 aprile.

	if (tmpPasqua == ('26/4/' + yyyy))
	{
	  tmpPasqua = '19/4/' + yyyy;
	}
	
	if (tmpPasqua == ('25/4/' + yyyy) && (Dp == 28) && (Ep == 6) && (Ap > 10) )
	{
		tmpPasqua = '18/4/' & yyyy;
	}

	return tmpPasqua;
}

function is_string(text)
{
    return (typeof(text) == 'string');
}

function anno_bisestile(yyyy)
{
	return (((yyyy % 4 == 0) && ( (!(yyyy % 100 == 0)) || (yyyy % 400 == 0))) ? true : false );
}

function nextNotHoliday(data)
{
	var thisDate = new Date();

	if (is_string(data))
		thisDate = StringToDate(data);
	else
		thisDate = data;

	if (!isWeekEnd(thisDate) && !isHoliday(thisDate))
		return thisDate;
		
	while (true)
	{
		thisDate.setDate(thisDate.getDate() + 1);
		
		if (!isHoliday(thisDate) && !isWeekEnd(thisDate))
			return thisDate;
	}
}

function isWeekEnd(data)
{
	var thisDate = new Date();

	if (is_string(data))
		thisDate = StringToDate(data);
	else
		thisDate = data;		

	// è sabato ?
	if (thisDate.getDay() == 6)
		return true;

	// è domenica ?	
	if (thisDate.getDay() == 0)
		return true;

	return false;
}

function isHoliday(data)
{
	var thisDate = new Date();

	if (is_string(data))
		thisDate = StringToDate(data);
	else
		thisDate = data;		
	
	// è lun pasquetta ?
	var currPasquetta = StringToDate(Pasqua(thisDate.getFullYear()));
	currPasquetta.setDate(currPasquetta.getDate() + 1);
	
	if (thisDate.getDate() == currPasquetta.getDate() && thisDate.getMonth() == currPasquetta.getMonth() && thisDate.getFullYear() == currPasquetta.getFullYear())
		return true;

//alert(thisDate);

	// è festività fissa ?
	if (thisDate.getDate() == 1 && thisDate.getMonth() == 0)
		return true;
	if (thisDate.getDate() == 6 && thisDate.getMonth() == 0)
		return true;
	if (thisDate.getDate() == 17 && thisDate.getMonth() == 1)
		return true;
	if (thisDate.getDate() == 25 && thisDate.getMonth() == 3)
		return true;
	if (thisDate.getDate() == 1 && thisDate.getMonth() == 4)
		return true;
	if (thisDate.getDate() == 2 && thisDate.getMonth() == 5)
		return true;
	if (thisDate.getDate() == 15 && thisDate.getMonth() == 7)
		return true;
	if (thisDate.getDate() == 1 && thisDate.getMonth() == 10)
		return true;
	if (thisDate.getDate() == 8 && thisDate.getMonth() == 11)
		return true;
	if (thisDate.getDate() == 25 && thisDate.getMonth() == 11)
		return true;
	if (thisDate.getDate() == 26 && thisDate.getMonth() == 11)
		return true;
		
	return false;
}

function toWeekDay(data)
{
	var thisDate = new Date();

	if (is_string(data))
		thisDate = StringToDate(data);
	else
		thisDate = data;

	var ret = null;
	switch (thisDate.getDay())
	{
		case 0: { ret = 'Domenica'; break }
		case 1: { ret = 'Lunedi\''; break }
		case 2: { ret = 'Martedi\''; break }
		case 3: { ret = 'Mercoledi\''; break }
		case 4: { ret = 'Giovedi\''; break }
		case 5: { ret = 'Venerdi\''; break }
		case 6: { ret = 'Sabato'; break }
	}	
	
	return ret;
}

function StringToDate(text)
{
	if (text == '' || text == null)
		return null;

	if ((text.indexOf('/') == -1) && (text.indexOf('-') == -1) && (text.indexOf('.') == -1))
		return null;
				
	var temp = null;
	
	if (text.indexOf('/') != -1)
		temp = text.split("/");
	else if (text.indexOf('-') != -1)
		temp = text.split("-");		
	else if (text.indexOf('.') != -1)
		temp = text.split(".");

	if (temp.length != 3)
		return null;
			
	var ggTemp	= temp[0];
	var mmTemp	= temp[1];
	var yyyyTemp= temp[2];

	if (!isanum(ggTemp) || !isanum(mmTemp) || !isanum(yyyyTemp))
		return null;
		
	if (ggTemp.length != 1 && ggTemp.length != 2)
		return null;		

	if (ggTemp.length == 2 && Left(ggTemp, 1) == '0')
		ggTemp = Right(ggTemp, 1);
		
	if (mmTemp.length != 1 && mmTemp.length != 2)
		return null;
	
	if (mmTemp.length == 2 && Left(mmTemp, 1) == '0')
		mmTemp= Right(mmTemp, 1);
	
	if (yyyyTemp.length != 4)
		return null;
		
	var gg 		= parseInt(ggTemp);
	var mm 		= parseInt(mmTemp) - 1;		//Note: January is 0, February is 1, and so on
	var yyyy 	= parseInt(yyyyTemp);
	
	if (gg <= 0 || gg > 31)
		return null;
	
	if (mm < 0 || mm > 11)
		return null;

	var currDate = new Date();
	maxYear = currDate.getFullYear() + 25;
	if ( (yyyy <= 1900) || (yyyy > maxYear) )
		return null;
	
	if ( (mm == 1 || mm == 3 || mm == 5 || mm == 8 || mm == 10) && gg == 31)
		return null;
		
	if (mm == 1 && gg == 30)
		return null;
				
	if (anno_bisestile(yyyy) == false && mm == 1 && gg == 29)
		return null;

	var dt = new Date(yyyy, mm, gg, 0, 0, 0, 0);

	return dt;
}





