var defaultCombo = "seleziona";
var maxImporto = 30000;
var minImporto = 500;

var valid = new Object();

    // inizio REGEX Elements

        // matches zip codes
        valid.zipCode = /^[0-9]{5}$/;

        // matches $17.23 or $14,281,545.45 or ...
        valid.Currency = /\$\d{1,3}(,\d{3})*\.\d{2}/;

        // matches 5:04 or 12:34 but not 75:83
        valid.Time = /^([1-9]|1[0-2]):[0-5]\d$/;

        //matches email
        //valid.emailAddress = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
				//valid.emailAddress = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
				//valid.emailAddress = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
				valid.emailAddress = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

        // matches phone ###-###-####
        valid.phoneNumber = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
		//valid.phoneNumber = /^([\d]|1[0,1,2])/([0-9]|[0,1,2][0-9]|3[0,1])/\d{4}$/;

        // International Phone Number
        valid.phoneNumberInternational = /^\d(\d|-){5,20}/;

        // IP Address
        valid.ipAddress = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;

        // Date xx/xx/xxxx
        valid.Date = /^\d{1,2}(\/)\d{1,2}\1\d{4}$/;

        // State Abbreviation
        valid.State = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i;

        // Social Security Number
        valid.SSN = /^\d{3}\-\d{2}\-\d{4}$/;
		
		// Text
		valid.letterRequiered = /^(?=.*[a-zA-Z]+.*)/;
		
		// Text1
		valid.letter1 = /^[a-zA-Z]{1}$/;	
		
		// Number
		valid.onlyNumbers = /^[0-9]+$/;

		// Alfanumerico 12
		valid.alfaNum4 = /^[a-zA-Z0-9]{4}$/;	
		
		valid.alfaNum1 = /^[a-zA-Z0-9]{1}$/;	

		// Alfanumerico 12
		valid.alfaNum12 = /^[a-zA-Z0-9]{12}$/;	
		
		// Alfanumerico 5
		valid.Numerico5 = /^[0-9]{5}$/;			

		// Alfanumerico
		valid.alfaNum = /^[a-zA-Z0-9]+$/;		
		
		// Nome e cognome in campi separati
		valid.textName = /^[a-zA-Z]+(([\'\,\.\-\ ][a-zA-Z])?[a-zA-Z]*)*$/;
		
		valid.codFiscale = /[A-Z]{6}[0-9]{2}[A-Z][0-9]{2}[A-Z][0-9]{3}[A-Z]/;
		
		
		
cValidator  = new Class({
			   isInteger: function (s) {
							return (s.toString().search(/^-?[0-9]+$/) == 0);
						}
				,
				exec: function(valore,caso){		
						switch(caso)
						{

						case 'sempreTrue':
								return true;
						
						break;
						
						case 'ITSM':
								if (valore.substring(0,2).toUpperCase()=='IT' || valore.substring(0,2).toUpperCase()=='SM')
								{
									return true;
								}
								else
								{
									return false;											
								}
						
						break;						

						case 'primoZero':
								if (valore.substring(0,1)=='0')
								{
									return true;
								}
								else
								{
									return false;											
								}
						
						break;

						case 'primoTre':
								if (valore.substring(0,1)=='3')
								{
									return true;
								}
								else
								{
									return false;											
								}
						
						break;

						
						case 'codiceFiscale':
								return ControllaCF(valore);
						
						break;
						
						case 'meseNonFuturo':

								var d = new Date();
								meseCorrente = 1 + d.getMonth();
								if (valore>meseCorrente){
									
									return false
								}
								else
								{
									return true
								}

						  break;						
						

						case 'maggiorenne':

								if (Age(valore)<18){
									
									return false
								}
								else
								{
									return true
								}

						  break;
						
						case 'abicab':
								if (verificaAbiCab($('CDABICLI').value,$('CDCABCLI').value))
								{
									return true;
								}
								else
								{
									return false;											
								}

						  break;    
						
						case 'maxImporto':
								if ((this.isInteger(valore)) && (valore<=maxImporto))
								{
									return true;
								}
								else
								{
									return false;											
								}

						  break;    
						  
						case 'minImporto':
								if ((this.isInteger(valore)) && (valore>=minImporto))
								{
									return true;
								}
								else
								{
									return false;											
								}

						  break;						  
						  
						case 'notNull':
								if ((valore.isNull  == true) || (valore=="") || (valore==defaultCombo))
								{
									return false;
								}
								else
								{
									return true;											
								}

						  break; 						  
						  
						  case 'trueDateMY':
						  
								if (isDateMY(valore)==false){
									
									return false
								}
								else
								{
									return true
								}

						  break;


						  case 'trueDate':
						  
								if (isDate(valore)==false){
									
									return false
								}
								else
								{
									return true
								}

						  break;
						  
						case 'statoProvinciaCliente':
								
								if (($('NAZNASCITA').value.toUpperCase() == 'ITALIA') && ($('CDPRVNASCLI').value.toUpperCase()=="EE"))
								{
									return false;
								}
								else if (($('NAZNASCITA').value.toUpperCase() != 'ITALIA') && ($('CDPRVNASCLI').value.toUpperCase()!="EE"))
								{
									return false;
								}
								else
								{
									return true;											
								}
								
						case 'statoProvinciaCoobbligato':
								
								if (($('NAZNASCITACOO').value.toUpperCase() == 'ITALIA') && ($('CDPRVNASCOO').value.toUpperCase()=="EE"))
								{
									return false;
								}
								else if (($('NAZNASCITACOO').value.toUpperCase() != 'ITALIA') && ($('CDPRVNASCOO').value.toUpperCase()!="EE"))
								{
									return false;
								}
								else
								{
									return true;											
								}								

						  break; 						  
						  
						  
						  
						default:
						  alert('Errore nella validazione valore:' + valore + ' caso:' + caso);
						}

						
				}
		 })





var validatorObject = new Class({
						  
						  
						  
	initialize: function(){
	    
	    
	    
	},
	

	validatePlus : function(obbligatorio,valutaErroriCorrente,field,fieldValue,arrValidation){

		var strOptions="";
		var error=false;
		var message="";



		strOptions+="i";

		
		arrValidation.each(function(item, index){
			
			try
			{
				tipo = item[0];
				
				validR = item[1];
				messageCurr = item[2];
				
				if (tipo=='custom')
				{
					
					if (!customValidator.exec(fieldValue,validR))
					{
			
						error = true;
						if (message=="")
						{
							message = messageCurr;
						}
	
						
					}
				}
				else
				{
					if (!validR.exec(fieldValue))
					{
			
						error = true;
						if (message=="")
						{
							message = messageCurr;
						}
						
					}				
				}
			}
			catch(err)

			{}

		
		
		}); //The optional second argument for binding isn't used here.
		

			if ((error==false) || ((obbligatorio == false) && (fieldValue == "")))
			{
				
				if (obbligatorio == false)
				{
					$('img' + field.id).set('src','img/null.gif');
				}
				else
				{
					$('img' + field.id).set('src','img/ok.gif');	
				}

				field.setStyle('background-color','#FFFFFF');
				try
				{
				  $(field.id+'_GG').setStyle('background-color','#FFFFFF');	
				  $(field.id+'_MM').setStyle('background-color','#FFFFFF');	
				  $(field.id+'_AAAA').setStyle('background-color','#FFFFFF');	
				}
				catch(e)
				{}				


				$('error' + field.id).set('html','');
				
				
				//return true;
			}
			else
			{

				$('img' + field.id).set('src','img/ko.gif');
				field.setStyle('background-color','#EDC2AE');	

				
				try
				{
				  $(field.id+'_GG').setStyle('background-color','#EDC2AE');	
				  $(field.id+'_MM').setStyle('background-color','#EDC2AE');	
				  $(field.id+'_AAAA').setStyle('background-color','#EDC2AE');	
				}
				catch(e)
				{}				
				
				try
				{		
					$('error' + field.id).set('html',message);
				}
				catch (e) 
				{

					alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message + " - " + field.id); 
				}
	
				
				window[valutaErroriCorrente]=true;
				//return false;

			}
	}
		
});





var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isDateMY(dtStr){

	var strMonth=dtStr.substring(0,2);
	var strYear=dtStr.substring(3,2);
	
	if (isInteger(strMonth) && isInteger(strYear))
	{
		return true;
	}
	else
	{
		return false;
	}

}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var dtCh= "/";
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}


function ControllaCF(cf)
{
    var validi, i, s, set1, set2, setpari, setdisp;
    if( cf == '' )  return '';
    cf = cf.toUpperCase();
    if( cf.length != 16 )
        return false;
		/*"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 false;
			/*"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 false;
		/*"Il codice fiscale non ? corretto:\n"+
            "il codice di controllo non corrisponde.\n";*/
    return true;
}



function Age(dateString )
{
/*
   function getAge
   parameters: dateString dateType
   returns: boolean

      */

    var now = new Date();
   

    var yearNow = now.getYear();
    var monthNow = now.getMonth()+1;
    var dateNow = now.getDate();

  
   
    //if (dateType == 3)
     var dob = new Date(dateString.substring(6,10),dateString.substring(3,5),dateString.substring(0,2));
   
   

    var yearDob = dob.getYear();
    var monthDob = dob.getMonth();
    var dateDob = dob.getDate();

    var yearAge = yearNow - yearDob;

    if (monthNow >= monthDob)
        var monthAge = monthNow - monthDob;
    else
    {
        yearAge--;
        var monthAge = 12 + monthNow -monthDob;
    }

    if (dateNow >= dateDob)
        var dateAge = dateNow - dateDob;
    else
    {
        monthAge--;
        var dateAge = 31 + dateNow - dateDob;

        if (monthAge < 0)
        {
            monthAge = 11;
            yearAge--;
        }
    }
	
	if (yearAge>100)
	{
		yearAge = yearAge -1900;
	}
	
    return yearAge;
}




customValidator = new cValidator();
validator = new validatorObject();





