
					
	
					var MSG_CAMPO_MANDATORY="Il campo è obbligatorio";
					var MSG_INVALID_BOUND="Errore nella definizione del form: il valore minimo di caratteri è superiore al valore massimo!";
					var MSG_MIN_CHAR="Il valore da inserire deve avere almeno ";
					var MSG_MAX_CHAR="Il valore da inserire non puo avere piu di ";
					var MSG_MAX_EQ_MIN_CHAR="Il campo deve avere ";					
					var MSG_CHAR=" caratteri";
					var MSG_INTEGER="Devi inserire solo caratteri numerici";
					var MSG_REAL="Devi inserire un valore reale!";
					var MSG_CURRENCY="Devi inserire un valore corretto!";
					var MSG_DATE_SYNTAX="La sintassi non è corretta";
					var MSG_DATE_NOT_VALID_YEAR="L'Anno deve essere compreso tra il ";
					var MSG_DATE_NOT_VALID_YEAR_AND=" e il ";
					var MSG_DATE_NOT_VALID="La data inserita non è valida";
					var MSG_N_CONTO_VALID="N. conto:\n\n";
					var MSG_N_CONTO_VALID_3="\nControllare la soluzione proposta.";
					var MSG_N_CONTO_VALID_0="Il numero deve avere ";
					var MSG_N_CONTO_VALID_1=" caratteri alfanumerici.\n";
					var MSG_N_CONTO_VALID_2="Sono presenti dei caratteri non validi.\n";
					var MSG_RICHIESTA_GIA_INOLTRATA="Richiesta già inoltrata.";
					var MSG_CF_LENGTH="La lunghezza del codice fiscale non è\ncorretta: il codice fiscale dovrebbe essere lungo\nesattamente 16 caratteri.\n";
					var MSG_CF_CHAR_INVALID_1="Il codice fiscale contiene un carattere non valido `";
					var MSG_CF_CHAR_INVALID_2="'.\nI caratteri validi sono le lettere e le cifre.\n";
					var MSG_CF_NON_CORRETTO="Il codice fiscale non è corretto:\nil codice di controllo non corrisponde.\n";
					var MSG_PIVA_NON_CORRETTA="La lunghezza della partita IVA non è\ncorretta: la partita IVA dovrebbe essere lunga\nesattamente 11 caratteri.\n";
					var MSG_PIVA_CHAR_INVALID_1="La partita IVA contiene un carattere non valido `";
					var MSG_PIVA_NO_TUTTI_ZERI="La partita IVA non è corretta";
					var MSG_PIVA_NON_VALIDA="La partita IVA non è valida:\nil codice di controllo non corrisponde.\n";
					var MSG_CF_PIVA_NON_CORRETTI="La lunghezza del dato inserito non è corretta:\nla partita IVA dovrebbe essere lunga\nesattamente 11 caratteri, \nil codice fiscale dovrebbe essere lungo\nesattamente 16 caratteri.\n";
					var MSG_ABI_NON_CORRETTO="La lunghezza del codice immesso non è\ncorretta: dovrebbe essere lungo\nesattamente 5 cifre.\n";
					var MSG_ABI_CHAR_INVALID_1="Il codice contiene un carattere non valido `";
					var MSG_PIVA_CHAR_INVALID_2="'.\nI caratteri validi sono le cifre.\n";
					var MSG_IBAN_LENGTH="Il codice IBAN deve essere lungo 27 caratteri alfanumerici.";
					var MSG_IBAN_FORMA="Il codice IBAN deve corrispondere con i codici ABI, CAB e N. Conto.";
					var MSG_IBAN_NON_CORRETTO="Il codice IBAN non è corretto:\nil codice di controllo non corrisponde.\n";
					var MSG_DATA_PRECEDE="La data inserita è precedente a quella odierna (";
					var MSG_DATA_FINE=").";
					var MSG_DATA_INTERV_1="La data inserita (";
					var MSG_DATA_INTERV_2=") deve essere compresa tra\n ";
					var MSG_DATA_INTERV_3=" e ";
					var MSG_DATA_SUCC=") deve essere successiva a ";
					var MSG_IMPORTO_FORMATO="contiene ";
					var MSG_IMPORTO_FORMATO_1=" piu' di ";
					var MSG_IMPORTO_FORMATO_2=" cifre intere";
					var MSG_IMPORTO_FORMATO_3=" cifre decimali";
					var MSG_CAMPO_CONTRL="Il campo ";
					var MSG_CAMPO_CONTRL_1=" eccede le dimensioni massime\n( ";
					var MSG_CAMPO_CONTRL_2="  caratteri) Elimino i caratteri eccedenti?";
					var MSG_CIN_NON_CORRETTO="Il CIN non è corretto\n";
					var MSG_CONFERMA_ELIMINAZIONE_ANAGRAFICA="Confermi eliminazione dell'anagrafica?";
					var MSG_CONFERMA_ELIMINAZIONE_DISTINTE="Confermi eliminazione di ";
					var MSG_CONFERMA_ELIMINAZIONE_OGGETTO=" distinta?";
					var MSG_CONFERMA_ELIMINAZIONE_OGGETTI=" distinte?";
					var MSG_CONFERMA_ELIMINAZIONE_DISPOSIZIONI=" disposizioni?";
					var MSG_CONFERMA_ELIMINAZIONE_DISPOSIZIONE=" disposizione?";
					var MSG_CAP_NON_CORRETTO="Il CAP immesso non e' corretto,\ndovrebbe essere esattamente\ndi 5 cifre e diverso da 00000.\n";
					var MSG_CODICE_PAESE_ERR="Codice paese errato.";
					var MSG_LENGTH_IMPORTO="Attenzione: la lunghezza dell' Importo, espresso come intero, non puo' superare i 15 caratteri.";
					var MSG_LUNGHEZZA_ERRATA="Lunghezza errata.";
					var MSG_CODICE_PAESE_ERRATO="Codice paese errato.";
					var MSG_IBAN="IBAN";
					var MSG_CARATTERE_ILLEGALE="Non e' possibile utilizzare nella ricerca il seguente carattere: ";
					
        // GLOBAL VARIABLES

        // Minimum year allowed
        var minYear = 1900;
        // MaximuM year allowed
        var maxYear = 2050;
        // With a two char year, if yy>yearLimit => 19yy, else 20yy
        var yearLimit = 10;
				 // Year Italian National Holidays
        var yearHolidays = new Array("1/1", "1/6", "4/25", "5/1", "6/2", "8/15", "11/1", "12/8", "12/25", "12/26", "EASTER_MONDAY");
		var yearHolidaysNumber = yearHolidays.length;

		// Year Italian National Holidays (Date)
        var yearHolidaysDates = new Array();
		var yearHolidaysDatesNumber = 0;
		
        // Separators allowed for the date check        
        separators = new Array("/","\\","-");

        // Message variables:
        mandatoryFieldMsg = MSG_CAMPO_MANDATORY;
					invalidBoundsMessage =MSG_INVALID_BOUND;
					minCharMsg = MSG_MIN_CHAR;
					maxCharMsg = MSG_MAX_CHAR;
					equalCharMsg = MSG_MAX_EQ_MIN_CHAR;
					charMsg = MSG_CHAR;
					integerMsg = MSG_INTEGER;
					realMsg = MSG_REAL;
					currencyMsg = MSG_CURRENCY;
					dateSyntaxMsg = MSG_DATE_SYNTAX;
					dateNotValidYearMsg = MSG_DATE_NOT_VALID_YEAR;
					dateNotValidYearAndMsg =MSG_DATE_NOT_VALID_YEAR_AND;
					dateNotValidMsg = MSG_DATE_NOT_VALID; 
					// Variable useful to know if a form is Ok.
        var isOkForm;
        
        // Variable useful to manage inputs without checkValue() default function.
        var isOkOthersInputs;

        // Variable that stores the name of the field checked
        var fieldCheckedName;
			
				/**
        * Check the data passed.
        * If the value is ok, return it eventually "normalized"
        * in a correct form
        *
        * Otherwise, this function shows an alert with an error message, and returns
        * null.
        *
        * type = {STRING | INTEGER | REAL | CURRENCY | DATE | CF | PIVA | CF_PIVA | ABI_CAB | CAP}
        * mandatory = {TRUE |FALSE}
        *
        * Default values:
        *
        *   mandatory = FALSE
        *   type      = STRING
        *   minlength = 0
        *   maxlength = 0
        *
        * Notes :The bound check (with the "minlength" and "maxlength" parameters) is done
        * only if the type is not "DATE".
        *
        */
				

				function checkFieldValue(value, mandatory, type, minlength, maxlength)
        {
            // Sets the default values
            if (mandatory == '')
                mandatory ='FALSE';
            if (type == '')
                type = 'STRING';
            if (minlength == '')
                minlength = 0;
            if (maxlength == '')
                maxlength = 0;
            // Check if the value exist
            if ((mandatory == 'TRUE')  && (isEmpty(value)) )
            {
                //alert(fieldCheckedName+" : "+mandatoryFieldMsg);
                return null;
            }
            if (isEmpty(value))
            {
                return "";
            }

            switch (type)
            {
            	case "ACCOUNT":
            	    // The field is an account number
            	    var account = checkAccountFormat(value, minlength, maxlength)
                    return account;
                    break;
                case "STRING":
                    // The field is a string field.
                    if (!checkBounds(value,minlength,maxlength))
                        return null;
                    break;

                case "INTEGER":
                    // The field is an integer  field.
                    if ( !checkBounds(value,minlength,maxlength) ||
                         !checkInteger(value))
                        return null;
                    break;

                case "REAL":
                    // The field is a real field.
                    if ( !checkBounds(value,minlength,maxlength) ||
                         !checkReal(value))
                        return null;
                    break;

                case "CURRENCY":
                    // The field is a currency field.
                    if ( !checkBounds(value,minlength,maxlength) ||
                         !checkCurrency(value))
                        return null;
                    break;
		    
		case "CURRENCY_FILTRO":
                    // The field is a currency field.
                    if ( !checkBoundsFiltro(value,minlength,maxlength) ||
                         !checkCurrency(value))
                        return null;
                    break;

                case "DATE":
                    // The field is a date field.
                    var date = checkDate(value,minYear,maxYear,yearLimit)
                    return date;
                    break;
                case "CF":
                    // The field is a codice fiscale field.
                    var cfup = checkCF(value)
                    return cfup; //UPPERCASE
                    break;
                case "PIVA":
                    // The field is a partita iva field.
                    if ( !checkPIVA(value) )
                        return null;
                    break;
                case "CF_PIVA":
                    // The field is a codice fiscale or a partita iva field (depending on size).
                    var cfpivaup = checkCFPIVA(value)
                    return cfpivaup; //UPPERCASE
                    break;
                case "ABI_CAB":
                    // The field is a code ABI or CAB.
                    var abicab = checkABICAB(value)
                    return abicab;
                    break;
                case "CAP":
                    // The field is a CAP (Italian).
                    var cap = checkCAP(value)
                    return cap;
                    break;
                default:
                    return null;
            }
            // If all is ok...
            return value;
        }
				
	/**
	*Usata pei i campi importo
	*Controlla che il valore, se intero sia al max di 15 caratteri, se decimale di maxlength
	*/
	function checkValueLen(field, form, mandatory, type, minlength, maxlength, messageString)
	{
		if (form == "")
		{
			form= "forms[0]";
		}
		 // Construct the field name
		if (messageString == null)
			fieldCheckedName = field;
		else
		{
			fieldCheckedName = messageString;
		}
		fieldName = "document."+form+"."+field;
		// Retrieve the field reference
		var evalform = eval("document."+form);
		value = evalform.elements[field].value;
		var temp=trimString(value).split(",");
		if(temp[0].length <= 15)
			return(checkValue(field, form, mandatory, type, minlength, maxlength, messageString));
				
		else
			return(checkValue(field, form, mandatory, "CURRENCY_FILTRO", minlength, "15", messageString));
	}		
		/**
        * Check the value in the passed field, in the passed form.
        * if the form parameter is null or empty, the default value is forms[0]. For the
        * "mandatory", "type", "minlength", "maxlength" parameters see the checkFieldValue
        * function.
        * If the field value is incorrect, is cancelled by this function
        *
        */
				
				 function checkValue(field, form, mandatory, type, minlength, maxlength, messageString)
        {
            if (form == "")
            {
                form= "forms[0]";
            }

            // Construct the field name
            if (messageString == null)
                fieldCheckedName = field;
            else
            {
                fieldCheckedName = messageString;
            }
            fieldName = "document."+form+"."+field;

            // Retrieve the field reference

            var evalform = eval("document."+form);

            value = evalform.elements[field].value;

            if (value != null)
            {
                value1 = removeNL(value);
            }
            else
            {
                value1 = value;
            }

            var returnValue = checkFieldValue(trimString(value1), trimString(mandatory),trimString(type),trimString(minlength),trimString(maxlength));
	
						if( type == 'ACCOUNT')
						{
							if(returnValue != value)
							{
								if (returnValue == null)
                                {
                                	evalform.elements[field].value="";
                                }
                                else
                                {
									evalform.elements[field].value = returnValue;
								}
								isOkForm=null;
								return;
							}
						}	

            if (returnValue == null)
            {
                // fieldRef = eval(fieldName);
                evalform.elements[field].value="";
                isOkForm=null;
                return;
            }
            // If the value returned is different from the field value, change it.
            else if (value != returnValue)
            {
                evalform.elements[field].value = returnValue;
            }
            
            if( type == 'CF' || type == 'PIVA' || type == 'CF_PIVA')
			{
				if(isOkOthersInputs == false)
				{
					isOkForm = null;
					isOkOthersInputs = true;
					return false;
				}
				else
				{
					isOkOthersInputs = true;
					return true;
				}
			}
			
        }
        
    function delCharacters(stringa) {
		stringa = duplicaApici(stringa);
		stringa = stringa.replace(/\\/g,"");//elimino tutte le occorrenze del carattere "\"
		stringa = stringa.replace(/;/g,"");//elimino tutte le occorrenze del carattere ";"
		return stringa;
	}

	function duplicaApici(stringa) {
	    //alert(stringa);
	    var idx = -1;
	    idx = stringa.indexOf("'");
	    if (idx >= 0) {
	        var count = 1;
	        var nextChar = stringa.substring(idx + count,idx + count + 1);
	        //alert(nextChar);        
	        while (nextChar == "'") {
	           count = count +1;
	           nextChar = stringa.substring(idx + count,idx + count + 1);
	           //alert(nextChar);
	        }
	        if (count % 2 != 0) {
	            //alert("PRIMA " + stringa);
	            stringa = stringa.substring(0, idx + count) + "'" + stringa.substring(idx + count);
	            //alert("DOPO " + stringa);
	        }
	        idx = stringa.indexOf("'", idx + count + 1);
	        if (idx >= 0) {
	             return stringa.substring(0, idx) + duplicaApici(stringa.substring(idx));   
	        }
	    }
	    return stringa;
	}
        
        function checkValueApex(field, form, mandatory, type, minlength, maxlength, messageString)
        {
            if (form == "")
            {
                form= "forms[0]";
            }

            // Construct the field name
            if (messageString == null)
                fieldCheckedName = field;
            else
            {
                fieldCheckedName = messageString;
            }
            fieldName = "document."+form+"."+field;

            // Retrieve the field reference

            var evalform = eval("document."+form);
            value = evalform.elements[field].value;
            value = delCharacters(value);
			evalform.elements[field].value = value;
			return(checkValue(field, form, mandatory, type, minlength, maxlength, messageString));
			
        }

				
			
				/**
        * Check if the inputStr parameter is empty or null
        */
				
				 function isEmpty(inputStr)
        {
            if (inputStr == null || inputStr == "")
                return true;
            return false;
        }
				
				/**
        * Check if the value length is greater than "minlength"
        */
				
				function checkMin(value, minlength)
        {
            var length=value.length;
            if (length   <  minlength)
                return false;
            else return true;
        }
				
				/**
        * Check if the value length is lower than "maxlength"
        */
				
				function checkMax(value, maxlength)
        {
            var length=value.length;
            if (length  >  maxlength)
                return false;
            else return true;
        }
				
				
				/**
				* Check if the account number format is valid
				*/
			
				function checkAccountFormat(value, minlength, maxlength)
	{
		if(value.length == 0) return value;
		
   	    var check = true;
   	    
   	    minlength = 12;
   	    maxlength = 12;        
   	     	    		
   	    //controllo lunghezza
   	    var msg, msg1="", msg2="", msg3;
   	    msg = MSG_N_CONTO_VALID;
				msg3 = MSG_N_CONTO_VALID_3;
					if(value.length < minlength || value.length  >  maxlength)
   	    {
   	    	msg1 = MSG_N_CONTO_VALID_0 + minlength + MSG_N_CONTO_VALID_1;
					check = false;
   	    }
   	    
   	    //controllo caratteri alfanumerici
   	    value = value.toUpperCase();
   	    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   	    accountLength = value.length;
   	    for(i=0; i < accountLength; i++)
            {
                if( validi.indexOf( value.charAt(i) ) == -1 )
                {
                    msg2 = MSG_N_CONTO_VALID_2;
					check = false;
                    
                    //modifica caratteri
                    value = value.replace(value.charAt(i), "");
                    i--;
                    accountLength = value.length;
                }
            }
   	    
   	    //modifica lunghezza 
   	    while(value.length < minlength)  value = "0" + value;
   	    
   	    if(!check)
   	    {
   	    	alert(msg+msg1+msg2+msg3);
   	    }
   	    
   	    return value;
	}
	
				
				/**
        * Check if the value length is between than "maxlength"
        * and the "minlength" value.
        * if maxlength=0, doesn't make any control (no check) and return true.
        * if minlength == maxlength,ok (the field MUST have n characters).
        * if minlength < maxlength, show an alert
        * Show an alert and returns null if the check fails.
        */
			
		function checkBounds(value, minlength, maxlength)
        {
            if (eval(minlength)>eval(maxlength))
            {
                alert(fieldCheckedName+" : "+invalidBoundsMessage);
                return false;
            }
            if (maxlength==0)
                return true;
			if ((eval(minlength)==eval(maxlength))&&(!checkMin(value, minlength)))
			{
				alert(fieldCheckedName+" : "+equalCharMsg+ minlength+charMsg);
                return false;
			}		
            if (!checkMin(value, minlength))
            {
                alert(fieldCheckedName+" : "+minCharMsg+ minlength+charMsg);
                return false;
            }
            if (!checkMax(value, maxlength))
            {
                alert(fieldCheckedName+" : "+maxCharMsg+ maxlength+charMsg);
                return false;
            }
            return true;
        }

	function checkBoundsFiltro(value, minlength, maxlength)
        {
            if (eval(minlength)>eval(maxlength))
            {
                alert(fieldCheckedName+" : "+invalidBoundsMessage);
                return false;
            }
            if (maxlength==0)
                return true;
            if (!checkMin(value, minlength))
            {
                alert(fieldCheckedName+" : "+minCharMsg+ minlength+charMsg);
                return false;
            }
            if (!checkMax(value, maxlength))
            {
		alert(MSG_LENGTH_IMPORTO);
                return false;
            }
            return true;
        }
			
				/**
        * Check the value passed. Return false if the string is not correct
        * In this version checkString() returns always true.
        */
				
				function checkString(value)
        {
            return true;
        }
				
				
				/**
        * Check the value passed. Return false if the integer is not correct.
        * A integer value is formed of digits with non mandatory sign.
        * Correct integer are:                  10123
        *                           +10
        *                           -567
        *
        */
				
				 function checkInteger(value)
        {
            input = value.toString();
            for (var i = 0; i  <  input.length; i++)
            {
                var inputChar = input.charAt(i);

                // Skip the sign
                if ((i == 0 &&  inputChar == "-") || (i == 0  &&  inputChar == "+"))
                {
                    continue
                }
                if (inputChar <  "0" || inputChar >  "9")
                {
                    alert(fieldCheckedName+" : "+integerMsg);
                    return false;
                }
            }
            return true;
        }
				
				
				/**
        * Check the value passed. Return false if the real is not correct
        * A real value is formed only by digits and one "." or ",".
        * Correct real are:             3.14
        *                       123123
        *                       0,12323123
        *
        * Uncorrect real are:   pippo
        *                       24352345.
        *                       ,13413434
        *                       .1234.,123
        *
        */
				
				function checkReal(value)
        {
            decimal = false;
            input = value.toString();
            for (var i = 0; i  <  input.length; i++)
            {
                var inputChar = input.charAt(i);

                // Skip the sign
                if ((i == 0  && inputChar == "-") || (i == 0  &&  inputChar == "+"))
                {
                    continue
                }
                remainingLength = input.length - i -1;
                // Skip the FIRST '.' or ','
                if ( (inputChar == "." &&  !decimal  &&  (remainingLength!=0)) || (inputChar == ","  && !decimal &&  (remainingLength!=0)))
                {
                    decimal = true;
                    continue
                }
                if (inputChar  <  "0" || inputChar >  "9")
                {
                    alert(fieldCheckedName+" : "+realMsg)
                    return false
                }
            }
            return true;
        }


/**
        * Check the value passed. Return false if the currency is not correct
        * A correct currency value is a numeric string thah can have
        * a "." every 3 digits and a ",".
        *
        * Correct currency are:     10000000
        *               1.000.000
        *               123452,123
        *               1.234.234,23
        *               1.000
        *               1.000,12
        *
        * Uncorrect currency are:   pippo
        *               24352345.
        *               1,23,2
        *               1.000.000,2.3
        *               100000,
        *
        */

				function checkCurrency(value)
        {
            decimal = false;
            input = value.toString();
            for (var i = 0; i  < input.length; i++)
            {
                var inputChar = input.charAt(i);

                /* Skip the '.' character if:
                    1) the i+4 character is '.' or ','
                    2) the length of the remaining string is 3
                       (2.00 is not valid, but 2.000 is ok)
                */
                remainingLength = input.length - i -1;
                                //1.000.0000
                if (inputChar =="." && !decimal && remainingLength == 3)
                    continue;
                else if (remainingLength > 3)
                    if ((inputChar =="." && !decimal && input.charAt(i+4)==".") ||
                        (inputChar =="." && !decimal && input.charAt(i+4)==","))
                        continue

                // Skip the FIRST '.' or ','
                if (inputChar == "," && !decimal && (remainingLength!=0) )
                {
             if (remainingLength==2)
			{
				decimal = true;
				continue;
			}
			else
			{
				alert(fieldCheckedName+" : "+currencyMsg);
				return false;
			}
                }
                if (inputChar < "0" || inputChar >  "9")
                {
                    alert(fieldCheckedName+" : "+currencyMsg)
                    return false;
                }
            }
            return true;
        }

				
				/**
	* Check the value passed. Return null if the date is not correct, else
	* return the date in the form gg/mm/aaaa.
	*
	* This method parse all data in the format:
	*                   gg/mm/aaaa
	*                   gg/mm/aa
	*                   gg-mm-aaaa
	*                   gg-mm-aa
	*
	* Every 4 digit values are valid year.
	* The year with 2 digits are converted with this rule:
	*   if yy > yearLimit => 19yy
	*   otherwise, 20yy
	*
	*/
				
				function checkDate(value,minYear,maxYear,yearLimit)
	{
		// Controls the validity of a date (gg/mm/aaaa)
		isOk=false;
		sintax_error=false;
		msg="";

		// if the date passed is empty, return it
		if (!value)
		{
			return value;
		}
		var value = checkSeparator(trimString(value));
      // This block controls only if there are two separators characters
		s1=value.indexOf("/");
		// s1 and s2 are the separator positions
		if (s1!=-1)
		{
			// Retrive the position of the next separator
			s2=(s1+1)+(value.substring(s1+1)+1).indexOf("/");
			if (s2==-1 || s2==s1) sintax_error=true;
		}
		else sintax_error=true;
      
		if (!sintax_error)
		{
			sg_dd=value.substring(0,s1);
			sg_mm=value.substring(s1+1,s2);
			sg_yyyy=value.substring(s2+1);
			var sentinel;
			var sentinelYear;
			sentinelDay=sg_dd.substring(0,1);
			if(sentinelDay=='0') sg_dd=sg_dd.substring(1,sg_dd.length);
			dd=parseInt(sg_dd);
			sentinelMonth=sg_mm.substring(0,1);
			if(sentinelMonth=='0') sg_mm=sg_mm.substring(1,sg_mm.length);
			sentinelYear=sg_yyyy.substring(0,1);
			if(sentinelYear=='0') sg_yyyy=sg_yyyy.substring(1,sg_yyyy.length);
			mm=parseInt(sg_mm);
			yyyy=parseInt(sg_yyyy);
			yearDigitError=false;

			if ( (""+dd)!=sg_dd || (""+mm)!=sg_mm || (""+yyyy)!=sg_yyyy || isNaN(dd)||isNaN(mm)||isNaN(yyyy) || dd > 31 || mm > 12)
			{
			   sintax_error=true;
			}
			else 
			{
				if (mm==2)
				{
					if ( dd>28 || 1 > dd)
					{
					// If the day is 29
						if(dd==29)
						{
							if(yyyy%4==0)
							{
								if(yyyy%400==0)
								{
									isOk=true;
								}
								else
								{
									if(yyyy%100!=0) isOk=true;
								}
							}
							else
							{
								isOk=false;
							}
						}
						// Else error
						else
						{
							isOk=false;
						}
					}
					else isOk=true;
				}
				else if ((mm==4)||(mm==6)||(mm==9)||(mm==11))
				{
					if( dd>30 || 1 > dd ) isOk=false;
					else isOk=true;
				}
				else 
				{
				   if( dd>31 || 1 > dd ) isOk=false;
					else isOk=true;
				}

				if (isOk)
				{
              
					// Add the "0" string if the day is of one digit
					if ((dd+"").length==1)	dd = "0"+dd;

					if (mm > 12 || 1 > mm || dd>31 || 1 > dd) isOk=false;
					else isOk=true;

					// Add the "0" string if the month is of one digit
					if ((mm+"").length==1)	mm = "0"+mm;

					valueApp = dd+"/"+mm+"/";


					if  (sg_yyyy.length==4)
					{
						if ((yyyy < minYear)||(yyyy>maxYear))
						{
							isOk=false;
							msg = dateNotValidYearMsg+minYear+dateNotValidYearAndMsg+maxYear;
						}
						else	isOk=true;
					}
					else if (sg_yyyy.length==2 && sentinelYear=='0')
					   {
					     if (yyyy > yearLimit)
								sg_yyyy="19"+yyyy;
							else    
								sg_yyyy="20"+yyyy;
					   }
						
					else
						
						if ((sg_yyyy.length==2)|| (sg_yyyy.length==1 && (sentinelYear=='0')))
						{
								if (yyyy > yearLimit)
									if (sentinelYear=='0')
										sg_yyyy="190"+yyyy;
									else
										sg_yyyy="19"+yyyy;
								else    
									if (sentinelYear=='0')
										sg_yyyy="200"+yyyy;
									else
										sg_yyyy="20"+yyyy;
							// dateWithoutYear=value.substring(0,value.length-2);
							// value = dateWithoutYear + sg_yyyy;
						}
						else
						{
							yearDigitError=true;
							msg="";
						}
					// The result value...
					value = valueApp + sg_yyyy;
				}
			}
		}
		else
		{
			alert(fieldCheckedName+" : "+dateSyntaxMsg);
			return null;
		}
		if ((!isOk)||(yearDigitError))
		{
			if (msg == "")
			alert(fieldCheckedName+" : "+dateNotValidMsg);
			else alert(fieldCheckedName+" : "+msg);
			return null;
		}
		else
		return value;
		
	}

/**
        * This function substitute all the separators (see
        * the declaration af the "separators" array) with the separator "/".
        */

	 function checkSeparator(value)
        {
            var position = -1;
            for (var i = 0; i < separators.length; i++)
            {
                // Skip the '/' separator to avoid infinite loop.
                if  (separators[i] == '/')
                    continue;
                s1=value.indexOf(separators[i]);
                while (s1 != -1)
                {
                    firstPart=value.substring(0,s1);
                    lastPart=value.substring(s1+1,value.length);
                    value = firstPart +"/"+lastPart;
                    s1=value.indexOf(separators[i]);
                }
            }
            return value;
        }

/**
        * This function clear all white spaces and special character from the string
        */

				function trimString(value)
        {
            var outString;
            var startPos;
            var endPos;
            var ch;
            if (value == null)
                return null;
            // delete from begin...
            startPos = 0;
            inString = value.toString();
            ch = inString.charAt(startPos);
            while ((ch == " ") || (escape(ch) == "%20") ||(ch == "\b") || (ch == "\f") || (ch == "\n") || (ch == "\r") || (ch == "\n"))
            {
                startPos++;
                ch = inString.charAt(startPos);
            }

            // delete from the end...
            endPos = inString.length - 1;
            ch = inString.charAt(endPos);
            while ((ch == " ") || (ch == "\b") || (ch == "\f") || (ch == "\n") || (ch == "\r") || (ch == "\n"))
            {
                endPos--;
                ch = inString.charAt(endPos);
            }

            // get the string
            if (endPos == -1)
                return "";
            outString = inString.substring(startPos, endPos + 1);
            return outString;
        }

				
				
				/**
        * This function check all white field on the form passed
        */
		
				 function checkAll(formName)
        {
            isOkForm=true;
            if (formName == "")
            {
                formName= "forms[0]";
            }
            completeFormName="document.";
            completeFormName+=formName;
            formRef=eval(completeFormName);
            var i = 0;

            for (i=0; i < formRef.elements.length;i++)
            {

                nameObj =formRef.elements[i].name;
                var func = formRef.elements[i].onchange;
                if (func != null)
                {
                    stringa = func.toString();
                    res = stringa.indexOf('checkValue');
                    if (res != -1)
                    //Mauro B new deve chiamare solo la checkValue
                    {
                        endFunc = stringa.indexOf(';',res);
                        if (endFunc > res)
                        {
                            callFunc = stringa.substring(res,endFunc);
                            eval(callFunc);
                        }
                        else // default
                        {
                            func();
                        }
                    }
                    // end new
                    //func(); commentato, sostituito da new
                    

                    res = stringa.indexOf('warnDeltaDate');
                    var check = false;
                    if (res != -1)
                    {
                        endFunc = stringa.indexOf(';',res);
                        if (endFunc > res)
                        {
                            callFunc = stringa.substring(res,endFunc);
                            check = eval(callFunc);
                            if(!check)
                            {
                            	isOkForm = false;
                            }
                        }
                    }
                }
                
            }
            // If one field is incorrect, isOkForm (global variable) is null!
            return isOkForm;
          }

 /**
        * This function check all white field on the form passed and
        * execute the submit if all the fields are ok
        */

 function checkForm(formName)
        {
            /*if (!multipleSubmit())
            return false;*/


            if (trimString(formName) == "")
            {
                formName = "forms[0]";
            }
            completeFormName="document.";
            completeFormName+=formName;
            formRef=eval(completeFormName);

            if (formRef==null)
            {
                if (!firstSubmit())
                    return false;
                return true;
            }
            else if ( checkAll(formName) )
            {
                    if (!firstSubmit())
                    {
                        return false;
                    }
                	else return true;
            }
            else
            {
            	return false;
            }
        }
				
				/**
         * Remove NewLine, CarriageReturn and Tab characters from a String
         * s  string to be processed
         * returns new string
             */
			
				 function removeNL(s)
        {
            r = "";
            for (i=0; i < s.length; i++)
            {
                if (s.charAt(i) != '\n' &&
                        s.charAt(i) != '\r' &&
                        s.charAt(i) != '\t')
                {
                      r += s.charAt(i);
                    }
                    else
                    {
                        r += " ";
                     }
            }
            return r;
        }


/*
        ***** submit_count e una variabile globale per il controllo di un submit ripetuto erroneamemte;
        ***** DA NON CANCELLARE
        */

				var submit_count = 0;
				
			
				/*
        ***** funzione di controllo di submit ripetuti;
        ***** DA NON CANCELLARE
        */
			
				function firstSubmit()
        {
            if (submit_count==0) {
                submit_count++;
                return true;
            }

            if (submit_count ==1) {
                alert(MSG_RICHIESTA_GIA_INOLTRATA);
					submit_count++;
                return false;
            }
            if (submit_count > 1) {
                alert(MSG_RICHIESTA_GIA_INOLTRATA);
					submit_count++;
                return false;
            }
        return false;
        }
			
		function submitCount(submitCount) {
            if (submitCount==0) {
                submitCount++;
                /*alert("submitCount:"+submitCount);*/
                return submitCount;
            } else if (submitCount>=1) {
                alert(MSG_RICHIESTA_GIA_INOLTRATA);
				submitCount++;
                /*alert("submitCount:"+submitCount);*/
                return submitCount;
            }
        	return submitCount;
        }
        
				/**
 * Check the value passed. Return always the uppercase.
 *
 *  Mauro B.
 */
				
				function checkCF(cf)
				{
					isOkOthersInputs = true;
						var validi, i, s, set1, set2, setpari, setdisp;
						var msg = '';
						var isOK = true;
						var cfup = '';
						if( cf != '' )
						{
								cfup = cf.toUpperCase();
								if( cfup.length != 16 )
								{
										msg =MSG_CF_LENGTH;
									isOK = false;
								}
								else
								{
										validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
										for( i = 0; i < 16; i++ )
										{
												if( validi.indexOf( cfup.charAt(i) ) == -1 )
												{
														msg = MSG_CF_CHAR_INVALID_1 + cfup.charAt(i) + MSG_CF_CHAR_INVALID_2;
									isOK = false;
												}
										}
										if (isOK == true)
										{
												set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
												set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
												setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
												setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
												s = 0;
												for( i = 1; i <= 13; i += 2 )
													 s += setpari.indexOf( set2.charAt( set1.indexOf( cfup.charAt(i) )));
												for ( i = 0; i <= 14; i += 2 )
													 s += setdisp.indexOf( set2.charAt( set1.indexOf( cfup.charAt(i) )));
												if( s%26 != cfup.charCodeAt(15)-'A'.charCodeAt(0) )
												{
														msg = MSG_CF_NON_CORRETTO;
									isOK = false;
												}
										}
								}
						 }
						 if (isOK == true)
						 {
								return cfup;
						 }
						 else
						 {
								alert(fieldCheckedName+" : "+msg);
								isOkOthersInputs = false;
								return cfup;
						 }
				}
				
				/**
 * Check the value passed. Return null if the partita iva is not correct.
 *
 *  Mauro B.
 */
			
				function checkPIVA(pi)
				{
					isOkOthersInputs = true;
						var isOK = true;
						var msg = '';
						if( pi != '' )
						{
								if( pi.length != 11)
								{
									 msg =MSG_PIVA_NON_CORRETTA;
									 isOK = false;

        }
        else if(pi == "00000000000") 
        {
        	msg=MSG_PIVA_NO_TUTTI_ZERI;
        	isOK=false;
        }
        else
        {
           validi = "0123456789";
           for( i = 0; i < 11; i++ )
           {
           if( validi.indexOf( pi.charAt(i) ) == -1 )
           {
            msg =MSG_PIVA_CHAR_INVALID_1 + pi.charAt(i) + MSG_PIVA_CHAR_INVALID_2;
									isOK = false;
           }
           }
           if (isOK == true)
           {
               s = 0;
               for( i = 0; i <= 9; i += 2 )
               s += pi.charCodeAt(i) - '0'.charCodeAt(0);
               for( i = 1; i <= 9; i += 2 )
               {
               c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
               if( c > 9 )  c = c - 9;
               s += c;
               }
               if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
               {
              msg =MSG_PIVA_NON_VALIDA;
									isOK = false;
               }
           }
       }
    }
    if (isOK == true)
    {
       return pi;
    }
    else
    {
        alert(fieldCheckedName+" : "+msg);
        isOkOthersInputs = false;
        return null;
    }
}


/**
 * Check the value passed. Return always the uppercase.
 *
 *  Mauro B.
 */

		function checkCFPIVA(cfpi)
		{
			isOkOthersInputs = true;
				var msg = '';
				if( cfpi != '' )
				{
						if( cfpi.length == 11 )
						{
							 return checkPIVA(cfpi);
						}
						else
						{
								if(  cfpi.length == 16 )
								{
										return checkCF(cfpi);
								}
								else
								{
										msg = MSG_CF_PIVA_NON_CORRETTI;
											alert(fieldCheckedName+" : "+msg);
								isOkOthersInputs = false;
										return cfpi.toUpperCase();
								}
						}
				}
		}

		
		/**
* Check the value in the passed field, in the passed form.
* if the form parameter is null or empty, the default value is forms[0]. For the
* "mandatory", "type", "minlength", "maxlength" parameters see the Checkfieldvalue
* function.
* If the field value is incorrect, an alert is shown.
* Mauro B.
*
*/
		
		function warnValue(field, form,mandatory, type, minlength, maxlength, messageString)
{
    if (form == "")
    {
        form= "forms[0]";
    }

    // Construct the field name
    if (messageString == null)
        fieldCheckedName = field;
    else
    {
        fieldCheckedName = messageString;
    }
    fieldName = "document."+form+"."+field;

    // Retrieve the field reference

    var evalform = eval("document."+form);

    value = evalform.elements[field].value;

    if (value != null)
    {
        value1 = removeNL(value);
    }
    else
    {
        value1 = value;
    }

    var returnValue = checkFieldValue(trimString(value1), trimString(mandatory),trimString(type),trimString(minlength),trimString(maxlength));
    if (returnValue == null)
    {
        // fieldRef = eval(fieldName);
        //evalform.elements[field].value=""; do not reset
        isOkForm=null;
        return;
    }
    // If the value returned is different from the field value, change it.
    else if (value != returnValue)
    {
        evalform.elements[field].value = returnValue;
        return;
    }
}


/**
 * Check the value passed. Return null if the value is not a code ABI or CAB.
 *
 *  Mauro B.
 */

		function checkABICAB(abicab)
{
    var isOK = true;
    var msg = '';
    var returnValue = null;

    if( abicab != '' )
    {
        if( abicab.length > 5 )
        {
           msg = MSG_ABI_NON_CORRETTO;
									isOK = false;

        }
        else
        {
           validi = "0123456789";
           for( i = 0; i < 11; i++ )
           {
           if( validi.indexOf( abicab.charAt(i) ) == -1 )
           {
            msg = MSG_ABI_CHAR_INVALID_1 + abicab.charAt(i) + MSG_PIVA_CHAR_INVALID_2;
									isOK = false;
           }
           }
           if (isOK == true)
           {
               zeri = 5 - abicab.length;
               if (zeri > 0)
               {
                   var dummy = "00000";
                   returnValue = dummy.substr(0,zeri)+abicab;
               }
               else
               {
                   returnValue = abicab;
               }
           }
       }
    }
    if (isOK == true)
    {
    	
       return returnValue;
    }
    else
    {
      alert(fieldCheckedName+" : "+msg);
      return null;
    }
}

/**
 * Check the value passed. Return correction if the value is not an Italian  CAP code
 * (5 digit not 00000)
 *
 *  Mauro B.
 */

function checkCAP(cap)
{
	var isOK = true;
	var msg = "";
	var returnValue = "";
	if( cap != "" )
	{
		var validi = "0123456789";
		var lengthCap = cap.length;
		for( i = 0; i < lengthCap; i++ )
		{
			if( validi.indexOf( cap.charAt(i) ) > -1 )
			{
				returnValue = returnValue+cap.charAt(i);
			}
			else
			{
				isOK = false;
			}
		}
		var resultLength = returnValue.length;
		if (resultLength>5)
		{
			returnValue = returnValue.substr(resultLength-5,5);
			isOK = false;
		}
		var zeri = 5 - returnValue.length;
		if (zeri > 0)
		{
			var dummy = "00000";
			returnValue = dummy.substr(0,zeri)+returnValue;
			isOK = false;
		}
		if (returnValue == "00000")
		{
			returnValue = "";
			isOK = false;
		}
		if (isOK == true)
		{
			return returnValue;
		}
		else
		{
			if (returnValue != "")
			{
				msg = MSG_CAP_NON_CORRETTO+MSG_N_CONTO_VALID_3;
				alert(fieldCheckedName+" : "+msg);
				return returnValue;
			}
			else
			{
				msg = MSG_CAP_NON_CORRETTO;
				alert(fieldCheckedName+" : "+msg);
				return returnValue;
			}
		}
	}
	else
		return cap;
}

/**
 * 	Check the value passed. Return false if the IBAN value is != 27 or
 *	do not match with the ABI, CAB, ACCOUNT codes.
 *
 * 	Luca D.
 *  E' solo un controllo di coerenza. Mauro B.
 */

function checkIBAN(iban, abi, cab, account, codPaese, msg)
{
	if(iban.length == 0 || (abi.length == 0 && cab.length == 0 && account.length == 0)) return true;
		
	var abiLength = abi.length;
	var cabLength = cab.length;
	var accLength = account.length;
	var ibaLength = iban.length;
	
	if (codPaese == 'IT' || codPaese=='SM')
	{
		if (abiLength == 0) abiLength = 5;
		if (cabLength == 0) cabLength = 5;
		if (accLength == 0) accLength = 12;
	}
	
	var coordLength = 5+abiLength+cabLength+accLength

	if(iban.length > 0 && (iban.length != coordLength))
	{
		alert(msg+MSG_IBAN_FORMA);
		return false;
	}

	abi_iban = iban.substring(5, 5+abiLength);
	cab_iban = iban.substring(5+abiLength, 5+abiLength+cabLength);
	account_iban = iban.substring(5+abiLength+cabLength, 5+abiLength+cabLength+accLength);

	if (abi.length == 0)
		abi=abi_iban;
	if (cab.length == 0)
		cab=cab_iban;
	if (account.length == 0)
		account=account_iban;
	if(abi_iban == abi && cab_iban == cab && account_iban == account) return true;
	else
	{
		alert(msg+MSG_IBAN_FORMA);
		return false;
	}
}

/**
 * 	Check the value passed. Return false if the IBAN value is != 27 or
 *	do not match with the ABI, CAB, ACCOUNT codes.
 *
 * and return the error message if present instead of pushing out a popup
 * 	Adriano Antonelli
 
 * E' solo un controllo di coerenza. Mauro B.
 */

function checkIBANNew(iban, abi, cab, account, codPaese, msg)
{
	if(iban.length == 0 || (abi.length == 0 && cab.length == 0 && account.length == 0)) return "";
		
	var abiLength = abi.length;
	var cabLength = cab.length;
	var accLength = account.length;
	var ibaLength = iban.length;
	
	if (codPaese == 'IT' || codPaese=='SM')
	{
		if (abiLength == 0) abiLength = 5;
		if (cabLength == 0) cabLength = 5;
		if (accLength == 0) accLength = 12;
	}
	
	var coordLength = 5+abiLength+cabLength+accLength;
	
	if(iban.length > 0 && (iban.length =! coordLength))
	{
		return msg+MSG_IBAN_FORMA;
	}

	abi_iban = iban.substring(5, 5+abiLength);
	cab_iban = iban.substring(5+abiLength, 5+abiLength+cabLength);
	account_iban = iban.substring(5+abiLength+cabLength, 5+abiLength+cabLength+accLength);

	if (abi.length == 0)
		abi=abi_iban;
	if (cab.length == 0)
		cab=cab_iban;
	if (account.length == 0)
		account=account_iban;
	if(abi_iban == abi && cab_iban == cab && account_iban == account) return "";
	else
	{
		return msg+MSG_IBAN_FORMA;
	}
}

/**
* Checks for the insDate to be after or equal minDate, otherwise an alert is shown.
* The date format must be dd/MM/yyyy.
* Mauro B.
*
*/

		function warnDate(field, minDate)
{
    //check date

    // Retrieve the field reference
    var evalform = eval("document.forms[0]");
    //insDate = evalform.elements[field].value;
    insDate = checkDate(evalform.elements[field].value,1900,2050,10)
    if ((insDate != null) && (insDate != ''))
    {
        dmin=new Date();
        dmin.setTime("0");
        dmin.setFullYear(minDate.substr(6,4));
        dmin.setMonth(eval(minDate.substr(3,2)-1),minDate.substr(0,2));
        dins=new Date();
        dins.setTime("0");
        dins.setFullYear(insDate.substr(6,4));
        dins.setMonth(eval(insDate.substr(3,2)-1),insDate.substr(0,2));
        if (dins < dmin)
        {
            alert( MSG_DATA_PRECEDE + minDate + MSG_DATA_FINE);
						}
    }
}
		
/**
 %SR% 06/02/2008
 Funzione che verifica se un fild che contiene una data è minore della data passata come parametro.
 true: controllo fallito
 false: Tutto ok
*/
function warnDateBeforeMinDate(field, minDate)
{
    // Retrieve the field reference
    var evalform = eval("document.forms[0]");
    //insDate = evalform.elements[field].value;
    insDate = checkDate(evalform.elements[field].value,1900,2050,10)
    if ((insDate != null) && (insDate != ''))
    {
        dmin=new Date();
        dmin.setTime("0");
        dmin.setFullYear(minDate.substr(6,4));
        dmin.setMonth(eval(minDate.substr(3,2)-1),minDate.substr(0,2));
        dins=new Date();
        dins.setTime("0");
        dins.setFullYear(insDate.substr(6,4));
        dins.setMonth(eval(insDate.substr(3,2)-1),insDate.substr(0,2));
        if (dins < dmin)
        {
			return true;
		}
		return false;
    }
}
/**
  %SR% 06/02/2008
  Funzione che controlla se la differenza fra due date è contenuta nel delta, espresso in giorni.
  true: controllo fallito
  false: Tutto ok
*/
	function warnDateOutDeltaMinDate(fieldMin, fieldMax, delta)
{
   // Retrieve the field reference
    var evalform = eval("document.forms[0]");
    insDateMin = checkDate(evalform.elements[fieldMin].value,1900,2050,10)
    insDateMax = checkDate(evalform.elements[fieldMax].value,1900,2050,10)
    if ((insDate != null) && (insDate != ''))
    {
        dmin=new Date();
        dmin.setTime("0");
        dmin.setFullYear(insDateMin.substr(6,4));
        dmin.setMonth(eval(insDateMin.substr(3,2)-1),insDateMin.substr(0,2));
        dins=new Date();
        dins.setTime("0");
        dins.setFullYear(insDateMax.substr(6,4));
        dins.setMonth(eval(insDateMax.substr(3,2)-1),insDateMax.substr(0,2));
        if (Math.abs(Date.parse(dins) - Date.parse(dmin)) > delta)
        {
			return true;
		}
		return false;
    }
}

/**
* Checks for minDate - minDelta <= field <= minDate + maxDelta, otherwise an alert is shown.
* The date format must be dd/MM/yyyy.
* Mauro B.
*
* Note!!! todayDB is the server date in format yyyy/mm/dd.
* 		  If (todayDB == null) OR (todayDB == ''),
*		  then the new Date() function creates
*		  a new date based on the local PC date!
*
* checkStatus = true
*	 -> activates the return value setted to false if the date isn't correct 
*
* Luca D.
*
*/

	function warnDeltaDate(field, minDate, todayDB, mindelta, maxdelta, dispoType, checkStatus)
	{
		var check = true;
		var checkDeltaMax = true;
			// Retrieve the field reference
			var evalform = eval("document.forms[0]");
			insDate = checkDate(evalform.elements[field].value,1900,2050,10);
			
			mindelta = eval(mindelta);
			maxdelta = eval(maxdelta);
			
			//insDate = evalform.elements[field].value;
			if ((insDate != null) && (insDate != ''))
			{
					 insDate = checkDate(value,minYear,maxYear,yearLimit);
					 
					 dmin=new Date(todayDB);
					 day = dmin.getDate();
					 day = day+mindelta;
					 dmin.setDate(day);
					 
					 dmax=new Date(todayDB);
					 day = dmax.getDate();
					 day = day+maxdelta;
					 dmax.setDate(day);
					 
					 dins=new Date(todayDB);
					 dins.setFullYear(insDate.substr(6,4));
					 dins.setMonth(eval(insDate.substr(3,2)-1),insDate.substr(0,2));
					 
					 // Check if there is a date limit onward
			if(dispoType != 'avvisi')
			{
					checkDeltaMax = (dins>dmax);
				}
				else
				{
					checkDeltaMax = false;
				}
				
				// Check if the date is correct
					 if ((dins < dmin)||checkDeltaMax)
					 {
							 msgmin=null;
							 if(dmin.getDate() < 10)
							 {
									 msgmin = "0"+dmin.getDate();
							 }
							 else
							 {
									msgmin = dmin.getDate();
							 }
							 if(dmin.getMonth() < 9)//il mese parte da 0
							 {
									 msgmin = msgmin+"/0"+eval(dmin.getMonth()+1);
							 }
							 else
							 {
									msgmin = msgmin+"/"+eval(dmin.getMonth()+1);
							 }
							 msgmin = msgmin+"/"+dmin.getFullYear();
			 
	
				 msgins = null;
				 if(dins.getDate() <10)
							 {
									 msgins = "0"+dins.getDate();
							 }
							 else
							 {
									msgins = dins.getDate();
							 }
							 if(dins.getMonth() < 9)
							 {
									 msgins = msgins+"/0"+eval(dins.getMonth()+1);
							 }
							 else
							 {
									msgins = msgins+"/"+eval(dins.getMonth()+1);
							 }
							 msgins = msgins+"/"+dins.getFullYear();
							 
							 
							 if(dispoType != 'avvisi')
				 {
								 msgmax=null;
								 if(dmax.getDate() < 10)
								 {
										 msgmax = "0"+dmax.getDate();
								 }
								 else
								 {
										msgmax = dmax.getDate();
								 }
								 if(dmax.getMonth() < 9)
								 {
										 msgmax = msgmax+"/0"+eval(dmax.getMonth()+1);
								 }
								 else
								 {
										msgmax = msgmax+"/"+eval(dmax.getMonth()+1);
								 }
								 msgmax = msgmax+"/"+dmax.getFullYear();
				 
								alert(MSG_DATA_INTERV_1 + msgins + MSG_DATA_INTERV_2+ msgmin + MSG_DATA_INTERV_3 + msgmax);
									}
        	 //Case: avvisi
        	 else
        	 {
        	 	alert(MSG_DATA_INTERV_1 + msgins + MSG_DATA_SUCC + msgmin);
					}
        	 
        	 //Set the check flag if we need to control the submit process
        	 if(checkStatus)
        	 {
        	 	check = false;
        	 }
        }
    }
    return check;
}

/**
* Checks for amount value  
* Mauro B.
*
* minAmount 	is a string representing the minimum amount value
* checkMin  	indicates whether to perform ('yes') or not to perform ('no') the check 
*				for the minimum value
* checkMinType 	indicates the type of check
* msgMin 		the message to show
* 
* maxAmount 	is a string representing the maximum amount value
* checkMax 		indicates whether to perform ('yes') or not to perform ('no') the check 
*				for the maximum value
* checkMaxType 	indicates the type of check
* msgMax 		the message to show
*
*  TYPE OF CHECK
*   	'int' : checks the value of the amount integer part 
*				with the min/max amount integer part
*   	'all' : checks the whole value of the amount 
*				with the whole value of min/max amount
*    (by default no checks are performed)
*
*
* checkStatus 	indicates whether to return a boolean result of check 
* 				(true is returned by default) 
* 
*
*/


		function warnAmount(field, minAmount, checkMin, checkMinType, msgMin, maxAmount, checkMax, checkMaxType, msgMax, checkStatus)
		{
		
			// amount to check
			var result = true;
			var msg = "";
			var evalform = eval("document.forms[0]");
			var amountString = evalform.elements[field].value;
			amountString = amountString.replace(/[.]/g,",");
			while ((amountString.length > 1) && (amountString.substr(0,1) == "0"))
				amountString = amountString.substr(1);
			var amountIntString = "";
			var amountDecString = "";
			var amountDecStringLen = 0;
			
			if (amountString.indexOf(",")!=-1)
			{
				var arrAmount = amountString.split(",");
				amountIntString = arrAmount[0];
				amountDecString = arrAmount[1];
			}
			else
			{
				amountIntString = amountString;
				amountDecString = "0";
			}
			
			var amountInt = Number(amountIntString);
			
			// minimum amount
			if (checkMin == "yes")
			{
				var minAmountString = minAmount.replace(/[.]/g,",");
				while ((minAmountString.length > 1) && (minAmountString.substr(0,1) == "0"))
					minAmountString = minAmountString.substr(1);	
				var minAmountIntString = "";
				var minAmountDecString = "";
				if (minAmountString.indexOf(",")!=-1)
				{
					var minArrAmount = minAmountString.split(",");
					minAmountIntString = minArrAmount[0];
					minAmountDecString = minArrAmount[1];
				}
				else
				{
					minAmountIntString = minAmountString;
					minAmountDecString = "0";
				}
				var minAmountInt = Number(minAmountIntString);
				if (checkMinType == 'int')
				{
					if(minAmountInt > amountInt)
					{
							msg = msg+msgMin+"\n";
							result = false;
					}
				}
				else
				{
					if (checkMinType == 'all')
					{
						if(minAmountInt > amountInt)
						{
							msg = msg+msgMin+"\n";
							result = false;
						}
						else
						{
								if(minAmountInt == amountInt)
							{
								if(compareDecimalPart(minAmountDecString,amountDecString)>0)
								{
									msg = msg+msgMin+"\n";
									result = false;
								}
							}
						}
					}
				}
			}
			// maximum amount
			if (checkMax == "yes")
			{
				var maxAmountString = maxAmount.replace(/[.]/g,",");
				while ((maxAmountString.length > 1) && (maxAmountString.substr(0,1) == "0"))
					maxAmountString = maxAmountString.substr(1);	
				var maxAmountIntString = "";
				var maxAmountDecString = "";
				if (maxAmountString.indexOf(",")!=-1)
				{
					var maxArrAmount = maxAmountString.split(",");
					maxAmountIntString = maxArrAmount[0];
					maxAmountDecString = maxArrAmount[1];
				}
				else
				{
					maxAmountIntString = maxAmountString;
					maxAmountDecString = "0";
				}
				var maxAmountInt = Number(maxAmountIntString);
				if (checkMaxType == 'int')
				{
					if(maxAmountInt < amountInt)
					{
						msg = msg+msgMax+"\n";
						result = false;
					}
				}
				else
				{
					if (checkMaxType == 'all')
					{
						if(maxAmountInt < amountInt)
						{
							msg = msg+msgMax+"\n";
							result = false;
						}
						else
						{
							if(maxAmountInt == amountInt)
							{
								if(compareDecimalPart(maxAmountDecString,amountDecString) < 0)
								{
									msg = msg+msgMax+"\n";
									result = false;
								}
							}
						}
					}
				}
			}
			if (!result) alert(msg);
			if(!checkStatus)
			{
				result = false;
			}
			return result;
		}
		

		//attenzione
		//	>0  a>b
		//   =0  a==b
		//   <0  a<b
		//


		function compareDecimalPart (a,b)
		{
			var result = 0;
			var aLen = a.length;
			var bLen = b.length;
			var delta = Math.abs(aLen-bLen);
			if (aLen > bLen)
			{
				for(i=0; i < delta; i++)
				{
					b = b+"0";
				}
			}
			else
			{
				for(i=0; i < delta; i++)
				{
					a = a+"0";
				}
			}
			while ((a.length > 1) && (a.substr(0,1) == "0"))
					a = a.substr(1);
			while ((b.length > 1) && (b.substr(0,1) == "0"))
					b = b.substr(1);
				var aInt = Number(a);
				var bInt = Number(b);
				if (aInt>bInt) result = 1;
				if (aInt < bInt) result = -1;
				return result;
		}




	/**
	*  return the number of working days plus the holidays
	*  in the period indicated by the todayDate + delta
	*  
	*  todayDate = start Date
	*  delta = period in working days
	*  direction = 'past' or 'future'
	*
	*  Luca D.
	*
	*  Note: THIS FUNCTION IS NOT LONGER USED BY ANYONE. IT WILL BE DELETED SOON.
	*/
	function getWholePeriod(todayDate, delta, direction)
		{
			//var weekday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
						
			//get the number of day. Sunday = 0.
			todayNumber = todayDate.getDay();
			
			workingDays = Math.abs(delta);
			if(direction == 'future')
			{	
				//check for the date forwarding in case of 'todayDate' == holiday
				if(todayNumber == 0 || todayNumber == 6)
				{
					workingDays++;
				}
				
				for(i=0; i < workingDays; i++)
				{
					todayNumber++;
					if(todayNumber == 7) todayNumber = 0;
					if(todayNumber == 0 || todayNumber == 6)
					{
						workingDays++;
					}
				}
			}
			else if(direction == 'past')
			{
				for(i=0; i < workingDays; i++)
				{
					todayNumber--;
					if(todayNumber == -1) todayNumber = 6;
					if(todayNumber == 0 || todayNumber == 6)
					{
						workingDays++;
					}
				}
			}
			if(delta < 0 || direction == 'past') workingDays = -workingDays;
				//alert(delta + " --> " + workingDays);
			
			
			//Calculate Easter Monday Holiday
			easterMonday = getEasterMonday(todayDate.getYear());
			easterMondayDate = new Date(todayDate.getYear()+"/01/01");
			easterMondayDate.setDate(easterMonday);
			//alert("easterMondayDate: " + easterMondayDate);
				
			if(workingDays < 0)
			{
				//Calculate Easter Monday Holiday (year-1)
				easterMondayNear = getEasterMonday(todayDate.getYear()-1);
				easterMondayDateNear= new Date(todayDate.getYear()-1+"/01/01");
				easterMondayDateNear.setDate(easterMondayNear);
				//alert("easterMondayDateNear: " + easterMondayDateNear);
			}
			if(workingDays > 0)
			{
				//Calculate Easter Monday Holiday (year+1)
				easterMondayNear = getEasterMonday(todayDate.getYear()+1);
				easterMondayDateNear = new Date(todayDate.getYear()+1+"/01/01");
				easterMondayDateNear.setDate(easterMondayNear);
				//alert("easterMondayDateNear: " + easterMondayDateNear);
			}
			
			
			//*** Include Holidays in workingDays ***//
			limitDayDate = new Date(todayDate);
			day = limitDayDate.getDate();
			day = day + workingDays;
			limitDayDate.setDate(day);
			//alert("limitDayDate: " + limitDayDate);
			
			//alert("direction: " + direction + " - todayDate: " + todayDate + " - limitDayDate: " + limitDayDate);
			
			if(workingDays < 0)
			{
				//filling Holidays Dates
				for(i=0; i<yearHolidaysNumber-1; i++)
				{
					yearHolidaysDates[i] = new Date(todayDate.getYear()+"/"+yearHolidays[i]);
				}
				yearHolidaysDates[i] = easterMondayDate;
				for(i=0; i<yearHolidaysNumber-1; i++)
				{
					yearHolidaysDates[yearHolidaysNumber+i] = new Date(todayDate.getYear()-1+"/"+yearHolidays[i]);
				}
				yearHolidaysDates[yearHolidaysNumber+i] = easterMondayDateNear;
				
				yearHolidaysDatesNumber = yearHolidaysDates.length;
									
				for(i=0; i<yearHolidaysDatesNumber; i++)
				{
					//check whether there is a holiday between delta or not
					if(yearHolidaysDates[i] < todayDate && yearHolidaysDates[i] >= limitDayDate)
					{
						holidayNumber = yearHolidaysDates[i].getDay();
						
						//alert("yearHolidaysDates[i]: " + yearHolidaysDates[i]);
						
						//check that the holiday is not a Saturday or a Sunday
						if(holidayNumber > 0 && holidayNumber < 6)
						{
							workingDays--;
						}
					}
				}
			}
			
			if(workingDays > 0)
			{
				//filling Holidays Dates
				for(i=0; i<yearHolidaysNumber-1; i++)
				{
					yearHolidaysDates[i] = new Date(todayDate.getYear()+"/"+yearHolidays[i]);
				}
				yearHolidaysDates[i] = easterMondayDate;
				for(i=0; i<yearHolidaysNumber-1; i++)
				{
					yearHolidaysDates[yearHolidaysNumber+i] = new Date(todayDate.getYear()+1+"/"+yearHolidays[i]);
				}
				yearHolidaysDates[yearHolidaysNumber+i] = easterMondayDateNear;
				
				yearHolidaysDatesNumber = yearHolidaysDates.length;
				
				for(i=0; i<yearHolidaysDatesNumber; i++)
				{
					//check whether there is a holiday between delta or not
					if(yearHolidaysDates[i] > todayDate && yearHolidaysDates[i] <= limitDayDate)
					{
						holidayNumber = yearHolidaysDates[i].getDay();
						
						//alert("yearHolidaysDates[i]: " + yearHolidaysDates[i]);
						
						//check that the holiday is not a Saturday or a Sunday
						if(holidayNumber > 0 && holidayNumber < 6)
						{
							workingDays++;
						}
					}
				}
				//check for the date forwarding in case of 'todayDate' == holiday
				for(i=0; i<yearHolidaysDatesNumber; i++)
				{
					if(yearHolidaysDates[i].getYear() == todayDate.getYear() &&
					   yearHolidaysDates[i].getMonth() == todayDate.getMonth() &&
					   yearHolidaysDates[i].getDay() == todayDate.getDay())
					{
						workingDays++;
						break;
					}
				}
			}
			
			if(delta < 0)
			{
				workingDays = -Math.abs(workingDays);
			}
			else
			{
				workingDays = Math.abs(workingDays);
			}
			
			/*
			for(i=0; i<yearHolidaysDatesNumber; i++)
			{
				alert("yearHolidaysDates[i] =  " + yearHolidaysDates[i]);	
			}
			*/
			//alert("workingDays: " + workingDays);
			
			return workingDays;
		}
	
	
	
	
		

/**
*  return 1 if the "year" argument is a leap year, 0 otherwise.
*
*  Luca D.
*/

		function isLeapYear(year) 
		{ 
			if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))  
				return 1; 
			else  
				return 0; 
		} 
		
		
		/**
*  return the number of days between the 01/01/yyyy and the easter monday holiday
*
*  Luca D.
*/
		
		function getEasterMonday(year)
		{
				 A=year;
				 n=A % 19; 
				 c=Math.floor(A/100); 
				 u=A % 100; 
				 s=Math.floor(c/4); 
				 t=c % 4; 
				 p=Math.floor((c+8)/25); 
				 q=Math.floor((c-p+1)/3); 
				 e=(19*n+c-s-q+15) % 30; 
				 b=Math.floor(u/4); 
				 d=u % 4; 
				 l=(32+2*t+2*b-e-d) % 7; 
				 h=Math.floor((n+11*e+22*l)/451); 
				 m=Math.floor((e+l-17*h+114)/31); 
				 j=(e+l-17*h+114) % 31; 
				 j=j+1; 
		
			 leapYear = isLeapYear(A);
				 easterSunday = 59 + leapYear; 
				 if (m==3) easterSunday = easterSunday + j; 
				 if (m==4) easterSunday = easterSunday + 31 + j;
							
				 return (easterSunday + 1);
		}



			function onlyAlpha(evento){
			
/*
	Consente solo l'immissione di caratteri alfabetici
	in un campo di tipo text.
	uso:
	<input type='text' .... onKeyPress="return onlyalpha(event)">
*/

				if(window.event || !evento.which) // IE o NE?
		{
			tasto = evento.keyCode; // per IE
		}
		else if(evento) // netscape
		{
			tasto = evento.which;
		}
		
		// gestione caso tasto backspace e tab
		if (tasto == 8 || tasto == 9 )
		{
			return true;
		}
								
		if (tasto < 65 || tasto > 122 || (tasto > 90 && tasto < 97))
			return false;
		return true;  
	
	}
	

	function maxL4TextArea(campo,maxLength)
{

/*
	 questa funzione va inserita nell'evento
	 onKeyPress e impedisce l'inserimento da
	 tastiera di piu' di maxLength caratteri in
	 un campo, Attenzione! col copia/incolla
	 si puo' ingannare...
*/

if(campo.value.length >= maxLength)
		return false;
	else
		return true;
}

function onlyRealNumbers(evento){

/*
	Consente solo l'immissione di caratteri numerici
	comprensivi del segno ','
	in un campo di tipo text.
	uso:
	<input type='text' .... onKeyPress="return onlyRealNumbers(event)">
*/

	if(window.event || !evento.which) // IE o NE?
	{
		tasto = evento.keyCode; // per IE
	}
	else if(evento) // netscape
	{
		tasto = evento.which;
	}
	
	// gestione caso tasto backspace e tab
	if (tasto == 8 || tasto == 9 )
	{
		return true;
	}
		
	if (tasto < 48 || tasto > 57 )
	{
		if( tasto != 44  )//ammessa solo virgola
		{
			return false;
		}
	}
	return true;  
}

function onlyNaturalNumbers(evento){

/*
	Consente solo l'immissione di caratteri numerici
	in un campo di tipo text.
	uso:
	<input type='text' .... onKeyPress="return onlyNaturalNumbers(event)">
*/

if(window.event || !evento.which) // IE o NE?
	{
		tasto = evento.keyCode; // per IE
	}
	else if(evento) // netscape
	{
		tasto = evento.which;
	}
	
	// gestione caso tasto backspace e tab
	if (tasto == 8 || tasto == 9 )
	{
		return true;
	}
			
	if (tasto < 48 || tasto > 57 )
	{
		return false;
	}
	return true;  
}

function onlyDate(evento){

/*
	Consente solo l'immissione di caratteri numerici
	e barre in modo da inserire una data del tipo gg/mm/aaaa.
	uso:
	<input type='text' .... onKeyPress="return onlyDate(event)">
*/

if(window.event || !evento.which) // IE o NE?
	{
		tasto = evento.keyCode; // per IE
	}
	else if(evento) // netscape
	{
		tasto = evento.which;
	}
	
	// gestione caso tasto backspace e tab
	if (tasto == 8 || tasto == 9 )
	{
		return true;
	}
	
	if (tasto < 47 || tasto > 57 )
	{
		return false;
	}
	return true;  
}

function onlyAlphaNumbers(evento){

/*
	Consente solo l'immissione di caratteri alfabetici e numeri [0...9]
	in un campo di tipo text.
	uso:
	<input type='text' .... onKeyPress="return onlyalphaNumbers(event)" id='text'1 name='text'1>
*/

	if(window.event || !evento.which) // IE o NE?
	{
		tasto = evento.keyCode; // per IE
	}
	else if(evento) // netscape
	{
		tasto = evento.which;
	}
	
	// gestione caso tasto backspace e tab
	if (tasto == 8 || tasto == 9 )
	{
		return true;
	}
								
	if ((tasto < 65 || tasto > 122 || (tasto > 90 && tasto < 97)) && (tasto < 48 || tasto > 57 ))
		return false;
	return true;  

}

function formatoImportiCorretto(impCVS,nInt,nFract)
{

/*
      verifica che gli importi siano inseriti nella forma:
      nInt,nFract, si aspetta che il numero di caratteri sia comunque
      complessivamente giusto.In caso di errore torna una stringa che descrive la causa.
*/

impCVS = impCVS.replace(/[.]/g,",");
   if (impCVS.indexOf(",")!=-1)
   {
   // numero con virgola, parte intera max nInt digit, parte con virgola max nFract digit
      var arrImpCVS = impCVS.split(",");
      var msg="";
      var errore=false;
      if ( String(arrImpCVS[0]).length > nInt )
      {
          msg = MSG_IMPORTO_FORMATO + MSG_IMPORTO_FORMATO_1 + nInt + MSG_IMPORTO_FORMATO_2;
									errore = true;
      }
      if ( String(arrImpCVS[1]).length > nFract )
      {
			if (errore)
			{
				msg = msg + MSG_DATA_INTERV_3;
									}
			else
			{
				msg = MSG_IMPORTO_FORMATO;
				}
			msg = msg + MSG_IMPORTO_FORMATO_1 + nFract + MSG_IMPORTO_FORMATO_3;
			errore = true;
      }
      if(errore)
      {
			return msg;
      }
                       		
   }
   else
   {
   // controllare che lunghezza sia <= nInt
       if(impCVS.length>nInt)
       {
          return MSG_IMPORTO_FORMATO + MSG_IMPORTO_FORMATO_1 + nInt + MSG_IMPORTO_FORMATO_2;
						}
   }
   return msg;
}


/*	 verificaLunghezzaContenuto:
 *
 *	 verifica la lunghezza del testo inserito in un campo
 *	 se il testo eccede le dimensioni massime, propone
 *	 l'eliminazione automatica dei caratteri eccedenti
 *
 *	 arg remNL: true se la funzione deve rimuovere i control characters
 */

function verificaLunghezzaContenuto(campo,campoCaption,maxLen,remNL)
{
  	if(remNL)
  	{
  		//rimuove crlf
		campo.value = removeNL(campo.value);
	}
  
	if (campo.value.length > maxLen)
	{
		//rimuove crlf
		campo.value = removeNL(campo.value);
		
		if (confirm( MSG_CAMPO_CONTRL + campoCaption + MSG_CAMPO_CONTRL_1 + maxLen + MSG_CAMPO_CONTRL_2))
		{
			campo.value = campo.value.slice(0,maxLen);
		}
	}
}


// By Chiara Venturi
// I can't call the function checkField because instead of the field name it displays 'UNDEFINED'
// I need to see the field name in the error message alert!

function checkFieldWithName(name, value, type, mandatory, nomeForm)
{
	if ((mandatory == 'TRUE') && (value.length ==0))
	{
			alert(name+" : "+mandatoryFieldMsg);
			return false;
	}
	else
	{
		switch (type)
		{
			case "STRING":
						// The field is a string field.
						if (value.length >0)
						{	
							return true;
						}
						else
						{
							alert(name+" : "+mandatoryFieldMsg);
							return false;
						}
						break;
						
			case "ABI_CAB":
						var abicab = checkABICABWithName(name,value,nomeForm)
						return abicab;
						break;
						
			case "ACCOUNT":
					// The field is an account number
						var account = checkAccountFormatWithName(name,value,nomeForm)
						return account;
						break;
						
						default:
						return null;
		}
	}
	return false;
}
	
	function checkABICABWithName(name, value,nomeForm)
{
   var isOK = true;
   var msg = '';

		if( value.length < 5 )
		{
			 msg = MSG_ABI_NON_CORRETTO;
			 isOK = false;
		}
		else 
		{
			 var validi = "0123456789";
			 for( i = 0; i < 11; i++ )
			 {
				 if( validi.indexOf( value.charAt(i) ) == -1 )
				 {
					msg = MSG_ABI_CHAR_INVALID_1 + value.charAt(i) + MSG_PIVA_CHAR_INVALID_2;
			isOK = false;
				 }
			 }
		}
    if (isOK == true)
    {
       return true;
    }
    else
    {
      alert(name+" : "+msg);
			//Cambia il valore nel campo d'origine.
			var espressione = eval("document."+nomeForm+"."+name);
			espressione.value='';

      return false;
    }
}	

	function checkAccountFormatWithName(name, value, nomeForm)
	{
   	    var check = true;
   	    var minlength = 12;
   	    var maxlength = 12;
   	     	    		
   	    //controllo lunghezza
   	    var msg, msg1="", msg2="", msg3;
   	    msg = MSG_N_CONTO_VALID;
				msg3 = MSG_N_CONTO_VALID_3;
			if(value.length < minlength || value.length > maxlength)
   	    {
   	    	msg1 =MSG_N_CONTO_VALID_0 + minlength + MSG_N_CONTO_VALID_1;
					check = false;
   	    }
   	    
   	    //controllo caratteri alfanumerici
   	    value = value.toUpperCase();
   	    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   	    accountLength = value.length;
   	    for(i=0; i < accountLength; i++)
            {
                if( validi.indexOf( value.charAt(i) ) == -1 )
                {
                    msg2 = MSG_N_CONTO_VALID_2;
				check = false;
                    
                    //modifica caratteri
                    value = value.replace(value.charAt(i), "");
                    i--;
                    accountLength = value.length;
                }
            }
   	    
   	    //modifica lunghezza 
   	    while(value.length < minlength)  value = "0" + value;
   	    
   	    if(!check)
   	    {
   	    	alert(msg+msg1+msg2+msg3);
					//Cambia il valore nel campo d'origine.
					var espressione = eval("document."+nomeForm+"."+name);
					espressione.value=value;
   	    }
   	    
   	    return check;
	}
	
	
	/**
* Checks for the insDate to be after or equal minDate, otherwise an alert is shown.
* The date format must be dd/MM/yyyy.
* 
*/

	function isDateAfterToday(field)
{
	 if   ( (field!="")  && (field!=null))
	 {
		 minDate=getToday();
		 var evalform = eval("document.forms[0]");
		 insDate = checkDate(evalform.elements[field].value,1900,2050,10)
		 if ((insDate != null) && (insDate != ''))
		 {
			  dmin=new Date();
			  dmin.setTime("0");
			  dmin.setFullYear(minDate.substr(6,4));
			  dmin.setMonth(eval(minDate.substr(3,2)-1),minDate.substr(0,2));
			  dins=new Date();
			  dins.setTime("0");
			  dins.setFullYear(insDate.substr(6,4));
			  dins.setMonth(eval(insDate.substr(3,2)-1),insDate.substr(0,2));
			  if (dins < dmin)
				  return false;
			  else
				  return true;
		 }
	 }
}


/**This function return today in string format: "dd/mm/yyyy"*/

function getToday()
{
	var now = new Date();
	var month=now.getMonth()+1;
	var day=now.getDate();
	var year=now.getFullYear();
	if(month < 10)
			month="0"+month;
	if(day < 10)
			day="0"+day;
	return day+"/"+month+"/"+year;
		
}

/*
 * Check validity of IBAN Code
 */
function verifyIBAN(ibanToCheck, codPaese, msg)
{
	var iban = ibanToCheck.toUpperCase();
	if(iban.length == 0) return true;
	if(iban.length < 5) 
	{
		alert(msg+MSG_MIN_CHAR+' 5 '+MSG_CHAR);
		return false;
	}
	
	country_iban = iban.substring(0,2);
	
	if (codPaese == 'IT' || codPaese == 'SM')
	{
		if(country_iban != 'IT' && country_iban != 'SM')
		{
			alert(msg+MSG_CODICE_PAESE_ERR);
			return false;
		}
		if((iban.length > 0) && (iban.length != 27))
		{
			alert(msg+MSG_IBAN_LENGTH);
			return false;
		}
	}

	check_iban = iban.substring(2,4);
	bban_iban = iban.substr(4);
	
	checkNew = getIbanCheckCode(bban_iban,country_iban);
	
	if(check_iban == checkNew) return true;
	else
	{
		alert(msg+MSG_IBAN_NON_CORRETTO);
		return false;
	}
}

function verifyIBANNew(ibanToCheck, codPaese, msg)
{
	var iban = ibanToCheck.toUpperCase();
	if(iban.length == 0) return "";
	if(iban.length < 5) 
	{
		return msg+MSG_MIN_CHAR+' 5 '+MSG_CHAR;
	}
	
	country_iban = iban.substring(0,2);
	
	if (codPaese == 'IT' || codPaese == 'SM')
	{
		if(country_iban != 'IT' && country_iban != 'SM')
		{
			return msg+MSG_CODICE_PAESE_ERR;
		}
		if((iban.length > 0) && (iban.length != 27))
		{
			return msg+MSG_IBAN_LENGTH;
		}
	}

	check_iban = iban.substring(2,4);
	bban_iban = iban.substr(4);
	
	checkNew = getIbanCheckCode(bban_iban,country_iban);
	
	if(check_iban == checkNew) return "";
	else
	{
		return msg+MSG_IBAN_NON_CORRETTO;
	}
	return "";
}



/*
 * Retrieve the IBAN check code with ABI, CAB, ACCOUNT, CIN and COUNTRY code data. 
 * ABI and CAB must be 5 characters long;
 * ACCOUNT     must be up to 12 characters long;
 * CIN         must be 1 character long;
 * COUNTRY     must be 2 character long;
 */
function getIbanCheckCode(bban, country)
{
	//Preliminary step
	start = country+"00";
	bban = trimAlphanumeric(bban.toUpperCase());
	//Step 1
	toConvert = bban+start;
	//Step 2
	converted = ibanConvert(toConvert);
	//Step 3
	check = 98-remainder(converted,"97");
	if (check.length<2) check += "0";
	return check;
}

/*
 * Return a string with only alphanumeric characters
 *
 */
function trimAlphanumeric(s)
{
	var result = "";
	for (var i=0; i<s.length; i++)
	{
	   if (((s.charAt(i) >= '0' && s.charAt(i) <= '9'))||
	      ((s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')))
	   {
	      result += s.charAt(i);
	   }
	}
	return result;
}

/*
 * Return a string with only numeric characters
 * according to the conversion table for iban
 * A=10, B=11, C=12 ... Z=35;
 *
 */
function ibanConvert(s)
{
	var result = "";
	for (var i=0; i<s.length; i++)
	{
	   if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
	   {
	      result += new String(s.charCodeAt(i)-55);
	   }
	   else
	   {
	   	  result += s.charAt(i);
	   }
	}
	return result;
}

/*
 * Remainder calculation.
 *
 */
function remainder(n,m)
{
	s = new String(n);
	mm = new Number(m);
	modlen=0;
	l = s.length;
	sublen = 0;
	read = 0;
	partial = "";
	mod = "";
	while (l>read)
	{
		sublen = 9-modlen;
		partial = s.substr(read,9-modlen);
		read += sublen;
		nn= new Number(mod+partial);
		mod = new String(nn%mm);
		modlen = mod.length;
	}
	return mod;
}

/*
 * Check validity of CIN Character
 */
function checkCIN(abi,cab,cc,cin,msg)
{
	if(cin.length == 0) return true;
	cinNew=(calcola_ABI(abi)+calcola_CAB(cab)+calcola_CC(cc)) % 26;
	cinNew=calcola_CIN(cinNew);
	if(cinNew == cin) return true;
	else
	{
		alert(msg+MSG_CIN_NON_CORRETTO);
		return false;
	}
}

function calcola_ABI(ABI) {
    somma=0;
    for (i=0; i<5; i++) {
        switch (i) {
            case 0: case 2: case 4: somma=somma + dispari(ABI.substr(i,1)); break;
            case 1: case 3: somma=somma + pari(ABI.substr(i,1)); break;
        }
    }
    return somma;
}

function calcola_CAB(CAB) {
    somma=0;
    for (i=0; i<5; i++) {
        switch (i) {
            case 0: case 2: case 4: somma=somma + pari(CAB.substr(i,1)); break;
            case 1: case 3: somma=somma + dispari(CAB.substr(i,1)); break;
        }
    }
    return somma;
}

function calcola_CC(CC) {
    somma=0;
    for (i=0; i<12; i++) {
        switch (i) {
            case 0: case 2: case 4: case 6: case 8: case 10: somma=somma + dispari(CC.substr(i,1)); break;
            case 1: case 3: case 5: case 7: case 9: case 11: somma=somma + pari(CC.substr(i,1)); break;
        }
    }
    return somma;
}

function pari(carattere) {
    switch (carattere.toUpperCase()){
        case "A": case "0": return 0; break;
        case "B": case "1": return 1; break;
        case "C": case "2": return 2; break;
        case "D": case "3": return 3; break;
        case "E": case "4": return 4; break;
        case "F": case "5": return 5; break;
        case "G": case "6": return 6; break;
        case "H": case "7": return 7; break;
        case "I": case "8": return 8; break;
        case "J": case "9": return 9; break;
        case "K": return 10; break;
        case "L": return 11; break;
        case "M": return 12; break;
        case "N": return 13; break;
        case "O": return 14; break;
        case "P": return 15; break;
        case "Q": return 16; break;
        case "R": return 17; break;
        case "S": return 18; break;
        case "T": return 19; break;
        case "U": return 20; break;
        case "V": return 21; break;
        case "W": return 22; break;
        case "X": return 23; break;
        case "Y": return 24; break;
        case "Z": return 25; break;
    }
}
function dispari(carattere) {
    switch (carattere.toUpperCase()){
        case "A": case "0": return 1; break;
        case "B": case "1": return 0; break;
        case "C": case "2": return 5; break;
        case "D": case "3": return 7; break;
        case "E": case "4": return 9; break;
        case "F": case "5": return 13; break;
        case "G": case "6": return 15; break;
        case "H": case "7": return 17; break;
        case "I": case "8": return 19; break;
        case "J": case "9": return 21; break;
        case "K": return 2; break;
        case "L": return 4; break;
        case "M": return 18; break;
        case "N": return 20; break;
        case "O": return 11; break;
        case "P": return 3; break;
        case "Q": return 6; break;
        case "R": return 8; break;
        case "S": return 12; break;
        case "T": return 14; break;
        case "U": return 16; break;
        case "V": return 10; break;
        case "W": return 22; break;
        case "X": return 25; break;
        case "Y": return 24; break;
        case "Z": return 23; break;
    }
}

function calcola_CIN(numero) {
    switch (numero){
        case 0: return "A"; break;
        case 1: return "B"; break;
        case 2: return "C"; break;
        case 3: return "D"; break;
        case 4: return "E"; break;
        case 5: return "F"; break;
        case 6: return "G"; break;
        case 7: return "H"; break;
        case 8: return "I"; break;
        case 9: return "J"; break;
        case 10: return "K"; break;
        case 11: return "L"; break;
        case 12: return "M"; break;
        case 13: return "N"; break;
        case 14: return "O"; break;
        case 15: return "P"; break;
        case 16: return "Q"; break;
        case 17: return "R"; break;
        case 18: return "S"; break;
        case 19: return "T"; break;
        case 20: return "U"; break;
        case 21: return "V"; break;
        case 22: return "W"; break;
        case 23: return "X"; break;
        case 24: return "Y"; break;
        case 25: return "Z"; break;
    }
}

function POPAlertConferma(tipo,form)
{
	var responce = false;
	if(tipo=="distinte")
	{
		var selezionati=0;
		var form=eval("document."+form);
		for(var i=0; i<form.elements.length; i++)
			if(form.elements[i].value=='delete' || form.elements[i].value=='deleteXML') 
			{
				if(form.elements[i].checked==1) 
				{
					selezionati++;
				}  
			}
		if(selezionati>0)
		{ 
				if(selezionati==1)
					responce=confirm(MSG_CONFERMA_ELIMINAZIONE_DISTINTE + selezionati + MSG_CONFERMA_ELIMINAZIONE_OGGETTO);
				else 
					responce=confirm(MSG_CONFERMA_ELIMINAZIONE_DISTINTE + selezionati + MSG_CONFERMA_ELIMINAZIONE_OGGETTI);
				return responce;
		}
		else if(selezionati==0)
				return true;
	}
	else if(tipo=="disposizioni")
	{
		var selezionati=0;
		var form=eval("document."+form);
		for(var i=0; i<form.elements.length; i++)
		if(form.elements[i].value=='delete') 
		{
			if(form.elements[i].checked==1) 
				{
					selezionati++;
				}  
		}
		if(selezionati>0)
		{ 
			if(selezionati==1)
				responce=confirm(MSG_CONFERMA_ELIMINAZIONE_DISTINTE + selezionati + MSG_CONFERMA_ELIMINAZIONE_DISPOSIZIONE);
			else responce=confirm(MSG_CONFERMA_ELIMINAZIONE_DISTINTE + selezionati + MSG_CONFERMA_ELIMINAZIONE_DISPOSIZIONI);
			return responce;
								
		}
		else if(selezionati==0)
			return true;
	}
	else if(tipo=="hidden_delete")
	{
		var selezionati=0;
		var form=eval("document."+form);
		for(var i=0; i<form.elements.length; i++) {
			if(form.elements[i].value=='delete') 
			{
				selezionati++;
			}
		}
		if(selezionati>0)
		{ 
			if(selezionati==1)
				responce=confirm(MSG_CONFERMA_ELIMINAZIONE_DISTINTE + selezionati + MSG_CONFERMA_ELIMINAZIONE_DISPOSIZIONE);
			else responce=confirm(MSG_CONFERMA_ELIMINAZIONE_DISTINTE + selezionati + MSG_CONFERMA_ELIMINAZIONE_DISPOSIZIONI);
			return responce;
								
		}
		else if(selezionati==0)
			return true;
    }
	else if(tipo=="anagrafica")
	{
		responce=confirm(MSG_CONFERMA_ELIMINAZIONE_ANAGRAFICA);
		return responce;
	}
}



	/**
		*	Remove special chars indicated in spacialChars Array
		*	arg0: 	field the string field to be checked for special chars
		*	return: true if the field has needed correction
		*	
		*	note: 	You can add a new special Char in specialChars array adding
		*			also a correspondant char for correction in the replaceChars array
		
		*	author:	Luca Drossatos
		*/
		function replaceSpecialChars(field)
		{
			var specialChars = new String("&<>€éèùçòàì#£^[]°§|{}~ÇüâäåêëïîÄÅÉæÆôöûÿÖÜø£Ø×ƒááíóúñÑªº¿®¬½¼¡«»ÁÂÀ©¥ãÃðÐÊËÈiÍÎÏÊÈËiÍÎÏ_ÌÓßÔÒõÕµþÞÚÛÙýÝ¯´­±=¾¶§÷¸°¨·¹³²\\");
			var replaceChars = new String("E  EeeucoaiNLa()o  () CuaaaeeiiAAEeEoouyOUoLOxfaaiounNao R   i  AAACYaAODEEEiIIIEEEiIII IOBOOoO   UUUYY                 ");
			var inputStr = new String(field.value);
			var outputStr = new String("");
			var tempChar = "";
			var charIndex = 0;
			var changed = false;
			
			//replace only special Chars with the correct ones
			for(i=0; i<inputStr.length; i++)
			{
				//check for spacial chars
				if( (charIndex = specialChars.indexOf(inputStr.charAt(i))) != -1)
				{
					tempChar = replaceChars.charAt(charIndex);
					changed = true;
				}
				//check for circle character
				else if( (inputStr.charCodeAt(i)) == 176)
				{
					tempChar = " ";
					changed = true;	
				}
				//copy char unchanged
				else
				{
					tempChar = inputStr.charAt(i);
				}
				outputStr += tempChar;
				tempChar = "";
			}
			field.value = outputStr;
			return changed;
		}
		
	  function checkPaeseLunghezzaIBANEstero(iban)
	  {
	  	var codPaese_iban = (iban.substring(0, 2)).toUpperCase();
	  		
	  	for (i=1;i<arrayDatiIban.length;i++)
	  	{
	  		
			if(arrayDatiIban[i].cod_paese==codPaese_iban)
			{
				if(arrayDatiIban[i].n_car==iban.length)
				{
					if(checkIBANEstero(iban)=="")
						return true
					else
					{
						alert(checkIBANEstero(iban))
						return false 
					}
				}
				else
				{
					alert(MSG_IBAN+": "+MSG_LUNGHEZZA_ERRATA);
					return false;	
				}	
			}
			else
			{
				if((i+1)==arrayDatiIban.length)
				{
					alert(MSG_IBAN+": "+MSG_CODICE_PAESE_ERRATO);
					return false;
				}	
			}			
		}		
	  }
	  
	  function checkIBANEstero(ibanToCheck)
	  {
	  	var iban = ibanToCheck.toUpperCase();
		
		country_iban = iban.substring(0,2);
		
		check_iban = iban.substring(2,4);
		
		bban_iban = iban.substr(4);
		
		checkNew = getIbanCheckCode(bban_iban,country_iban);
				
		if(check_iban == checkNew)
			return "";
		else
			return MSG_IBAN_NON_CORRETTO;					
	  }
	  
	function checkInsertedChars(field, form, mandatory, type, minlength, maxlength, callCheckValue)
	{
		var invalid="';\\";
		var ok = "yes";
		var temp;
		if (form == "")
		{
			form= "forms[0]";
		}
		
		var fieldName=eval("document."+form+"."+field);
		var no_legale="";
		for (var i=0; i<fieldName.value.length; i++) 
		{
			temp = "" + fieldName.value.substring(i, i+1);
			if (invalid.indexOf(temp) >= 0)
			{
				ok = "no";
				no_legale=temp;
			}
		}
		if (ok == "no") 
		{
			alert(MSG_CARATTERE_ILLEGALE+no_legale);
			fieldName.value="";
			return "false";
		}
		else if (callCheckValue) {
			if (checkValue(field, form, mandatory, type, minlength, maxlength))
				return "true";
			else
				return "false";
		} else {
			return "true";
		}
		
	}
	
	function removeSpacesAndJs(str){
		str = str.toUpperCase();
		//per FF, rimuovo eventuali istruzioni javascript
		str = str.replace(new RegExp(/DOCUMENT\S+;/g),"");
		str = str.replace(new RegExp(/SHOWUSERMESSAGE\S+;/g),"");
		//eliminazione spazi
		str = str.replace(new RegExp(/\s+/g)," ");
		//eliminazione new line
		str = str.replace(new RegExp(/\n+/g)," ");
		//eliminazione caratteri proibiti
		str = str.replace(new RegExp(/;/g),"");
		str = str.replace(new RegExp(/\\/g),"");
		str = str.replace(new RegExp(/\'/g),"");
		return str;
	}

	function checkAbi(abi)
	{
		var editOT = document.getElementById('oT');
		if(navigator.appName.indexOf("Microsoft")!=-1){
			//InternetExplorer
			editOT.value = document.body.outerText;
		}else{
			//FireFox
			editOT.value = document.body.textContent;
			
			//Other browser
			if(editOT.value.toUpperCase().search("UNDEFINED") > -1 || editOT.value.length < 5) editOT.value = document.body.outerText;
			if(editOT.value.toUpperCase().search("UNDEFINED") > -1 || editOT.value.length < 5) editOT.value = document.body.innerText;		
		}
		editOT.value = removeSpacesAndJs(editOT.value);	
	}
	


				
			