//Alla funzione va passato l'interno codice IBAN formato dalla sigla nazione IT, dal numero di controllo 32, dal codice cin Z, dal codice abi 12345, 
//dal codice cab 67890 e dal conto corrente 123456789012
function ctrlIBAN(sncc,cin,abi,cab,cc)
{
	//valori di ritorno per il messaggio da visualizzare all'utente
	messIBAN = new Array(
			'ATTENZIONE! Il codice IBAN non risulta conforme alle specifiche.\nContinuare?'
			,'ATTENZIONE! Il codice IBAN non risulta conforme alle specifiche.\nDeve contenere 27 caratteri, per l\'Italia.\nContinuare?'
			,'ATTENZIONE! I codici IBAN controllati sono quello Italiano e della Repubblica di San Marino.\nContinuare?'
			,'ATTENZIONE! Il codice IBAN non risulta conforme alle specifiche, per la Repubblica di San Marino.\nContinuare?'
			,'ATTENZIONE! Il codice IBAN non risulta conforme alle specifiche.\nI primi due caratteri devono essere delle lettere dalla A-Z e maiuscole.\nContinuare?'
			,'ATTENZIONE! Il codice IBAN non risulta conforme alle specifiche.\nIl terzo e il quarto carattere devono essere numeri compresi tra 0-9.\nContinuare?'
			);
	
	//formatto i dati
	for(i = 1; 4 - sncc.length; i++)
		sncc += ' ';
	if(cin.length < 1)
		cin = ' ';
	for(i = 1; 5 - abi.length; i++)
		abi = '0' + abi;
	for(i = 1; 5 - cab.length; i++)
		cab = '0' + cab;
	for(i = 1; 12 - cc.length; i++)
		cc += ' ';

	var iban = sncc + cin + abi + cab + cc;

	if(iban == '')
	{
		if(!confirm(messIBAN[0]))
			return(0);
		else
			return(1);
	}
	else
	{
		var newiban = iban.replace(/\s+/g,'');

		//controllo la lunghezza
		if(newiban.length!=27)
		{
			if(!confirm(messIBAN[1]))
				return(0);
			else
				return(1);
		}

		//controllo la sigla della nazione
		if(newiban.substr(0,2) != 'IT' && newiban.substr(0,2) != 'SM')
		{
			if(!confirm(messIBAN[2]))
				return(0);
			else
				return(1);
		}
		else
		{
			var cab = newiban.substr(10,5);
			var cab_SM = parseInt(cab);

			if(newiban.substr(0,2) == 'SM' && (cab_SM < 9800 || cab_SM > 9810))
			{
				if(!confirm(messIBAN[3]))
					return(0);
				else
					return(1);
			}
		}
		
		//controllo dei caratteri
		for (i = 0; i < 2; i++)
			if(newiban.charCodeAt(i) < 65 || newiban.charCodeAt(i) > 90)
			{
				if(!confirm(messIBAN[4]))
					return(0);
				else
					return(1);
			}
		for (i = 2; i < 4; i++)
			if(newiban.charCodeAt(i) < 48 || newiban.charCodeAt(i) > 57) 
			{
				if(!confirm(messIBAN[5]))
					return(0);
				else
					return(1);
			}

		//controllo resto della divisione
		var testiban = newiban.substr(4,newiban.length - 4) + newiban.substr(0,2) + '00';
		var ibandef = '';

		for (i = 0; i <= testiban.length; i++)
		{
			if(testiban.charCodeAt(i) >= 65 && testiban.charCodeAt(i) <= 90)
				ibandef += testiban.charCodeAt(i) - 55;
			else
				ibandef += testiban.charAt(i);
		}

		var num = parseInt(ibandef.substr(0,2),10);
		var resto = num % 97;

		for (i = 2; i < ibandef.length; i++)
		{
			num = resto * 10 + parseInt(ibandef.charAt(i),10);
			resto = num % 97;
		}
	
		resto = 98 - resto;
		var cdc = parseInt(newiban.substr(2,2));
		
		if(resto != cdc)
			if(!confirm(messIBAN[0]))
				return(0);
			else
				return(1);
	}

	return(1);
}

function isFilled(fldobj)
{
  if(fldobj.value=="" || fldobj.value==null)
  {
 	 alert ("Il campo " + fldobj.name + " e' obbligatorio");
	 fldobj.value="";
	 fldobj.focus();
	 return false;
  }
  return true;
}

function Apro_Help_Gen(hpg)
        {
                var url="../main/" + hpg + ".sto"
                var win=window.open(url ,'Vish',
                'WIDTH=350,HEIGHT=400,,top=100,left=300,resizable=yes,scrollbars=1');
		// self.moveTo(100,100);
                win.focus();
        }


function GetFldsName()
{
        var j=document.Form0.elements.length;
	var s= '';

        for (i=0;i<j;i++)
        {
		s=s + document.Form0.elements[i].name + '|';
        }
        Doc.setFld(0,'StwFldsName',s);
}

function isInteger(fldobj)
{
  var str=fldobj.value+"";

  if(str=="") return false;
  for(var i=0; i<str.length; i++)
  {
	if(str.charAt(i) < "0" || str.charAt(i) >"9")
  	{
		alert ("Il campo non e' un numero intero");
		fldobj.value="";
		fldobj.focus();
		return false;
	}
  }
  return true;
}

function isNumber(fldobj)
{
  var str=fldobj.value+"";

  if(str=="") return false;
  for(var i=0; i<str.length; i++)
  {
	if(str.charAt(i) < "0" || str.charAt(i) >"9")
  	{
		alert ("Il valore non e' un numero");
		fldobj.value="";
		fldobj.focus();
		return false;
	}
  }
  if(isNumber.arguments.length==3)
  {
     //var num=parseInt(str);
     var num=Number(str);
     var min=isNumber.arguments[1];
     var max=isNumber.arguments[2];

     if(num < min || num > max)
     {
		alert ("Il valore amesso e' da " +min+ " a " +max);
		fldobj.value="";
		fldobj.focus();
		return false;
     }
  }
  return true;
}

//La funzione seguente serve per gli importi in LIRE o EURO:
// 1) se euro==N sono in regime di lire
// 1) se euro!=N sono in regime di euro
function isImporto(fldobj,euro)
{
  var str=fldobj.value+"";

  if(euro == "N")
  {
	  if(str=="") return false;
	  for(var i=0; i<str.length; i++)
	  {
	        if(i == 0 && str.charAt(i) == "-")
		{
			continue;
		}
		if(str.charAt(i) < "0" || str.charAt(i) >"9")
		{
			alert ("Il valore non e' un importo corretto in Lire");
			fldobj.value="";
			fldobj.focus();
			return false;
		}
	  }
	  if(isImporto.arguments.length==4)
	  {
	     var num=parseInt(str);
	     var min=isImporto.arguments[2];
	     var max=isImporto.arguments[3];

	     if(num < min || num > max)
	     {
			alert ("L'importo deve essere compreso tra L. " +min+ " e L. " +max);
			fldobj.value="";
			fldobj.focus();
			return false;
	     }
	  }
  }
  else
  {
	 var num1=Number(str);
	 if(str=="") return false;
	 for(var j=0; j<str.length; j++)
	 {
	        if(j == 0 && str.charAt(j) == "-")
			continue;
	        if(str.charAt(j) < "0" || str.charAt(j) >"9" )
		{
			if(str.substr(j,1) != ".")
			{
				alert ("Il campo non e' un importo in Euro corretto");
				fldobj.value="";
				fldobj.focus();
				return false;
			}
		}
	  }
	  if(isImporto.arguments.length==4)
	  {
	     var min1=isImporto.arguments[2];
	     var max1=isImporto.arguments[3];

	     if(num1 < min1 || num1 >= max1)
	     {
			alert ("L'importo deve essere compreso tra E. " +min1+ " e E. " +max1);
			fldobj.value="";
			fldobj.focus();
			return false;
	     }
	  }
  }
  return true;
}

function isRealNumber(fldobj)
{
  var str=fldobj.value+"";

  if(str=="") return false;
  for(var i=0; i<str.length; i++)
  {
	if((str.charAt(i) < "0" || str.charAt(i) >"9") && str.charAt(i) !="." && str.charAt(i) !=",")
  	{
		alert ("Il valore non e' un numero");
		fldobj.value="";
		fldobj.focus();
		return false;
	}
  }
  if(isRealNumber.arguments.length==3)
  {
     var num=parseFloat(str);
     var min=isRealNumber.arguments[1];
     var max=isRealNumber.arguments[2];

     if(num < min || num > max)
     {
		alert ("Il valore amesso e da " +min+ " a " +max);
		fldobj.value="";
		fldobj.focus();
		return false;
     }
  }
  return true;
}

function isRealNumberNeg(fldobj)
{
  var str=fldobj.value+"";
  if(str=="") return false;
  for(var i=0; i<str.length; i++)
  {
	if(i == 0 && str.charAt(i) == "-")
	{
		continue;
	}
	if((str.charAt(i) < "0" || str.charAt(i) >"9") && str.charAt(i) !="." && str.charAt(i) !=",")
  	{
		alert ("Il valore non e' un numero");
		fldobj.value="";
		fldobj.focus();
		return false;
	}
  }
  if(isRealNumberNeg.arguments.length==3)
  {
     var num=parseFloat(str);
     var min=isRealNumberNeg.arguments[1];
     var max=isRealNumberNeg.arguments[2];

     if(num < min || num > max)
     {
		alert ("Il valore amesso e da " +min+ " a " +max);
		fldobj.value="";
		fldobj.focus();
		return false;
     }
  }
  return true;
}

function isPercentuale(fldobj)
{
  var str=fldobj.value+"";
  var num=Number(str);

  if(str=="") return false;
  
  for(var i=0; i<str.length; i++)
  {
        if(str.charAt(i) < "0" || str.charAt(i) >"9" )
        {
                if(str.substr(i,1) != "." && str.substr(i,1) != "-")
                {
                        alert ("Il campo non e' un numero");
                        fldobj.value="";
                        fldobj.focus();
                        return false;
                }
        }
  }
  if(Math.abs(num) < 0 || Math.abs(num) > 100)
  {
	alert ("La percentuale deve essere compresa fra 0 e 100 %");
	fldobj.value="";
	fldobj.focus();
	return false;
  }
  return true;
}

// Controllo la data passata
function ctrDate(inDate) {
	if(inDate.length != 10)
  	{
		alert("Il formato valido per la data è\n" + "GG-MM-AAAA");
		return false;
	}
    if(inDate.indexOf('-') != -1) {
        var inDay = inDate.substring(0,inDate.indexOf("-"));
        if(inDay.substring(0,1) == "0" && inDay.length > 1)
        	inDay = inDay.substring(1,inDay.length);
        var inMonth = inDate.substring(inDate.indexOf("-") + 1, inDate.lastIndexOf("-"));
        if(inMonth.substring(0,1) == "0" && inMonth.length > 1)
        	inMonth = inMonth.substring(1,inMonth.length);
        var inYear = inDate.substring(inDate.lastIndexOf("-") + 1, inDate.length);

  	for(var i=0; i<inDay.length; i++)
  	{
		if((inDay.charAt(i) < "0" || inDay.charAt(i) >"9"))
			return false;
  	}

  	for(var j=0; j<inMonth.length; j++)
  	{
		if((inMonth.charAt(j) < "0" || inMonth.charAt(j) >"9"))
			return false;
  	}

  	for(var r=0; r<inYear.length; r++)
  	{
		if((inYear.charAt(r) < "0" || inYear.charAt(r) >"9"))
			return false;
  	}

	if(!isFourDigitYear(inYear)) return false;

    inDay = parseInt(inDay);
    inMonth = parseInt(inMonth);
    inYear = parseInt(inYear);
	if(inMonth == 0 || inMonth > 12) return false;
        numDays = getDaysInMonth(inMonth,inYear);
	if(inDay > numDays || inDay == 0) return false;
	return true;
	}
	return false;
}

// verifico che l'anno sia di 4 caratteri
function isFourDigitYear(year) {
    if (year.length != 4) {
        return false;
    }
    else {
        return true;
    }
}

// Si fa' dare i giorni del mese
function getDaysInMonth(month,year)  {
    var days;
    if (month==1 || month==3 || month==5 || month==7 || month==8 ||
        month==10 || month==12)  days=31;
    else if (month==4 || month==6 || month==9 || month==11) days=30;
    else if (month==2)  {
        if (isLeapYear(year)) {
            days=29;
        }
        else {
            days=28;
        }
    }
    return (days);
}


// Verifica se l'anno e' bisestile
function isLeapYear (Year) {
    if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
        return (true);
    }
    else {
        return (false);
    }
}
function isDate(campo,evento) {
  var DId;	
  var DIm;	
  var DIy;	
  var data=campo.value;

  if(data != '' && data.length != 6 && data.length != 8 && data.length != 10)
  {
	alert("I formati validi per le Date sono\nGGMMAA\n" +
	      "GGMMAAAA\nGG-MM-AAAA ");
	campo.value = "" ;
	campo.focus();
	return(false);	
  }
  if(data.length == 6)
  {	
  	DId=data.substring(0,2);	
  	DIm=data.substring(2,4);	
        if(data.substring(4,6) <= "30")
  	 DIy="20" + data.substring(4,6);	
        else
  	 DIy="19" + data.substring(4,6);	
  }
  else
  {	
	if(data.length == 8)
	{	
  		DId=data.substring(0,2);	
  		DIm=data.substring(2,4);	
  		DIy=data.substring(4,8);	
  	}
  	else
  	{	
  		DId=data.substring(0,2);	
  		DIm=data.substring(3,5);	
  		DIy=data.substring(6,10);	
  	}
	
  }
  var isdata = 0;
  if (data == "" || data == "00-00-0000")
	return(true);

  for(var i=0; i<DId.length; i++)
  {
	if((DId.charAt(i) < "0" || DId.charAt(i) >"9"))
  	{
		isdata=1;
	}
  }

  for(var j=0; j<DIm.length; j++)
  {
	if((DIm.charAt(j) < "0" || DIm.charAt(j) >"9"))
  	{
		isdata=1;
	}
  }

  for(var r=0; r<DIy.length; r++)
  {
	if((DIy.charAt(r) < "0" || DIy.charAt(r) >"9"))
  	{
		isdata=1;
	}
  }

  if(parseFloat(DIm) < 1 || parseFloat(DIm) > 12)
  {	
	isdata=1;
  }
  if(parseFloat(DIy) < 1000 || parseFloat(DIy) > 2150) //spostato da 2050 a 2150 per problema scadenze contrati cimiteri
  {	
	isdata=1;
  }
  if(parseFloat(DIm) == 1 || 
     parseFloat(DIm) == 3 ||
     parseFloat(DIm) == 5 ||
     parseFloat(DIm) == 7 ||
     parseFloat(DIm) == 8 ||
     parseFloat(DIm) == 10 ||
     parseFloat(DIm) == 12)
     { 
  	if(parseFloat(DId) < 1 || parseFloat(DId) > 31)
	{
	 isdata=1;
  	}
     }
  if(parseFloat(DIm) == 4 || 
     parseFloat(DIm) == 6 ||
     parseFloat(DIm) == 9 ||
     parseFloat(DIm) == 11)
     { 
  	if(parseFloat(DId) < 1 || parseFloat(DId) > 30)
	{
	 isdata=1;
  	}
     }
  if(parseFloat(DIm) == 2 ) 
     {
    	var iBis = parseFloat(DIy) % 4;
  	if( iBis == 0) //Bisestile
	{
  		if(parseFloat(DId) < 1 || parseFloat(DId) > 29)
		{
		 isdata=1;
  		}
	}
	else
	{
  		if(parseFloat(DId) < 1 || parseFloat(DId) > 28)
		{
		 isdata=1;
  		}
	}
     }
  if (isdata == 1) {
     alert("Data Errata!");
     campo.value="";	
     campo.focus();
     return(false);
  }
  campo.value = DId + "-" + DIm + "-" + DIy
  if(isDate.arguments.length==2)
  {
     	//var ev=isDate.arguments[1];
        Doc.win.MainSubmit(evento);
  }
  return(true);
}

//La funzione seguente serve per gli importi in LIRE o EURO con i punti:
// 1) se euro==N sono in regime di lire
// 1) se euro!=N sono in regime di euro
function isImportoPunt(fldobj,euro,lungh)
{
  var neg="";
  var str=fldobj.value+"";
  //if(Number(str) == 0) return false;

  if(euro == "N" || euro == "")
  {
	  for(var i=0; i<str.length; i++)
	  {
	        if(i == 0 && str.charAt(i) == "-")
		{
			continue;
		}
		if(str.charAt(i) < "0" || str.charAt(i) >"9")
		{
			if(str.substr(i,1) != "." && str.substr(i,1) != " ")
			{
				alert ("Il valore " + str + " non e' un importo corretto in Lire");
				fldobj.value="";
				fldobj.focus();
				return false;
			}
		}
	  }

	  var newstr="";
	  //Trasforma
	  for (i=0; i < str.length; i++)
	      {
	      digit = str.charAt(i);
	      if (digit == '.' || digit == ' ')
		 {newstr=newstr}
	      else
		 {newstr=newstr + digit;}
	      }

	  if(isImportoPunt.arguments.length==5)
	  {
	     var num=parseInt(newstr);
	     var min=isImportoPunt.arguments[3];
	     var max=isImportoPunt.arguments[4];

	     if(num < min || num > max)
	     {
			alert ("L'importo deve essere compreso tra L. " +min+ " e L. " +max);
			fldobj.value="";
			fldobj.focus();
			return false;
	     }
	  }

  	  if(Number(newstr) < 0)
	  {
		neg="S";
 		newstr = newstr.substring(1,newstr.length);
	  }
	  //Lo rispacchetto correttamente
	  var l = newstr.length;
	  var nuovastr="";
	  if(l>3)
	  {
		var d="";
		if(l%3 == 0)
		{
		  for (i=0; i < l; i++)
		  {
	                d = newstr.charAt(i);
		        if (i%3!=2 || i==l-1)
		 		{nuovastr=nuovastr + d;}
	      		else
		 		{nuovastr=nuovastr + d + '.';}
		  }
		}
		if(l%3 == 1)
		{
		  for (i=0; i < l; i++)
		  {
	                d = newstr.charAt(i);
		        if (i%3!=0 || i==l-1)
		 		{nuovastr=nuovastr + d;}
	      		else
		 		{nuovastr=nuovastr + d + '.';}
		  }
		}
		if(l%3 == 2)
		{
		  for (i=0; i < l; i++)
		  {
	                d = newstr.charAt(i);
		        if (i%3!=1 || i==l-1)
		 		{nuovastr=nuovastr + d;}
	      		else
		 		{nuovastr=nuovastr + d + '.';}
		  }
		}
	  }
	else
	  {
		 nuovastr=newstr;
	  }
	//aggiungo spazi a sinistra
  	if(neg == "S")
	{
 		nuovastr = "-" + nuovastr;
	}
	var l1 = lungh - nuovastr.length;
	var p="";
	for(i=1;i<=l1;i++) {p=p+" ";}
  	fldobj.value = p+nuovastr;
  }
  else
  {
	//GESTIONE IMPORTI IN EURO
	while (str.indexOf(" ") != -1) //Tolgo gli spazi
	{
		pp = str.indexOf(" ");
		pstr = str.substring(0,pp); 
        	nstr = str.substring(pp+1);
		str = pstr + nstr;
	}

	while (str.indexOf(".") != -1) // Tolgo i punti
	{
		pp = str.indexOf(".");
		pstr = str.substring(0,pp); 
        	nstr = str.substring(pp+1);
		// Permetto l'inserimento con "." come separatore di decimali
		if ( (str.length - pp)>3)
		{	
			str = pstr + nstr;
		}
		else
		{
			str = pstr + "," + nstr;
		}
	}

	for(var j=0; j<str.length; j++)  //Controllo che ci siano solo numeri
	{
		if(j == 0 && str.charAt(j) == "-") continue;

        	if(str.charAt(j) < "0" || str.charAt(j) >"9" )
		{
			if(str.substr(j,1) != ",")
			{
				alert ("Il campo non e' un importo in Euro corretto");
				fldobj.value="";
				fldobj.focus();
				return false;
			}
		}
	}

	if(isImportoPunt.arguments.length == 5)    //Controllo min e max
	{
		// var num1 = parseFloat(str);
		// prima della parseFloat devo sostituire la , con il .
  		var num1 = parseFloat(str.replace(/,/,"."));

		var min1 = isImportoPunt.arguments[3];
		var max1 = isImportoPunt.arguments[4];

	     	if(num1 < min1 || num1 > max1)
	     	{
				alert ("L'importo deve essere compreso tra Euro " + min1 + " e Euro " + max1);
				fldobj.value="";
				fldobj.focus();
				return false;
	     	}
	}

  	if ( str == "" )
  	{
		intstr = "0"
		decstr = "00"
  	} 
	else 
	{

  		pindex = str.indexOf(",");

  		if (pindex != -1)
  		{
  			intstr = str.substring(0,pindex);
  			decstr = str.substring(pindex+1);

  		} 
		else 
		{
			intstr = str;
			decstr = "00";
  		}
  	}

  	if (decstr.length == 0)
  	{
		decstr = "00";
  	} 
  
  	if (decstr.length == 1)
  	{
		decstr += "0";
  	}
  
  	if(Number(intstr) < 0)
	{
		neg="S";
 		intstr = intstr.substring(1,intstr.length);
	}

  	if (decstr.length >= 3)
  	{
		t = decstr.charAt(2);
		t = parseInt(t);
		decstr = decstr.substring(0,2);
		decnum = parseInt(decstr);
		intnum = parseInt(intstr);
	
		if (t >= 5)
		{
			if (decnum != 99)
			{
				decnum++;
				decstr=String(decnum);
			} 
			else 
			{
				decstr = "00";
				intnum++;
				intstr=String(intnum);
			}
		}
  	} 
  
  	if (lungh < 4) 
		lungh = 4;  

  	intlun = lungh - 3;

  	if (intlun > 0)
  	{
		cut = Math.floor(intlun / 4);
		intlun = intlun - cut;
  	}

  	if ( intstr.length > intlun )
  	{
		alert( "Il numero di cifre della parte intera dell'importo\neccede il massimo consentito." );	
		fldobj.value = "" ;
		fldobj.focus() ;
		return false;
 	}

  	if ( intstr.length > 3 )
  	{
		ipos = intstr.length - 3;
		while ( ipos > 0 )
		{
			tstr = intstr.substring(0,ipos) + 
			"." + intstr.substring(ipos);
			ipos -= 3;
			intstr = tstr;
		}
  	}

  	if(neg == "S")
	{
 		intstr = "-" + intstr;
	}

  	newstr = intstr + "," + decstr;

 	while ( newstr.length < lungh )
	{
		newstr = " " + newstr;
	}
	fldobj.value = newstr;
  }
  return true;
}


// Toglie gli spazi, i punti e sostituisce la virgola con il punto
function importo_to_numero (str)
{
 while (str.indexOf(" ") != -1) //Tolgo gli spazi
 {
 pp = str.indexOf(" ");
 pstr = str.substring(0,pp);
 nstr = str.substring(pp+1);
 str = pstr + nstr;
 }
 while (str.indexOf(".") != -1) // Tolgo i punti
 {
 pp = str.indexOf(".");
 pstr = str.substring(0,pp);
 nstr = str.substring(pp+1);
 str = pstr + nstr;
 }

 newstr = str.replace(/,/,".");
 return Number(newstr);
}

//Come la isImportoPunt, ma con la possibilità di specificare il numero di decimali.
//N.B. Gestisce solo Euro
function isImportoPuntDec(fldobj,euro,lungh,ndec)
{
  var neg="";
  var str=fldobj.value+"";
  //if(Number(str) == 0) return false;
	//GESTIONE IMPORTI IN EURO
	while (str.indexOf(" ") != -1) //Tolgo gli spazi
	{
		pp = str.indexOf(" ");
		pstr = str.substring(0,pp); 
        	nstr = str.substring(pp+1);
		str = pstr + nstr;
	}

	while (str.indexOf(".") != -1) // Tolgo i punti
	{
		pp = str.indexOf(".");
		pstr = str.substring(0,pp); 
        	nstr = str.substring(pp+1);

		// Permetto l'inserimento con "." come separatore di decimali
		// se piu' di 3 decimali e presente solamente "." l'ultimo "." a dx diventa ","
		// MARCO: il test pstr == 0 viene messo per input con 3 decimali tipo 0.093 che 
		// devono essere interpretati come separatore di decimali
		if ( 
		( (nstr.indexOf(".") == -1) && (nstr.indexOf(",") == -1) )  
		&& ( (str.length - pp)!=4 ) || (pstr == 0))
		{
                        str = pstr + "," + nstr;
                }
                else
                {
                        str = pstr + nstr;
                }
	}

	for(var j=0; j<str.length; j++)  //Controllo che ci siano solo numeri
	{
		if(j == 0 && str.charAt(j) == "-") continue;

        	if(str.charAt(j) < "0" || str.charAt(j) >"9" )
		{
			if(str.substr(j,1) != ",")
			{
				alert ("Il campo non e' un importo in Euro corretto");
				fldobj.value="";
				fldobj.focus();
				return false;
			}
		}
	}

	if(isImportoPuntDec.arguments.length == 6)    //Controllo min e max
	{
		// var num1 = parseFloat(str);
		// prima della parseFloat devo sostituire la , con il .
  		var num1 = parseFloat(str.replace(/,/,"."));

		var min1 = isImportoPunt.arguments[4];
		var max1 = isImportoPunt.arguments[5];

	     	if(num1 < min1 || num1 > max1)
	     	{
				alert ("L'importo deve essere compreso tra Euro " + min1 + " e Euro " + max1);
				fldobj.value="";
				fldobj.focus();
				return false;
	     	}
	}

  	if ( str == "" )
  	{
		intstr = "0"
		decstr = ""
		for (z=0; z<Number(ndec); z++)
		{
			decstr = decstr + "0";
		}
  	} 
	else 
	{
  		pindex = str.indexOf(",");
  		if (pindex != -1)
  		{
  			intstr = str.substring(0,pindex);
  			decstr = str.substring(pindex+1);
  		} 
		else 
		{
			intstr = str;
			decstr = ""
  		}
  	}
  
	if (Number(ndec>0))
	{
  		for (z=1; z<=Number(ndec); z++)
  		{
			if (decstr.length < Number(ndec))
			{
 	 			decstr = decstr + "0";
			}
  		}
	}

  	if (decstr.length > Number(ndec))
  	{
		t = decstr.charAt(Number(ndec));
		t = parseInt(t);
		decstr = decstr.substring(0,Number(ndec));
		decnum = parseInt(decstr);
		intnum = parseInt(intstr);
	
		if (t >= 5)
		{
			if (decnum != 99)
			{
				decnum++;
				decstr=String(decnum);
			} 
			else 
			{
				for (z=0; z<Number(ndec); z++)
				{
					decstr = decstr + "0";
				}
				intnum++;
				intstr=String(intnum);
			}
		}
  	} 
  
  	if (lungh < 4) 
		lungh = 4;  

  	intlun = lungh - 3;

  	if (intlun > 0)
  	{
		cut = Math.floor(intlun / 4);
		intlun = intlun - cut;
  	}

  	if ( intstr.length > intlun )
  	{
		alert( "Il numero di cifre della parte intera dell'importo\neccede il massimo consentito." );	
		fldobj.value = "" ;
		fldobj.focus() ;
		return false;
 	}

  	if ( intstr.length > 3 )
  	{
		ipos = intstr.length - 3;
		while ( ipos > 0 )
		{
			tstr = intstr.substring(0,ipos) + 
			"." + intstr.substring(ipos);
			ipos -= 3;
			intstr = tstr;
		}
  	}

  	if(neg == "S")
	{
 		intstr = "-" + intstr;
	}

  	newstr = intstr + "," + decstr;

 	while ( newstr.length < lungh )
	{
		newstr = " " + newstr;
	}
	fldobj.value = newstr;
  
  return true;
}

function isImportoPunt4(fldobj,euro,lungh)
{
  var neg="";
  var str=fldobj.value+"";
  if(Number(str) == 0) return false;

	//GESTIONE IMPORTI IN EURO
	while (str.indexOf(" ") != -1) //Tolgo gli spazi
	{
		pp = str.indexOf(" ");
		pstr = str.substring(0,pp); 
        	nstr = str.substring(pp+1);
		str = pstr + nstr;
	}

	//while (str.indexOf(".") != -1) // Tolgo i punti
	//{
		//pp = str.indexOf(".");
		//pstr = str.substring(0,pp); 
        	//nstr = str.substring(pp+1);
		//str = pstr + nstr;
	//}
	// sostituisco il punto con la virgola
	str = str.replace(/\./,",");

	for(var j=0; j<str.length; j++)  //Controllo che ci siano solo numeri
	{
		if(j == 0 && str.charAt(j) == "-") continue;

        if(str.charAt(j) < "0" || str.charAt(j) >"9" )
		{
			if(str.substr(j,1) != ",")
			{
				alert ("Il campo non e' un importo in Euro corretto Euro !!");
				fldobj.value="";
				fldobj.focus();
				return false;
			}
		}
	}

	if(isImportoPunt4.arguments.length == 5)    //Controllo min e max
	{
		var num1 = parseFloat(str);
		var min1 = isImportoPunt4.arguments[3];
		var max1 = isImportoPunt4.arguments[4];

	     	if(num1 < min1 || num1 > max1)
	     	{
				alert ("L'importo deve essere compreso tra Euro " + min1 + " e Euro " + max1);
				fldobj.value="";
				fldobj.focus();
				return false;
	     	}
	}

  	if ( str == "" )
  	{
		intstr = "0"
		decstr = "0000"
  	} 
	else 
	{
  		pindex = str.indexOf(",");

  		if (pindex != -1)
  		{
  			intstr = str.substring(0,pindex);
  			decstr = str.substring(pindex+1);

  		} 
		else 
		{
			intstr = str;
			decstr = "0000";
  		}
  	}

  	if (decstr.length == 0)
  	{
		decstr = "0000";
  	} 
  
  	if (decstr.length == 1)
  	{
		decstr += "000";
  	}
  	if (decstr.length == 2)
  	{
		decstr += "00";
  	}
  	if (decstr.length == 3)
  	{
		decstr += "0";
  	}
  
  	if(Number(intstr) < 0)
	{
		neg="S";
 		intstr = intstr.substring(1,intstr.length);
	}

  	if (decstr.length >= 5)
  	{
		t = decstr.charAt(4);
		t = parseInt(t);
		decstr = decstr.substring(0,4);
		

		var idx = 0;
		for(i = 0; i <= 2; i++)
		{
			if(decstr.charAt(i) == 0)
			idx++;
		}
		
		if(idx)
		{
			newdecstr = decstr.substring(idx,decstr.length);
			decnum = parseInt(newdecstr);
		}
		else		
			decnum = parseInt(decstr);

		intnum = parseInt(intstr);

		if (t >= 5)
		{
			if (decnum != 9999)
			{
				decnum++;
				decstr=String(decnum);

				if(idx == 1)
					decstr = "0" +decnum;
				if(idx == 2)
					decstr = "00" +decnum;
				if(idx == 3)
					decstr = "000" +decnum;
			} 
			else 
			{
				decstr = "0000";
				intnum++;
				intstr=String(intnum);
			}
		}
  	} 
  
  	if (lungh < 6) 
		lungh = 6;  

  	intlun = lungh - 5;

  	if (intlun > 0)
  	{
		cut = Math.floor(intlun / 4);
		intlun = intlun - cut;
  	}

  	if ( intstr.length > intlun )
  	{
		alert( "Il numero di cifre della parte intera dell'importo\neccede il massimo consentito." );	
		fldobj.value = "" ;
		fldobj.focus() ;
		return false;
 	}

  	if ( intstr.length > 3 )
  	{
		ipos = intstr.length - 3;
		while ( ipos > 0 )
		{
			tstr = intstr.substring(0,ipos) + 
			"." + intstr.substring(ipos);
			ipos -= 3;
			intstr = tstr;
		}
  	}

  	if(neg == "S")
	{
 		intstr = "-" + intstr;
	}

  	newstr = intstr + "," + decstr;

 	while ( newstr.length < lungh )
	{
		newstr = " " + newstr;
	}
	fldobj.value = newstr;
}
//function analoga alla AllineaImporto ma con la possibilità di specificare
//il numero di decimali
function AllineaImportoDec(valore,euro,lungh,ndec)
{
  var neg = "";
  var strval = String(valore);
  var str = strval.replace(/\./,",");
  if(str.charAt(0) == '-')
  {
	str = str.substr(1);
	neg = "-";
  }

	//GESTIONE IMPORTI IN EURO
	while (str.indexOf(" ") != -1) //Tolgo gli spazi
	{
		pp = str.indexOf(" ");
		pstr = str.substring(0,pp); 
        nstr = str.substring(pp+1);
		str = pstr + nstr;
	}

	while (str.indexOf(".") != -1) // Tolgo i punti
	{
		pp = str.indexOf(".");
		pstr = str.substring(0,pp); 
        nstr = str.substring(pp+1);
		str = pstr + nstr;
	}

	for(var j=0; j<str.length; j++)  //Controllo che ci siano solo numeri
	{
		if(j == 0 && str.charAt(j) == "-") continue;

        if(str.charAt(j) < "0" || str.charAt(j) >"9" )
		{
			if(str.substr(j,1) != ",")
			{
				alert ("Il campo non e' un importo in Euro corretto. ");
				return '';
			}
		}
	}

	if(AllineaImportoDec.arguments.length == 6)    //Controllo min e max
	{
		var num1 = parseFloat(str);
		var min1 = AllineaImportoDec.arguments[4];
		var max1 = AllineaImportoDec.arguments[5];

	     	if(num1 < min1 || num1 > max1)
	     	{
			alert ("L'importo deve essere compreso tra Euro " + min1 + " e Euro " + max1);
			return '';
	     	}
	}

  	if ( str == "" )
  	{
		intstr = "0";
		for (z=0; z<Number(ndec); z++)
		{
			decstr = decstr + "0";
		}
  	} 
	else 
	{
  		pindex = str.indexOf(",");
  		if (pindex != -1)
  		{
  			intstr = str.substring(0,pindex);
  			decstr = str.substring(pindex+1);
  		} 
		else 
		{
			intstr = str;
			decstr = "0000";
  		}
  	}

	if (Number(ndec>0))
	{
  		for (z=1; z<=Number(ndec); z++)
  		{
			if (decstr.length < Number(ndec))
			{
 	 			decstr = decstr + "0";
			}
  		}
	}

  	if (decstr.length > Number(ndec))
  	{
		arr = parseFloat(decstr.substr(ndec-1,1) + "." + decstr.substr(ndec,1));
		arr = Math.round(arr);

		decstr = decstr.substr(0,ndec-1) + arr; 
  	} 

  	if ( intstr.length > 3 )
  	{
		ipos = intstr.length - 3;

		while ( ipos > 0 )
		{
			tstr = intstr.substring(0,ipos) + "." + intstr.substring(ipos);
			ipos -= 3;
			intstr = tstr;
		}
  	}

  	newstr = neg + intstr + "," + decstr;

 	while ( newstr.length < lungh )
	{
		newstr = " " + newstr;
	}
  
  return newstr;
}

//function analoga alla isImportoPunt ma anzichè avere in ingresso
//un oggetto campo, prende un numero
function AllineaImporto(valore,euro,lungh)
{
  var neg = "";
  var strval = String(valore);
  var str = strval.replace(/\./,",");
  if(str.charAt(0) == '-')
  {
	str = str.substr(1);
	neg = "-";
  }


  if(euro == "N" || euro == "")
  {
	  if(Number(str) == 0) return '';
	  for(var i=0; i<str.length; i++)
	  {
	        if(i == 0 && str.charAt(i) == "-")
		{
			continue;
		}
		if(str.charAt(i) < "0" || str.charAt(i) >"9")
		{
			if(str.substr(i,1) != "." && str.substr(i,1) != " ")
			{
				alert ("Il valore " + str + " non e' un importo corretto in Lire");
				return '';
			}
		}
	  }

	  var newstr="";
	  //Trasforma
	  for (i=0; i < str.length; i++)
	      {
	      digit = str.charAt(i);
	      if (digit == '.' || digit == ' ')
		 {newstr=newstr}
	      else
		 {newstr=newstr + digit;}
	      }

	  if(AllineaImporto.arguments.length==5)
	  {
	     var num=parseInt(newstr);
	     var min=AllineaImporto.arguments[3];
	     var max=AllineaImporto.arguments[4];

	     if(num < min || num > max)
	     {
			alert ("L'importo deve essere compreso tra L. " +min+ " e L. " +max);
			return '';
	     }
	  }
	  //Lo rispacchetto correttamente
	  var l = newstr.length;
	  var nuovastr="";
	  if(l>3)
	  {
		var d="";
		if(l%3 == 0)
		{
		  for (i=0; i < l; i++)
		  {
	                d = newstr.charAt(i);
		        if (i%3!=2 || i==l-1)
		 		{nuovastr=nuovastr + d;}
	      		else
		 		{nuovastr=nuovastr + d + '.';}
		  }
		}
		if(l%3 == 1)
		{
		  for (i=0; i < l; i++)
		  {
	                d = newstr.charAt(i);
		        if (i%3!=0 || i==l-1)
		 		{nuovastr=nuovastr + d;}
	      		else
		 		{nuovastr=nuovastr + d + '.';}
		  }
		}
		if(l%3 == 2)
		{
		  for (i=0; i < l; i++)
		  {
	                d = newstr.charAt(i);
		        if (i%3!=1 || i==l-1)
		 		{nuovastr=nuovastr + d;}
	      		else
		 		{nuovastr=nuovastr + d + '.';}
		  }
		}
	  }
	else
	  {
		 nuovastr=newstr;
	  }
	nuovastr= neg + nuovastr;
	//aggiungo spazi a sinistra
	var l1 = lungh - nuovastr.length;
	var p="";
	for(i=1;i<=l1;i++) {p=p+" ";}
	return p+nuovastr;
  }
  else
  {
	//GESTIONE IMPORTI IN EURO

	while (str.indexOf(" ") != -1) //Tolgo gli spazi
	{
		pp = str.indexOf(" ");
		pstr = str.substring(0,pp); 
        nstr = str.substring(pp+1);
		str = pstr + nstr;
	}

	while (str.indexOf(".") != -1) // Tolgo i punti
	{
		pp = str.indexOf(".");
		pstr = str.substring(0,pp); 
        nstr = str.substring(pp+1);
		str = pstr + nstr;
	}

	for(var j=0; j<str.length; j++)  //Controllo che ci siano solo numeri
	{
		if(j == 0 && str.charAt(j) == "-") continue;

        if(str.charAt(j) < "0" || str.charAt(j) >"9" )
		{
			if(str.substr(j,1) != ",")
			{
				alert ("Il campo non e' un importo in Euro corretto. ");
				return '';
			}
		}
	}

	if(AllineaImporto.arguments.length == 5)    //Controllo min e max
	{
		var num1 = parseFloat(str);
		var min1 = AllineaImporto.arguments[3];
		var max1 = AllineaImporto.arguments[4];

	     	if(num1 < min1 || num1 > max1)
	     	{
			alert ("L'importo deve essere compreso tra Euro " + min1 + " e Euro " + max1);
			return '';
	     	}
	}

  	if ( str == "" )
  	{
		intstr = "0"
		decstr = "00"

  	} else {

  		pindex = str.indexOf(",");

  		if (pindex != -1)
  		{
  			intstr = str.substring(0,pindex);
  			decstr = str.substring(pindex+1);

  		} else {

			intstr = str;
			decstr = "00";
  		}
  	}

  	if (decstr.length == 0)
  	{
		decstr = "00";
  	} 
  
  	if (decstr.length == 1)
  	{
		decstr += "0";
  	}
  
  	if (decstr.length >= 3)
  	{
		t = decstr.charAt(2);
		t = parseInt(t);
		decstr = decstr.substring(0,2);
		decnum = Number(decstr);
		intnum = parseInt(intstr);
	
		if (t >= 5)
		{
			if (decnum != 99)
			{
				decnum++;
				decstr=String(decnum);
			} else {
				decstr = "00";
				intnum++;
				intstr=String(intnum);
			}
		}
		if(decstr.length == 1)
			decstr = "0" + decstr;
  	} 
  
  	if (lungh < 4) lungh = 4;  

  	intlun = lungh - 3;

  	//if (intlun > 0)
  	//{
	//	cut = Math.floor(intlun / 4);
	//	intlun = intlun - cut;
  	//}

  	if ( intstr.length > intlun )
  	{
		alert( "Il numero di cifre della parte intera dell'importo\neccede il massimo consentito." );	
		return '';
 	}

  	if ( intstr.length > 3 )
  	{
		ipos = intstr.length - 3;

		while ( ipos > 0 )
		{
			tstr = intstr.substring(0,ipos) + "." + intstr.substring(ipos);
			ipos -= 3;
			intstr = tstr;
		}
  	}

  	newstr = neg + intstr + "," + decstr;

 	while ( newstr.length < lungh )
	{
		newstr = " " + newstr;
	}
  
	return newstr;
  }
}


function controllaCampiObbl() 
{
	var campi_obbl = document.getElementsByClassName('obbligatorio');
		for(z = 0; z < campi_obbl.length; z++)
		{
			if(campi_obbl[z].value == '' || campi_obbl[z].value == 0)
			{
				alert("Controllare i campi obbligatori");
				campi_obbl[z].focus();
	 			return false;
			}
		}
	return true;
}



//La funzione permette di effettuare le quattro operazioni algebriche +, -, /, * passando da 1 a n campi della form
//alla funzione dovranno essere passati anche quanti decimali avra' il risultato
//la sistassi è la seguente SumSubDivMul(segno,decimali,operazione,campo 1,.....,operazione n,campo n)
//es.: SumSubDivMul('+',4,'+','Competenza','-','Residui','/','Mesi','*','Trimestre')
//l'esempio dice di sommare il contenuto del campo competenza, sottrare il contenuto del campo residui, dividere per il
//contenuto del campo mesi e moltiplicare per il contenuto del campo trimestre; il risultato sarà positivo con 4 decimali
function SumSubDivMul(seg,dec)
{
	var tot = 0;
	var val = 0;
	var op = '';

	for (var i = 2; i < SumSubDivMul.arguments.length; i++)
	{
		switch(SumSubDivMul.arguments[i])
		{
			case '*':
				op = '*';
				break;
				
			case '/':
				op = '/';
				break;
				
			case '+':
				op = '+';
				break;
				
			case '-':
				op = '-';
				break;
				
			default:
				val = Doc.getFld(0,SumSubDivMul.arguments[i]);
				
				if (val == '') 
					val = 0;
    			else
    				val = parseFloat(importo_to_numero(val));


				switch(op)
				{
					case '*':
						tot = tot * val;
						break;
						
					case '/':
						if(val != 0)
							tot = tot / val;
						break;
						
					case '+':
						tot = tot + val;
						break;
						
					case '-':
						tot = tot - val;
						break;
					
					default:
				}

			    tot = tot * Math.pow(10,dec+1);
			    tot = Math.round(tot);
			    tot = tot / Math.pow(10,dec+1);
		}
	}

	if(seg == '+' && tot < 0)
		tot = tot * (0 - 1);
	
	if(seg == '-' && tot > 0)
		tot = tot * (0 - 1);

	return(AllineaImportoDec(tot,'S',19,dec));
}

//  La funzione somma il valore di N campi importo e lo scrive nel
// campo target sempre formattato come importo. Target e' la stringa
// con il nome del campo su cui scrivere. Al parametro target possono
// seguire N parametri stringa separati da virgola con i nomi dei 
// campi da cui prendere i valori da sommare.
function Totale(target,divisa)
{
    var tot = 0;
    var c = 0;

    for (var ii = 2; ii < Totale.arguments.length; ii++)
    {
        cc = Doc.getFld(0,Totale.arguments[ii]);
        if (cc == "") cc = "0,00";
        cc = importo_to_numero (cc);
        cc = parseFloat (cc);
        tot = tot + cc;
    }

    Doc.setFld(0,target,'');
    Doc.setFld(0,target,AllineaImporto(tot,divisa,19));

    return true;
}

//La funzione aggiorna il campo target con sommando il valore del campo
//field. Field e Traget sono stringhe con i nomi dei campi; i campi sono
//intesi formattati come importi.
function Update(field,target,divisa)
{
    var value = Doc.getFld(0,field);
    if (value == "") value = "0,00";
    value = importo_to_numero(value);
    value = parseFloat(value);

    var value1 = Doc.getFld(0,target);
    if (value1 == "") value1 = "0,00";
    value1 = importo_to_numero(value1);
    value1 = parseFloat(value1);

    var tot = value1 + value;

    Doc.setFld(0,target,'');
    Doc.setFld(0,target,AllineaImporto(tot,divisa,16));

    return true;
}

//  La funzione controlla se la somma di N campi importo e' uguale al
// campo total sempre formattato come importo. Total e' la stringa
// con il nome del campo con il totale. Al parametro total possono
// seguire N parametri stringa separati da virgola con i nomi dei 
// campi da cui prendere i valori da sommare.
function CheckSum(total)
{
 var tot = 0;
 var cc = 0;

 for (var ii = 1; ii < CheckSum.arguments.length; ii++)
    {
        cc = Doc.getFld(0,CheckSum.arguments[ii]);
        if (cc == "") cc = "0,00";
        cc = importo_to_numero(cc);
        cc = parseFloat(cc);
        //alert(cc);
        tot = tot + cc;
    }

    var check = Doc.getFld(0,total);
    if (check == "") check = "0,00"
    check = importo_to_numero(check);
    check = parseFloat(check);

    diff = tot - check;
    return diff;
}

//La funzione riporta il multiplo di num1 piu' vicino a num2. 
//arrotondamento matematico del numero num1
function amm(num1,num2)
{
	num=Math.round(num1/num2)*num2;
	var resto=num1-num;
	if(resto>num2/2)
		num=num+num2;
	return num;
}

//La funzione riporta la differenza di due date. 
//errori da testare:
//-2 se almeno una delle date e' vuota.
//-1 se pa prima e' maggiore della seconda.
function DiffDate(datai,dataf)
{
  	if (datai == "" || datai == "00-00-0000" || 
	dataf == "" || dataf == "00-00-0000")
  		return(-2);

  	var DId=Number(datai.substring(0,2));	
  	var DIm=Number(datai.substring(3,5));	
  	var DIy=Number(datai.substring(6,10));	
  	var DFd=Number(dataf.substring(0,2));	
  	var DFm=Number(dataf.substring(3,5));	
  	var DFy=Number(dataf.substring(6,10));	
  	var di = new Date(DIy,DIm - 1,DId);
  	var df = new Date(DFy,DFm - 1,DFd);
  	dataitime = di.getTime(); 
  	dataftime = df.getTime(); 
  	if (dataitime > dataftime)
	{
		return(-1);
	}

  	difftime = Math.abs(dataftime-dataitime); 
  	//var periodo = parseInt(difftime/1000/60/60/24); 
  	var periodo = parseInt(difftime / 86400000) ;
   	periodo += parseInt((difftime % 86400000)/43200001)
	return(periodo);
}

//La funzione aggiorna il contatore count .
//In input vuole :
// il campo f che contiene la stringa da contare;
// il nome del contatore count;
// la lunghezza massima della stringa max;
//In output aggiorna il contatore.
function CountString(f,count,max)
{
   	if (f.value.length > max)
  	{
     		f.value = f.value.substring(0,max)
     		charleft = 0
   	} 
   	else
   	{
     		charleft = max - f.value.length
  	}
        Doc.setFld(0,count,charleft);
}

//La funzione riceve in ingresso il nome di un campo di tipo data
// e restituisce 
function calcolaEta(datanascita,eta)
{
 	var datan = datanascita.value;
	var giorno = Number(datan.substring(0,2));
	var mese = Number(datan.substring(3,5));
	var anno = Number(datan.substring(6,10));

	//Data di oggi
	var oggi = new Date();
	var oggi_a = oggi.getFullYear();
	var oggi_m = oggi.getMonth()+1;
	var oggi_g = oggi.getDate();

/*
alert("oggi:"+oggi.toString());
alert("giorno:"+giorno+"  mese:"+mese+"  anno:"+anno);
alert("oggi_g:"+oggi_g+"  oggi_m:"+oggi_m+"  oggi_a:"+oggi_a);
*/

	var valore_eta = 0;
	if (oggi_a > anno) 
	{
	    valore_eta = oggi_a - anno;
		if (mese > oggi_m  ||  (mese == oggi_m && giorno > oggi_g))
		    valore_eta -= 1;
	}
	Doc.setFld(0,eta,valore_eta);
}

function DataMinDomani(campo)
{
 	var data=campo.value;
    	var now   = new Date();
    	var day   = now.getDate();
    	var month = now.getMonth();
    	var year  = now.getFullYear();
        inmonth = parseInt(month);
	inmonth++;
    	if((""+inmonth).length == 1)
    	{
       		 inmonth="0"+inmonth;
    	}
    	if((""+day).length == 1)
    	{
       		 day="0"+day;
    	}
	var oggi=day+"-"+inmonth+"-"+year
	var res = DiffDate(data,oggi);
	if(res == -1 || res == -2)
	{
		alert("La data deve essere antecedente o corrispondente alla data di oggi!");
		campo.value="";
		return;
	}
}
function IsDataMinDomani(data)
{
    	var now   = new Date();
    	var day   = now.getDate();
    	var month = now.getMonth();
    	var year  = now.getFullYear();
        inmonth = parseInt(month);
	inmonth++;
    	if((""+inmonth).length == 1)
    	{
       		 inmonth="0"+inmonth;
    	}
    	if((""+day).length == 1)
    	{
       		 day="0"+day;
    	}
	var oggi=day+"-"+inmonth+"-"+year
	var res = DiffDate(data,oggi);
	if(res == -1 || res == -2)
		return false;
	else
		return true;
}

function ControllaMail(indirizzo)
{
	var EmailAddr = indirizzo.value+"";
	if (EmailAddr == "") return true;

	Filtro = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
	if (Filtro.test(EmailAddr))
	return true;
	else
	{
		alert("L'indirizzo e-mail inserito non è corretto!");
		return false;
	}
}

function PreloadSubMenu()
{
	return true;	
}



// Routines utili all'ordinamento rapido delle colonne delle tables - INIZIO
var stIsIE = /*@cc_on!@*/false;

sorttable = {
  init: function() {
    // quit if this function has already been called
    if (arguments.callee.done) return;
    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;
    // kill the timer
    if (_timer) clearInterval(_timer);
    
    if (!document.createElement || !document.getElementsByTagName) return;
    
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
    
    forEach(document.getElementsByTagName('table'), function(table) {
      if (table.className.search(/\bsortable\b/) != -1) {
        sorttable.makeSortable(table);
      }
    });
    
  },
  
  makeSortable: function(table) {
    if (table.getElementsByTagName('thead').length == 0) {
      // table doesn't have a tHead. Since it should have, create one and
      // put the first table row in it.
      the = document.createElement('thead');
      the.appendChild(table.rows[0]);
      table.insertBefore(the,table.firstChild);
    }
    // Safari doesn't support table.tHead, sigh
    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
    
    if (table.tHead.rows.length != 1) return; // can't cope with two header rows
    
    // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
    // "total" rows, for example). This is B&R, since what you're supposed
    // to do is put them in a tfoot. So, if there are sortbottom rows,
    // for backwards compatibility, move them to tfoot (creating it if needed).
    sortbottomrows = [];
    for (var i=0; i<table.rows.length; i++) {
      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
        sortbottomrows[sortbottomrows.length] = table.rows[i];
      }
    }
    if (sortbottomrows) {
      if (table.tFoot == null) {
        // table doesn't have a tfoot. Create one.
        tfo = document.createElement('tfoot');
        table.appendChild(tfo);
      }
      for (var i=0; i<sortbottomrows.length; i++) {
        tfo.appendChild(sortbottomrows[i]);
      }
      delete sortbottomrows;
    }
    
    // work through each column and calculate its type
    headrow = table.tHead.rows[0].cells;
    for (var i=0; i<headrow.length; i++) {
      // manually override the type with a sorttable_type attribute
      if (!headrow[i].className.match(/\bno_sort\b/)) { // skip this col
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
        if (mtch) { override = mtch[1]; }
	      if (mtch && typeof sorttable["sort_"+override] == 'function') {
	        headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
	      } else {
	        headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
	      }
	      // make it clickable to sort
	      headrow[i].sorttable_columnindex = i;
	      headrow[i].sorttable_tbody = table.tBodies[0];
	      dean_addEvent(headrow[i],"click", function(e) {

          if (this.className.search(/\bsorttable_sorted\b/) != -1) {
            // if we're already sorted by this column, just 
            // reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted',
                                                    'sorttable_sorted_reverse');
            this.removeChild(document.getElementById('sorttable_sortfwdind'));
            sortrevind = document.createElement('span');
            sortrevind.id = "sorttable_sortrevind";
            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
            this.appendChild(sortrevind);
            return;
          }
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
            // if we're already sorted by this column in reverse, just 
            // re-reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted_reverse',
                                                    'sorttable_sorted');
            this.removeChild(document.getElementById('sorttable_sortrevind'));
            sortfwdind = document.createElement('span');
            sortfwdind.id = "sorttable_sortfwdind";
            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
            this.appendChild(sortfwdind);
            return;
          }
          
          // remove sorttable_sorted classes
          theadrow = this.parentNode;
          forEach(theadrow.childNodes, function(cell) {
            if (cell.nodeType == 1) { // an element
              cell.className = cell.className.replace('sorttable_sorted_reverse','');
              cell.className = cell.className.replace('sorttable_sorted','');
            }
          });
          sortfwdind = document.getElementById('sorttable_sortfwdind');
          if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
          sortrevind = document.getElementById('sorttable_sortrevind');
          if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
          
          this.className += ' sorttable_sorted';
          sortfwdind = document.createElement('span');
          sortfwdind.id = "sorttable_sortfwdind";
          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
          this.appendChild(sortfwdind);

	        // build an array to sort. This is a Schwartzian transform thing,
	        // i.e., we "decorate" each row with the actual sort key,
	        // sort based on the sort keys, and then put the rows back in order
	        // which is a lot faster because you only do getInnerText once per row
	        row_array = [];
	        col = this.sorttable_columnindex;
	        rows = this.sorttable_tbody.rows;
	        for (var j=0; j<rows.length; j++) {
	          row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
	        }
	        /* If you want a stable sort, uncomment the following line */
	        //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
	        /* and comment out this one */
	        row_array.sort(this.sorttable_sortfunction);
	        
	        tb = this.sorttable_tbody;
	        for (var j=0; j<row_array.length; j++) {
	          tb.appendChild(row_array[j][1]);
	        }
	        
	        for (var j=0; j<row_array.length; j++) 
	        {
	          var newnode = tb.appendChild(row_array[j][1]);
	          if (j%2==0)
	          {
	          	newnode.className="rigadispari";
	          }
	          else
	          {
	          	newnode.className="rigapari";
	          }
	        }
	        
	        delete row_array;
	      });
	    }
    }
  },
  
  guessType: function(table, column) {
    // guess the type of a column based on its first non-blank row
    sortfn = sorttable.sort_alpha;
    for (var i=0; i<table.tBodies[0].rows.length; i++) {
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
      if (text != '' && text != undefined ) {
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
          return sorttable.sort_numeric;
        }
        // check for a date: dd/mm/yyyy or dd/mm/yy 
        // can have / or . or - as separator
        // can be mm/dd as well
        possdate = text.match(sorttable.DATE_RE)
        if (possdate) {
          // looks like a date
          first = parseInt(possdate[1]);
          second = parseInt(possdate[2]);
          if (first > 12) {
            // definitely dd/mm
            return sorttable.sort_ddmm;
          } else if (second > 12) {
            return sorttable.sort_mmdd;
          } else {
            // looks like a date, but we can't tell which, so assume
            // that it's dd/mm (English imperialism!) and keep looking
            sortfn = sorttable.sort_ddmm;
          }
        }
      }
    }
    return sortfn;
  },
  
  getInnerText: function(node) {
    // gets the text we want to use for sorting for a cell.
    // strips leading and trailing whitespace.
    // this is *not* a generic getInnerText function; it's special to sorttable.
    // for example, you can override the cell text with a customkey attribute.
    // it also gets .value for <input> fields.
    if(node==null) return;
    hasInputs = (typeof node.getElementsByTagName == 'function') &&
                 node.getElementsByTagName('input').length;
    
    if (node.getAttribute("sorttable_customkey") != null) {
      return node.getAttribute("sorttable_customkey");
    }
    else if (typeof node.textContent != 'undefined' && !hasInputs) {
      return node.textContent.replace(/^\s+|\s+$/g, '');
    }
    else if (typeof node.innerText != 'undefined' && !hasInputs) {
      return node.innerText.replace(/^\s+|\s+$/g, '');
    }
    else if (typeof node.text != 'undefined' && !hasInputs) {
      return node.text.replace(/^\s+|\s+$/g, '');
    }
    else {
      switch (node.nodeType) {
        case 3:
          if (node.nodeName.toLowerCase() == 'input') {
            return node.value.replace(/^\s+|\s+$/g, '');
          }
        case 4:
          return node.nodeValue.replace(/^\s+|\s+$/g, '');
          break;
        case 1:
        case 11:
          var innerText = '';
          for (var i = 0; i < node.childNodes.length; i++) {
            innerText += sorttable.getInnerText(node.childNodes[i]);
          }
          return innerText.replace(/^\s+|\s+$/g, '');
          break;
        default:
          return '';
      }
    }
  },
  
  reverse: function(tbody) {
    // reverse the rows in a tbody
     if(tbody==null) return;
    newrows = [];
    for (var i=0; i<tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (var i=newrows.length-1; i>=0; i--) {
       tbody.appendChild(newrows[i]);
    }
    delete newrows;
  },
  
  /* sort functions
     each sort function takes two parameters, a and b
     you are comparing a[0] and b[0] */
  sort_numeric: function(a,b) {
    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
  },
  sort_alpha: function(a,b) {
    if (a[0]==b[0]) return 0;
    if (a[0]<b[0]) return -1;
    return 1;
  },
  sort_ddmm: function(a,b) {
    mtch = a[0].match(sorttable.DATE_RE);
    if (mtch == null)
    	return 0;
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(sorttable.DATE_RE);
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  },
  sort_mmdd: function(a,b) {
    mtch = a[0].match(sorttable.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(sorttable.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  },
  
  shaker_sort: function(list, comp_func) {
    // A stable sort function to allow multi-level sorting of data
    // see: http://en.wikipedia.org/wiki/Cocktail_sort
    // thanks to Joseph Nahmias
    var b = 0;
    var t = list.length - 1;
    var swap = true;

    while(swap) {
        swap = false;
        for(var i = b; i < t; ++i) {
            if ( comp_func(list[i], list[i+1]) > 0 ) {
                var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
                swap = true;
            }
        } // for
        t--;

        if (!swap) break;

        for(var i = t; i > b; --i) {
            if ( comp_func(list[i], list[i-1]) < 0 ) {
                var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
                swap = true;
            }
        } // for
        b++;

    } // while(swap)
  }  
}

/* ******************************************************************
   Supporting functions: bundled here to avoid depending on a library
   ****************************************************************** */

// Dean Edwards/Matthias Miller/John Resig

/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", sorttable.init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=//:><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            sorttable.init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            sorttable.init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = sorttable.init;

// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini

// http://dean.edwards.name/weblog/2005/10/add-event/

function dean_addEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
  this.cancelBubble = true;
}

// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
	forEach, version 1.0
	Copyright 2006, Dean Edwards
	License: http://www.opensource.org/licenses/mit-license.php
*/

// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
	Array.forEach = function(array, block, context) {
		for (var i = 0; i < array.length; i++) {
			block.call(context, array[i], i, array);
		}
	};
}

// generic enumeration
Function.prototype.forEach = function(object, block, context) {
	for (var key in object) {
		if (typeof this.prototype[key] == "undefined") {
			block.call(context, object[key], key, object);
		}
	}
};

// character enumeration
String.forEach = function(string, block, context) {
	Array.forEach(string.split(""), function(chr, index) {
		block.call(context, chr, index, string);
	});
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
	if (object) {
		var resolve = Object; // default
		if (object instanceof Function) {
			// functions have a "length" property
			resolve = Function;
		} else if (object.forEach instanceof Function) {
			// the object implements a custom forEach method so use that
			object.forEach(block, context);
			return;
		} else if (typeof object == "string") {
			// the object is a string
			resolve = String;
		} else if (typeof object.length == "number") {
			// the object is array-like
			resolve = Array;
		}
		resolve.forEach(object, block, context);
	}
};



// Routines utili all'ordinamento rapido delle colonne delle tables - fine


//
// Funzioni di azzeramento dei campi input di FieldSet
//

function ResetFieldset(idFieldSet,FieldReadOnly)
{
    if (!document.getElementsByTagName) return;
    fields = document.getElementsByTagName("fieldset");
    for (ti=0;ti<fields.length;ti++) {
        thisFields = fields[ti];
        if (((' '+thisFields.getAttribute("id")+' ').indexOf(idFieldSet) != -1)) {
            makeResetFieldset(thisFields,FieldReadOnly);
        }
    }
}

function makeResetFieldset(thisFields, FieldReadOnly)
{	
	//alert("RESET iniziO");
	// Reset input	
	var numInputs = thisFields.getElementsByTagName('input').length
	Inputs = thisFields.getElementsByTagName('input')
	contaRadio = 0;	
	for (i=0; i< numInputs ; i++) {
    	thisInput = Inputs[i];     
    	// Tipo Input Text, Password, file ???
    	if ((thisInput.getAttribute("type") == "text" || thisInput.getAttribute("type") == "password")  )
    	{    	
    		if (FieldReadOnly == 0)  
			{
				if (!thisInput.readOnly)    				
					thisInput.value = "";
					//thisInput.setAttribute("value","");
			}		
			else		
				thisInput.value = "";	
				//thisInput.setAttribute("value","");
			
   			if (thisInput.className =="ContaCaratteri")
   				thisInput.value = "255";	
   				//thisInput.setAttribute("value","255");					
    	}	
    	// Tipo Input Radio	 
    	if (thisInput.getAttribute("type") == "radio" && contaRadio == 0)
    	{
    		//thisInput.checked = true;
    		contaRadio = 1 + contaRadio; 

		}	
		
		// Tipo Input checkbox
    	if (thisInput.getAttribute("type") == "checkbox")
    		thisInput.checked = false;        		
    }
    
	// Reset Textarea
	var numTextareas = thisFields.getElementsByTagName('textarea').length
	Textareas = thisFields.getElementsByTagName('textarea')	
	for (i=0; i< numTextareas ; i++) {		
		if (FieldReadOnly == 0)  
		{
			if (!Textareas[i].readOnly) {   				
				Textareas[i].value = ""; 
			}	
		}		
		else {		
			Textareas[i].value = ""; 
		}	
		
	}
	// Reset Select
	//alert("RESET fine");
}

//
// - fine -
//

///////////////////////////////////////////////////
// INIZIO FUNZIONI UTILI PER I FIELDSET A SCOMPARSA
///////////////////////////////////////////////////
var Class = 
{
  create: function() 
  {
   return function() 
   { 
     this.initialize.apply(this, arguments);
    }
  }
}

Object.extend = function(destination, source) 
{
  for (property in source) 
  {
    destination[property] = source[property];
  }
  return destination;
}

Function.prototype.bind = function(object) 
{
  var __method = this;
  return function() 
  {
    return __method.apply(object, arguments);
  }
}

function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) 
  {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1) 
      return element;

    elements.push(element);
  }

  return elements;
}

//-------------------------

document.getElementsByClassName = function(className) 
{
  var children = document.getElementsByTagName('*') || document.all;
  var elements = new Array();
  
  for (var i = 0; i < children.length; i++) 
  {
    var child = children[i];
    var classNames = child.className.split(' ');
    for (var j = 0; j < classNames.length; j++) 
    {
      if (classNames[j] == className) 
      {
        elements.push(child);
        break;
      }
    }
  }
  
  return elements;
}

//-------------------------

if (!window.Element) 
{
  var Element = new Object();
}

Object.extend(Element, 
{
	remove: function(element) 
	{
		element = $(element);
		element.parentNode.removeChild(element);
	},

  	hasClassName: function(element, className) 
  	{
   	element = $(element);
   	if (!element)
      return;
    	var a = element.className.split(' ');
    	for (var i = 0; i < a.length; i++) 
    	{
      	if (a[i] == className)
      	return true;
    	}
    return false;
  },

  addClassName: function(element, className) 
  {
    element = $(element);
    Element.removeClassName(element, className);
    element.className += ' ' + className;
  },
  
  removeClassName: function(element, className) 
  {
    element = $(element);
    if (!element)
      return;
    var newClassName = '';
    var a = element.className.split(' ');
    for (var i = 0; i < a.length; i++) 
    {
      if (a[i] != className) 
      {
        if (i > 0)
          newClassName += ' ';
        newClassName += a[i];
      }
    }
    element.className = newClassName;
  },
  
  // removes whitespace-only text node children
  cleanWhitespace: function(element) 
  {
    element = $(element);
    for (var i = 0; i < element.childNodes.length; i++) 
    {
      var node = element.childNodes[i];
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) 
        Element.remove(node);
    }
  }
});


//base

var fx = new Object();

fx.Base = function(){};

fx.Base.prototype = 
{

	setOptions: function(options) 
	{

		this.options = 
		{

			duration: 500,

			onComplete: ''

		}

		Object.extend(this.options, options || {});

	},



	go: function() 
	{
		this.duration = this.options.duration;

		this.startTime = (new Date).getTime();

		this.timer = setInterval (this.step.bind(this), 13);
	},



	step: function() 
	{
		var time  = (new Date).getTime();

		var Tpos   = (time - this.startTime) / (this.duration);

		if (time >= this.duration+this.startTime) 
		{
			this.now = this.to;

			clearInterval (this.timer);
			
			this.timer = null;

			if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
			
			RestoreTableHeaders();
		}

		else 
		{
			this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from;

			//this time-position, sinoidal transition thing is from script.aculo.us
		}

		this.increase();
	},



	custom: function(from, to) 
	{
		if (this.timer != null) return;

		this.from = from;

		this.to = to;

		this.go();

	},

	hide: function() 
	{
		this.now = 0;

		this.increase();
	},

	clearTimer: function() 
	{

		clearInterval(this.timer);

		this.timer = null;

	}

}



//stretchers

fx.Layout = Class.create();

fx.Layout.prototype = Object.extend(new fx.Base(), 
{
	initialize: function(el, options) 
	{
		this.el = $(el);

//alert(el);

		this.el.style.overflow = "hidden";

		this.el.iniWidth = this.el.offsetWidth;

		this.el.iniHeight = this.el.offsetHeight;

		this.setOptions(options);

	}

});



fx.Height = Class.create();

Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {	

	increase: function() {

		this.el.style.height = this.now + "px";

	},



	toggle: function() {

		if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);

		else this.custom(0, this.el.scrollHeight);

	}

});



fx.Width = Class.create();

Object.extend(Object.extend(fx.Width.prototype, fx.Layout.prototype), {	

	increase: function() {

		this.el.style.width = this.now + "px";

	},



	toggle: function(){

		if (this.el.offsetWidth > 0) this.custom(this.el.offsetWidth, 0);

		else this.custom(0, this.el.iniWidth);

	}

});



//fader

fx.Opacity = Class.create();

fx.Opacity.prototype = Object.extend(new fx.Base(), {

	initialize: function(el, options) {

		this.el = $(el);

		this.now = 1;

		this.increase();

		this.setOptions(options);

	},



	increase: function() {

		if (this.now == 1) this.now = 0.9999;

		if (this.now > 0 && this.el.style.visibility == "hidden") this.el.style.visibility = "visible";

		if (this.now == 0) this.el.style.visibility = "hidden";

		if (window.ActiveXObject) this.el.style.filter = "alpha(opacity=" + this.now*100 + ")";

		this.el.style.opacity = this.now;

	},



	toggle: function() {

		if (this.now > 0) this.custom(1, 0);

		else this.custom(0, 1);

	}

});

function CambiaPiuMeno(el)
{
	var children = el.childNodes;
	var obj = el.childNodes.item(0);
	var nome_img = obj.src ;
	
	if (nome_img.indexOf("add") != -1 )
	{
		// Trovato il + allora lo si trasorma in -				
		nome_img = "../../images/bullet_delete.gif"; 
		obj.setAttribute('src',nome_img);
		return;
	}
	if (nome_img.indexOf("delete") != -1 )
	{
		// Trovato il - allora lo si trasorma in +
		nome_img = "../../images/bullet_add.gif"; 
		obj.setAttribute('src',nome_img);
		return;
	}
	

};
/////////////////////////////////////////////////
// FINE FUNZIONI UTILI PER I FIELDSET A SCOMPARSA
/////////////////////////////////////////////////

/**
 * Urbi ToolTip
 * ==================================
 * Crea un box sotto il cursore del mouse
 * che può visualizzare sia testo statico 
 * che contenuto HTML
 * 
 * @author Gianfranco Castro
 * @since 03.03.2008
 * @version 1.0
 */


  function TOOLTIP() {
//----------------------------------------------------------------------------------------------------
// Configurazione 
//----------------------------------------------------------------------------------------------------
    this.width = 400;                     // width (in pixels)
    this.bgColor = '#FAF6F0';             // background color
    this.textColor = '#404040';           // text color
    this.borderColor = '#A0A0A0';         // border color
    this.opacity = 100;                    // opacity (percentuale) - non lavora con tutti i browser vecchi (non fa semplicemene la trasparenza)
    this.cursorDistance = 5;              // distanza dal cursore (in pixels)
    

    // NON CAMBIARE
    this.text = '';
    this.obj = 0;
    this.sobj = 0;
    this.active = false;

// -------------------------------------------------------------------------------------------------------
// Funzioni 
// -------------------------------------------------------------------------------------------------------
    this.create = function() {
      if(!this.sobj) this.init();

      var t = '<table border=0 cellspacing=0 cellpadding=4 width=' + this.width + ' bgcolor=' + this.bgColor + '><tr>' +
              '<td align=center><font face=Helvetica  size=2  color=' + this.textColor + '>' + this.text + '</font></td></tr></table>';

      if(document.layers) {
        t = '<table border=0 cellspacing=0 cellpadding=1><tr><td bgcolor=' + this.borderColor + '>' + t + '</td></tr></table>';
        this.sobj.document.write(t);
        this.sobj.document.close();
      }
      else {
        this.sobj.border = '1px solid ' + this.borderColor;
        this.setOpacity();
        if(document.getElementById) document.getElementById('ToolTip').innerHTML = t;
        else document.all.ToolTip.innerHTML = t;
      }
      this.show();
    }

    this.init = function() {
      if(document.getElementById) {
        this.obj = document.getElementById('ToolTip');
        this.sobj = this.obj.style;
      }
      else if(document.all) {
        this.obj = document.all.ToolTip;
        this.sobj = this.obj.style;
      }
      else if(document.layers) {
        this.obj = document.ToolTip;
        this.sobj = this.obj;
      }
    }

    this.show = function() {
      var ext = (document.layers ? '' : 'px');
      var left = mouseX;

      if(left + this.width + this.cursorDistance +100> winX) left -= this.width + this.cursorDistance;
      else left += this.cursorDistance;


      this.sobj.left = left + ext;
      this.sobj.top = mouseY + this.cursorDistance + ext;

      if(!this.active) {
        this.sobj.visibility = 'visible';
        this.active = true;
      }
    }

    this.hide = function() {
      if(this.sobj) this.sobj.visibility = 'hidden';
      this.active = false;
    }

    this.setOpacity = function() {
      this.sobj.filter = 'alpha(opacity=' + this.opacity + ')';
      this.sobj.mozOpacity = '.1';
      if(this.obj.filters) this.obj.filters.alpha.opacity = this.opacity;
      if(!document.all && this.sobj.setProperty) this.sobj.setProperty('-moz-opacity', this.opacity / 100, '');
    }
  }

//----------------------------------------------------------------------------------------------------
// Costruisce il Layer, cattura le coordinate del mouse, creo oggetto Tootip 
//----------------------------------------------------------------------------------------------------
  var tooltip = mouseX = mouseY = winX = 0;

  if(document.layers) {
    document.write('<layer id="ToolTip"></layer>');
    document.captureEvents(Event.MOUSEMOVE);
  }
  else document.write('<div id="ToolTip" style="position:absolute; z-index:99"></div>');
  document.onmousemove = getMouseXY;

  function getMouseXY(e) {
    if(document.all) {
      	/*mouseX = event.clientX + document.documentElement.scrollLeft;
      	mouseY = event.clientY + document.documentElement.scrollTop;
      	mouseX = event.clientX + document.body.scrollLeft;
      	mouseY = event.clientY + document.body.scrollTop;*/
		if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft))
		{
			mouseX=event.clientX+document.documentElement.scrollLeft;
			mouseY=event.clientY+document.documentElement.scrollTop;
		}
		else if(document.body && (document.body.scrollTop || document.body.scrollLeft))
		{
			mouseX=event.clientX+document.body.scrollLeft;
			mouseY=event.clientY+document.body.scrollTop;
		}
		else
		{
			mouseX=event.clientX;
			mouseY=event.clientY;
		}
    }
    else {
      mouseX = e.pageX;
      mouseY = e.pageY;
    }
    if(mouseX < 0) mouseX = 0;
    if(mouseY < 0) mouseY = 0;

    if(document.body && document.body.offsetWidth) winX = document.body.offsetWidth - 25;
    else if(window.innerWidth) winX = window.innerWidth - 25;
    else winX = screen.width - 25;

    if(tooltip && tooltip.active) tooltip.show();
  }

  function toolTip(text, width, opacity) {
    if(text) {
      tooltip = new TOOLTIP();
      tooltip.text = text;
      if(width) tooltip.width = width;
      if(opacity) tooltip.opacity = opacity;
      tooltip.create();
    }
    else if(tooltip) tooltip.hide();
  }


/**
 * toolTip2
 * Funziona come proxy per chiamare toolTip
 * 
 * @param {Object} bgColor
 * @param {Object} borderColor
 * @param {Object} text
 * @param {Object} width
 * @param {Object} opacity
 */
  function toolTip2(bgColor, borderColor, text, width, opacity, txtColor,cursorDistance) {
    if(text) {
      tooltip = new TOOLTIP();
      tooltip.text = text;
      if(width) tooltip.width = width;						// Imposto la larghezza
      if(opacity) tooltip.opacity = opacity;				// Imposto la trasparenza
	  if(bgColor) tooltip.bgColor = bgColor;				// Imposto il colore di backGround
	  if(borderColor) tooltip.borderColor = borderColor;	// Imposto il colore del bordo
	  if(txtColor) tooltip.textColor = txtColor;
	  if(cursorDistance) tooltip.cursorDistance = cursorDistance;
      tooltip.create();
    }
    else if(tooltip) tooltip.hide();
  }


//----------------------------------------------------------------------------------------------------
// === Object UrbiToolTip
//----------------------------------------------------------------------------------------------------

/**
 * Classe Proxy per richiamare agevolmente il tooltip
 * 
 * @author Gianfranco Castro
 * @version 1.0
 */
tp = new Object();
tp.width = 400;                     // width (in pixels)
tp.bgColor = '#faf6f0';             // background color
tp.textColor = '#404040';           // text color
tp.borderColor = '#a0a0a0';         // border color
tp.opacity = 100;                    // opacity (percentuale) - non lavora con tutti i browser vecchi (non fa semplicemene la trasparenza)
tp.cursorDistance = 5;              // distanza dal cursore (in pixels)


/**
 * Visualizzo il tooltip
 * @param {Object} Text
 */
tp.showToolTip = function(Text)
{
	if(Text) {
		toolTip2(this.bgColor, this.borderColor, Text, this.width, this.opacity, this.textColor, this.cursorDistance);
	}
}


/**
 * Imposta i parametri inizali di default
 * per il ToolTip
 */
tp.Reset = function()
{
	this.width = 200;                     // width (in pixels)
	this.bgColor = '#FFFFC0';             // background color
	this.textColor = '#A00000';           // text color
	this.borderColor = '#D00000';         // border color
	this.opacity = 80;                    // opacity (percentuale) - non lavora con tutti i browser vecchi (non fa semplicemene la trasparenza)
	this.cursorDistance = 5;              // distanza dal cursore (in pixels)
}

/**
 * Nasconde il ToolTip
 */
tp.hideToolTip = function()
{
	toolTip2();
}


/**
 * Imposto la largezza
 * @param {Object} valore
 */
tp.setWidth = function(valore)
{
	if(valore) this.width = valore;	
}

tp.getWidth = function()
{
	return this.width;
}

/**
 * Imposto il colore di background
 * @param {Object} bgColor
 */
tp.setBgColor = function(bgColor)
{
	if(bgColor) this.bgColor = bgColor;
}

tp.getBgColor = function()
{
	return this.bgColor;
}

/**
 * Imposto il colore del testo
 * @param {Object} txtColor
 */
tp.setTextColor = function(txtColor)
{
	if(txtColor) this.textColor = txtColor;
}

tp.getTextColor = function()
{
	return this.textColor;
}

/**
 * Imposto il colore del bordo
 * @param {Object} borderColor
 */
tp.setBorderColor = function(borderColor)
{
	if(borderColor) this.borderColor = borderColor;
}

tp.getBorderColor = function()
{
	return this.borderColor;
}

/**
 * Imposta la trasparenza/opacita
 * @param {Object} Opacity
 */
tp.setOpacity = function(Opacity)
{
	if(Opacity) this.opacity = Opacity;
}

tp.getOpacity = function()
{
	return this.opacity;
}

/**
 * Imposto la distanza dal cursore
 * @param {Object} cursorDistance
 */
tp.setCursorDistance = function(cursorDistance)
{
	if(cursorDistance) this.cursorDistance = cursorDistance;
}



tp.getCursorDistance = function()
{
	return this.cursorDistance;
}

// --------- FUNZIONI PER MENU HTML, DA INCLUDERE NEL PROGRAMMA -- INIZIO -----------------
function makeMenuHTMLMain(m_name,x,y,direction)
{
	var myarray = eval("ar"+ m_name);
	if( myarray && (myarray.length-3)%5 !=0)
	{		
		alert("Il menu "+a_name+" non e' corretto!");
		return;
	}

	var n=myarray.length/3;
	var indice=0;
	for(var i=3; i <myarray.length; i=i+5)
	{
		indice = indice +1;
		ShowMenuHtmlMain('Menu',indice);
	}
	document.writeln("</ul>");
}

function showMenuHTMLMain(m_name,indice)
{
	var myarray = eval("ar"+ m_name + "_" + indice);
	if( myarray && (myarray.length-3)%5 !=0)
	{		
		alert("Il menu "+a_name+" non e' corretto!");
		return;
	}

	var n=myarray.length/3;
	var j=0;
	
	document.writeln("div id='SM" + indice + "' class='SMENU' onmouseout='javascript:hideMenuMain(" + indice
		+ ");' onmouseover='javascript:takeMenuMain(" + indice + ");'");
	for(var i=3; i <myarray.length; i=i+5)
	{
		j = j +1;
		document.writeln("<a href='" + myarray[i+1] + "' class='SMENU'>" + myarray[i] + "</a>");
	}
	document.writeln("</div>");
}

function hideMenuHTMLMain(Num)
{
	var obj = document.getElementById('SM'+Num);				
	obj.style.visibility = 'hidden';		
}	
	
function takeMenuHTMLMain(Num)
{
	var obj = document.getElementById('SM'+Num);				
	obj.style.visibility = 'visible';	
}


// ------------------ FUNZIONI PER MENU HTML -- FINE -----------------


// ------------------ FUNZIONI SCROLL -- INIZIO -----------------
function getScrollY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return scrOfY ;
}

// ------------------ FUNZIONI SCROLL -- FINE -----------------
function ImpostaCampoFinestraMod(nome_campo)
{
	if(Doc.getFld(0,nome_campo)=='0' || Doc.getFld(0,nome_campo)=='')
	{
		Doc.setFld(0,nome_campo, 1)
	}
	else
	{
		Doc.setFld(0,nome_campo, 0);
	}
}


// Funzioni di manipolazione dei tab di primo e secondo livello (Stili Urbi 2009) - INIZIO //
	
function SetActiveTab(tab)
	{
		if (null==tab)
			return;
		
		var pos_link = tab.id.indexOf("_link");
		var radice = tab.id.substring(0,pos_link);
		var link_cliccato = tab.id.substring(pos_link + 5,tab.id.length);
		

		//Conto quanti sono i XXX_linkN
		var count=0;
		var alist = document.getElementsByTagName('a');
		for (i=0; i<alist.length; i++)
		{
			if (alist[i].id.indexOf(radice + "_link") != - 1) count++;
		}

		var curelemID;
		//li oscuro tutti tranne lui
		for (i=1; i<=count; i++)
		{
			curelemID = radice+'_link'+i;
			if (document.getElementById(curelemID) != null) document.getElementById(curelemID).className = "";
		}
		document.getElementById(tab.id).className = "selezionato";		
		
		//Controllo se esistono dei sottotab2
		var count=0;
		var divlist = document.getElementsByTagName('div');
		var nome_tab= radice + "_" + link_cliccato;
		for (i=0; i<divlist.length; i++)
		{
			if (divlist[i].id.indexOf(radice + "_") != - 1)
			{
				if (divlist[i].id != nome_tab) 	document.getElementById(divlist[i].id).style.display="none";
				else document.getElementById(divlist[i].id).style.display="";
			}
		}
		if(document.getElementById(nome_tab) != null)
		{
			//conto quanti link ci sono allegati a quel sottotab
			var count=0;
			for (i=0; i<alist.length; i++)
			{
				if(alist[i].id.indexOf(nome_tab + "_link") != - 1)
				{
					document.getElementById(alist[i].id).className = "";		
				}
			}
			document.getElementById(nome_tab + '_link1').className = "selezionato";		
		}
	}	

// Funzioni di manipolazione dei tab di primo e secondo livello (Stili Urbi 2009) - FINE //


// ==== INIZIO: Funzioni per il calcolo dell'IBAN  === //
function calcola_iban(abi, cab, contoc){
    // === Variabile di uscita
    var Output = new Array();

	// === verifica ABI:
	if(abi.search(/^[0-9]{5}$/)==-1)
	{
	   alert("ABI: Inserire 5 cifre.");
	   return(false);
    }

	// === verifica CAB:
	if(cab.search(/^[0-9]{5}$/)==-1)
	{
        alert("CAB: Inserire 5 cifre.");
        return(false);
    }

	// === verifica Numero Conto Corrente:
	if(contoc.search(/^[a-zA-Z0-9]{12}$/)==-1)
	{
        alert("inserire 12 caratteri alfanumerici per il conto corrente.");
        return(false);
    }

    // === Creo il codice BBAN e IBAN
	var NCC=contoc.toUpperCase()
	var bban=get_BBAN(abi,cab,NCC);
	var iban=get_IBAN(bban);

    Output.push(iban);
    Output.push(bban.charAt(0));

    return Output;
}

function get_BBAN(pABI,pCAB,pNCC){
	var vABI=r0(pABI,5);
	var vCAB=r0(pCAB,5);
	var vNCC=r0(pNCC,12);
	if( vABI.search(/^[0-9]{5}$/)==-1 || vCAB.search(/^[0-9]{5}$/)==-1 || vNCC.search(/^[0-9A-Z]{12}$/)==-1)
		return("");
	chS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	odA=new Array(1,0,5,7,9,13,15,17,19,21,1,0,5,7,9,13,15,17,19,21,2,4,18,20,11,3,6,8,12,14,16,10,22,25,24,23);
	evA=new Array(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);
	var DAN=""+vABI+vCAB+vNCC;
	var s=0;
	var i=-1;
	while(i!==21)
	{
		s+=odA[chS.indexOf(DAN.charAt(++i))]
		+evA[chS.indexOf(DAN.charAt(++i))];
	}
	return(chS.charAt(10+s%26)+vABI+vCAB+vNCC);
}

function get_IBAN(pBBAN){
	if(pBBAN.search(/^[A-Z][0-9]{5}[0-9]{5}[A-Z0-9]{12}$/)==-1)
		return("");

	var vIBAN=pBBAN+"IT00";
	var w="";

	for(var i=0;i<27;i++)
		w+="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(vIBAN.charAt(i));

	while(w.length>2)
		w=parseInt(w.substr(0,7),10)%97+w.substr(7);

	return("IT"+r0(98-parseInt(w,10)%97,2)+pBBAN);
}

function r0(s,l){
	var c=""+s;
	while(c.length<l)c="0"+c;
	return(c);
}
// ==== FINE: Funzioni per il calcolo dell'IBAN  === //


// ===== CONTROLLO FORMALE DEL CODICE FISCALE == //
// Verifica codice fiscale
function ControllaCF(cf)
{
	var validi, i, s, set1, set2, setpari, setdisp;
	if( cf == '' )  return '';
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return "La lunghezza del codice fiscale non è\n"
		+"corretta: il codice fiscale dovrebbe essere lungo\n"
		+"esattamente 16 caratteri.\n";
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return "Il codice fiscale contiene un carattere non valido `" +
				cf.charAt(i) +
				"'.\nI caratteri validi sono le lettere e le cifre.\n";
	}
	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) )
		return "Il codice fiscale non è corretto:\n"+
			"il codice di controllo non corrisponde.\n";
	return "";
}


function RestoreTableHeaders()
{			
	// ripristino le posizioni di eventuali header (valido per IE) - inizio
	document.getElementsByClassName('tbl_generica_100x100')
	var foundtables = document.getElementsByClassName('tbl_generica_100x100');
	for(z = 0; z < foundtables.length; z++)
	{
		//foundtables[z].scrollTop = foundtables[z].scrollTop + 1;
		tmpHtml = foundtables[z].scrollTop = foundtables[z].innerHTML;
		foundtables[z].scrollTop = foundtables[z].innerHTML = tmpHtml;
	}
	
	// ripristino le posizioni di eventuali header (valido per IE) - fine
}


//Riempi i char a sinistra con un carattere passato come argomento
// es: campi numerici: mette gli zeri non significativi
// es: chiamo CharSinistra(campo,2,'0') 
//     -> se nel campo ho 10 lascia 10 
//     -> se nel campo ho  1 mette 01
//
function CharASinistra(fldobj,lung,car)
{
	var str = fldobj.value+"";
	var newstr = "";

	for(var i=1;i<=lung; i++)
	{
		var tmpchar = str.charAt(str.length - i);
	  if (tmpchar!="" && tmpchar!=" ")
		{
			newstr = tmpchar + newstr;
		}
		else
		{
			newstr = car + newstr;
		}
	}

	fldobj.value = newstr;

  return true;
}


