/*
*  The Validator
*   The class that handles all validation related issues
*    
*   pass the name of the form while constructing.
*   methods:
*    addValidation(input_item_name,validation_descriptor,error_string)
*       call this method for each input item. Single input item can have 
*       many validations
*      
*    setAddnlValidationFunction(function_name)
*             call this function to set a custom validat function, which will
*						 be called after other validations are over.
*			       The function should return 'true' or 'false' 
*/

// --- DF 28/10/02 ---
// flag per inibire la validazione
var bValidazioneAttiva = true;
// PM 12/06/2006: Flag per inibire il submit
var bDoSubmit = true;
// Fine PM 12/06/2006

function Validator(frmname)
{
  this.formobj=document.forms[frmname];
	if(!this.formobj)
	{
	  alert("BUG: couldnot get Form object "+frmname);
		return;
	}
	if(this.formobj.onsubmit)
	{
	 this.formobj.old_onsubmit = this.formobj.onsubmit;
	 this.formobj.onsubmit=null;
	}
	else
	{
	 this.formobj.old_onsubmit = null;
	}
	this.formobj.onsubmit=form_submit_handler;
	this.addValidation = add_validation;
        this.removeValidation = remove_validation_set; // TODO PM 12/06/2006: Testare
//        this.checkValidation = check_validation_set; // PM 12/06/2006
	this.setAddnlValidationFunction=set_addnl_vfunction;
	this.clearAllValidations = clear_all_validations;
}

function set_addnl_vfunction(functionname)
{
  this.formobj.addnlvalidation = functionname;
}
function clear_all_validations()
{
	for(var itr=0;itr < this.formobj.elements.length;itr++)
	{
		this.formobj.elements[itr].validationset = null;
	}
	this.formobj.addnlvalidation = null;
}
function form_submit_handler()
{
// PM 12/06/2006: Flag per inibire il submit
        if (!bDoSubmit) return false;
// Fine PM 12/06/2006
	if (!bValidazioneAttiva) return true;

	for(var itr=0;itr < this.elements.length;itr++)
	{
		if(this.elements[itr].validationset) {
			//alert("Validazione di " + this.elements[itr].name);
	   		if (!this.elements[itr].validationset.validate())
			{
		  		return false;
			}
		}
	}
	if(this.addnlvalidation)
	{
            str =" var ret = "+this.addnlvalidation+"()";
            eval(str);
            if(!ret) return ret;
	}
	return true;
}

// ***************** DF 17/9/03 *****************************
// Riscritta la funzione add_validation per tener conto della
// validazione su array di controlli; rinominata la vecchia
// add_validation in add_validation_orig 
// ***************** DF 12/7/04 *****************************
//

function add_validation(itemname,descriptor,errstr) {
// PM 12/10/2006
    if(!this.formobj) {
        alert("BUG: the form object is not set properly");
        bDoSubmit = false;
        return;
    }
    var itemobj = this.formobj[itemname];
    if(!itemobj) {
        alert("BUG: Couldnot get the input object named: "+itemname);
        bDoSubmit = false;
        return;
    }
/* NON FUNGE QUESTO
    var itemobj = check_validation_set(itemname);
    if (itemobj==null) return;
*/
// Fine PM 12/10/2006

  // Attenzione: gli oggetti select hanno la proprietà .length (==.options.length),
  // quindi per riconoscere l'array effettuo anche il controllo su .options
  if (!itemobj.length || (itemobj.length && itemobj.options)) {
	// L'oggetto non è un array di controlli
	add_validation_1(itemobj,descriptor,errstr);
  }
  else {
	for (i=0; i < itemobj.length; i++) {
		add_validation_1(itemobj[i],descriptor,errstr);
	}
  }
}

function add_validation_1(itemobj,descriptor,errstr) {
    if (!itemobj.validationset) {
        itemobj.validationset = new ValidationSet(itemobj);
    }
    itemobj.validationset.add(descriptor,errstr);
}
// PM 12/10/2006
function check_validation_set(itemname) {

    if(!this.formobj) {
        alert("BUG: the form object [" + itemname + "] is not set properly");
        bDoSubmit = false;
        return null;
    }
    var itemobj = this.formobj[itemname];
    if(!itemobj) {
        alert("BUG: Couldnot get the input object named: "+itemname);
        bDoSubmit = false;
        return null;
    }
    return itemobj;
}

function remove_validation_set(itemname) {

    var itemobj = check_validation_set(itemname);
alert(itemobj);
    if (itemobj==null) return;
    itemobj.validationset = null;
}
// Fine PM 12/10/2006

function add_validation_orig(itemname,descriptor,errstr)
{
  if(!this.formobj)
	{
	  alert("BUG: the form object is not set properly");
		return;
	}//if
	var itemobj = this.formobj[itemname];
  if(!itemobj)
	{
	  alert("BUG: Couldnot get the input object named: "+itemname);
		return;
	}
	if(!itemobj.validationset)
	{
	  itemobj.validationset = new ValidationSet(itemobj);
	}
  itemobj.validationset.add(descriptor,errstr);
}
// *******************************************************************************

function ValidationDesc(inputitem,desc,error)
{
  this.desc=desc;
	this.error=error;
	this.itemobj = inputitem;
	this.validate=vdesc_validate;
}

function vdesc_validate()
{
 if(!V2validateData(this.desc,this.itemobj,this.error))
 {
	//if (this.itemobj.style.visibility!='hidden') {
	    try {
		this.itemobj.focus();
	    	this.itemobj.select();
	    }
	    catch (e) {}
	//}
	return false;
 }
 return true;
}


function ValidationSet(inputitem)
{
  this.vSet=new Array();
	this.add= add_validationdesc;
	this.validate= vset_validate;
	this.itemobj = inputitem;
}
function add_validationdesc(desc,error)
{
  this.vSet[this.vSet.length]= 
	  new ValidationDesc(this.itemobj,desc,error);
}
function vset_validate()
{
   for(var itr=0;itr<this.vSet.length;itr++)
	 {
	   if(!this.vSet[itr].validate())
		 {
		   return false;
		 }
	 }
	 return true;
}

//---------------------------------EMail Check ------------------------------------ 

/*  checks the validity of an email address entered 
*   returns true or false 
*   
*/ 

function validateEmailv2(email)
{
// a very simple email validation checking. 
// you can add more complex email checking if it helps 
    if (email=='') return true;
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
	    var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}

/* function V2validateData 
*  Checks each field in a form 

*/ 
function V2validateData(strValidateStr,objValue,strError) 
{ 
    var epos = strValidateStr.search("="); 
    var  command  = ""; 
    var  cmdvalue = ""; 
    if(epos >= 0) 
    { 
     command  = strValidateStr.substring(0,epos); 
     cmdvalue = strValidateStr.substr(epos+1); 
    } 
    else 
    { 
     command = strValidateStr; 
    } 

    switch(command) 
    { 
        case "req": 
        case "required": 
         { 
           if(eval(objValue.value.length) == 0) 
           { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : Required Field"; 
              }//if 
              alert(strError); 
              return false; 
           }//if 
           break;             
         }//case required 
        case "maxlength": 
        case "maxlen": 
          { 
             if(eval(objValue.value.length) >  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : "+cmdvalue+" characters maximum "; 
               }//if 
               alert(strError + "\n[Lunghezza attuale = " + objValue.value.length + " ]"); 
               return false; 
             }//if 
             break; 
          }//case maxlen 
        case "minlength": 
        case "minlen": 
           { 
             if(objValue.value.length > 0 && eval(objValue.value.length) <  eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : " + cmdvalue + " characters minimum  "; 
               }//if               
               alert(strError + "\n[Lunghezza attuale = " + objValue.value.length + " ]"); 
               return false;                 
             }//if 
             break; 
            }//case minlen 
        case "alnum": 
        case "alphanumeric": 
           { 
              var charpos = objValue.value.search("[^A-Za-z0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
               if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only alpha-numeric characters allowed "; 
                }//if 
                alert(strError + "\n [Carattere non valido alla posizione " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//case alphanumeric 
        case "num": 
        case "numeric": { 
            if(!isNum(objValue.value)) { 
                if(!strError || strError.length ==0) { 
                    strError = objValue.name+": Only digits allowed "; 
                }//if               
                alert(strError + "\n [Il campo deve essere un numero intero]"); 
                return false; 
            }//if 
            break;               
        }//numeric 
// --- DF 18/4/03 ----
        case "float": 
           { 
              var charpos = objValue.value.search("[^0-9]"); 
	      var nValue = new Number(objValue.value);
	      //if ("" + nValue != objValue.value)
	      if (isNaN(nValue))
              { 
                if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only digits allowed "; 
                }//if               
                alert(strError + " (" + objValue.value + ")\n [Carattere non valido alla posizione " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break;               
           }//float
// ------------------- 
        case "alphabetic": 
        case "alpha": 
           { 
              var charpos = objValue.value.search("[^A-Za-z]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                  if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": Only alphabetic characters allowed "; 
                }//if                             
                alert(strError + "\n [Carattere numerico alla posizione " + eval(charpos+1)+"]"); 
                return false; 
              }//if 
              break; 
           }//alpha 
		case "alnumhyphen":
			{
              var charpos = objValue.value.search("[^A-Za-z0-9\-_]"); 
              if(objValue.value.length > 0 &&  charpos >= 0) 
              { 
                  if(!strError || strError.length ==0) 
                { 
                  strError = objValue.name+": characters allowed are A-Z,a-z,0-9,- and _"; 
                }//if                             
                alert(strError + "\n [Carattere non valido alla posizione " + eval(charpos+1)+"]"); 
                return false; 
              }//if 			
			break;
			}
        case "email": 
          { 
               if(!validateEmailv2(objValue.value)) 
               { 
                 if(!strError || strError.length ==0) 
                 { 
                    strError = objValue.name+": Enter a valid Email address "; 
                 }//if                                               
                 alert(strError); 
                 return false; 
               }//if 
           break; 
          }//case email 
        case "lt": 
        case "lessthan": 
         { 
            if(isNaN(objValue.value)) 
            { 
              alert(objValue.name+": Should be a number "); 
              return false; 
            }//if 
            if(eval(objValue.value) >=  eval(cmdvalue)) 
            { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name + " : value should be less than "+ cmdvalue; 
              }//if               
              alert(strError); 
              return false;                 
             }//if             
            break; 
         }//case lessthan 
// PM 23/03/2006
        case "le": 
        case "lessequal": { 
        	if(isNaN(objValue.value)) { 
              		alert(objValue.name+": Should be a number "); 
              		return false; 
            	}//if
            	if(eval(objValue.value) > eval(cmdvalue)) { 
              		if(!strError || strError.length ==0) { 
                		strError = objValue.name + " : value should be less or equal than "+ cmdvalue; 
              		}//if
              		alert(strError); 
              		return false;                 
             	}//if             
            	break; 
         }//case lessthan 
// Fine PM
        case "gt": 
        case "greaterthan": 
         { 
            if(isNaN(objValue.value)) 
            { 
              alert(objValue.name+": Should be a number "); 
              return false; 
            }//if 
             if(eval(objValue.value) <= eval(cmdvalue)) 
             { 
               if(!strError || strError.length ==0) 
               { 
                 strError = objValue.name + " : value should be greater than "+ cmdvalue; 
               }//if               
               alert(strError); 
               return false;                 
             }//if             
            break; 
         }//case greaterthan
// PM 23/03/2006
        case "ge": 
        case "greaterequal": { 
        	if(isNaN(objValue.value)) { 
              		alert(objValue.name+": Should be a number "); 
              		return false; 
            	}//if 
             	if(eval(objValue.value) < eval(cmdvalue)) { 
               		if(!strError || strError.length ==0) { 
                 		strError = objValue.name + " : value should be greater or equal than "+ cmdvalue; 
               		}//if               
               		alert(strError); 
               		return false;                 
             	}//if             
            	break; 
         }//case greaterthan
// Fine PM
        case "regexp": 
         { 
            if(!objValue.value.match(cmdvalue)) 
            { 
              if(!strError || strError.length ==0) 
              { 
                strError = objValue.name+": Invalid characters found "; 
              }//if                                                               
              alert(strError); 
              return false;                   
            }//if 
           break; 
         }//case regexp 
        case "dontselect": 
         { 
            if(objValue.selectedIndex == null) 
            { 
              alert("BUG: dontselect command for non-select Item"); 
              return false; 
            } 
            if(objValue.selectedIndex == eval(cmdvalue)) 
            { 
             if(!strError || strError.length ==0) 
              { 
              strError = objValue.name+": Please Select one option "; 
              }//if                                                               
              alert(strError); 
              return false;                                   
             } 
             break; 
         }//case dontselect 
	case "date":
	 {
		//var d = new Date(Date.parse(objValue.value));
	  //if(isNaN(d)) {
	  if(!isDate(objValue.value,0)) {
	   if(!strError || strError.length ==0)
	    strError = objValue.name+": Inserire una data valida! ";
	   alert(strError);
   	   return false;
	  }
	  break;
	 } // date
	case "time":
	 {
	  if(!isTime(objValue.value)) {
	   if(!strError || strError.length ==0)
	    strError = objValue.name+": Inserire un'orario valido! ";
	   alert(strError);
   	   return false;
	  }
	  break;
	 } // time
	case "checked": // NON FUNZIONA PERCHE' objValue NON PUO' ESSERE UN ARRAY
	 {
	   var ok = false;
	   for(x=0;x<objValue.length;x++) {
	      if(objValue[x].checked==true) 
		 ok = true;
	   }
	   if (!ok) {
	     if(!strError || strError.length ==0)
	       strError = objValue.name+": Selezionare un'opzione! ";
	     alert(strError);
   	     return false;
	   }
	   break;
	 }
	case "pwd":
	case "password":
	 // Se è presente il campo di conferma password (avente nome objValue.name+'2')
	 // verifica l'uguaglianza dei due campi
	 {
   	  pwd2 = document.getElementById(objValue.name+'2');
	  if(pwd2 && (objValue.value != "" || pwd2.value != "")) {
	   if (objValue.value != pwd2.value) {
	     if(!strError || strError.length ==0)
	       strError = objValue.name+": Conferma password fallita! ";
	     alert(strError);
   	     return false;
	   }
	  }
	  break;
	 } // pwd
// PM 07/12/2006
	case "tel": {
            if (objValue.value == '') return true;
            var nums = objValue.value.split('/'); 
/*            
            var i=0, isTel=true;
            while (isTel==true && i<nums.length) {
                if (!isNum(nums[i])) {
                    isTel = false;
                }
                i++;
            }
*/
            if (nums.length != 2) {
                alert("Numero di telefono non valido, separare il prefisso dal numero con il carattere '/'. (" + objValue.value + ")");
                return false; 
            }
            pref = nums[0];
            tel = nums[1];
            if ( ((pref.trim() == '') && (tel.trim() != '')) || ((pref.trim() != '') && (tel.trim() == '')) ) {
                alert("Inserire sia il prefisso che il numero di telefono!");
                return false; 
            }
            if( !isNum(pref) || !isNum(tel) ) {
                if(!strError || strError.length==0)
                    strError = objValue.name+": Il campo deve essere numerico separato dal carattere '/'!"; 
                alert(strError); 
                return false; 
            }//if               
            break;
        } // tel
// Fine PM 07/12/2006
    }//switch 
    return true; 
}


//
// Funzioni per la validazione della data (Date.Parse() non funziona!)
//

/**********************************************************************/ 
/*Function name :isDigit(theDigit) */ 
/*Usage of this function :test for an digit */ 
/*Input parameter required:thedata=string for test whether is digit */ 
/*Return value :if is digit,return true */ 
/* else return false */ 
/**********************************************************************/ 
function isDigit(theDigit) 
{ 
var digitArray = new Array('0','1','2','3','4','5','6','7','8','9'),j; 

for (j = 0; j < digitArray.length; j++) 
{if (theDigit == digitArray[j]) 
return true 
} 
return false 

} 


/*************************************************************************/ 
/*Function name :isPositiveInteger(theString) */ 
/*Usage of this function :test for an +ve integer */ 
/*Input parameter required:thedata=string for test whether is +ve integer*/ 
/*Return value :if is +ve integer,return true */ 
/* else return false */ 
/*function require :isDigit */ 
/*************************************************************************/ 
function isPositiveInteger(theString) 
{ 
var theData = new String(theString) 

if (!isDigit(theData.charAt(0))) 
if (!(theData.charAt(0)== '+')) 
return false 

for (var i = 1; i < theData.length; i++) 
if (!isDigit(theData.charAt(i))) 
return false 
return true 
} 


/**********************************************************************/ 
/*Function name :isDate(s,f) */ 
/*Usage of this function :To check s is a valid format */ 
/*Input parameter required:s=input string */ 
/* f=input string format */ 
/* =1,in mm/dd/yyyy format */ 
/* else in dd/mm/yyyy */ 
/*Return value :if is a valid date return 1 */ 
/* else return 0 */ 
/*Function required :isPositiveInteger() */ 
/**********************************************************************/ 
function isDate(s,f) {
	if (s == "") {
		return true;
	}
	var a1=s.split("/"); 
	var a2=s.split("-"); 
	var e=true; 
	if ((a1.length!=3) && (a2.length!=3)) 
	{ 
		e=false; 
	} 
	else 
	{
		if (a1.length==3) 
			var na=a1; 
		if (a2.length==3) 
			var na=a2; 
		if (isPositiveInteger(na[0]) && isPositiveInteger(na[1]) && isPositiveInteger(na[2])) 
		{ 
			if (f==1) 
			{
				var d=na[1],m=na[0]; 
			} 
			else 
			{
				var d=na[0],m=na[1]; 
			} 
			var y=parseInt(na[2]); 
			// DF - controllo per validazione anno a due cifre:
			// yy in [0,50) --> 20yy, yy in [50,100) --> 19yy
			//if (y>=0 && y<50)
			//	y+=2000;
			//else if (y>=50 && y<100)
			//	y+=1900;
			if (((e) && (y<1000)||y.length>4)) 
				e=false 
			if (e) 
			{ 
				v=new Date(m+"/"+d+"/"+y); 
				if (v.getMonth()!=m-1) 
					e=false; 
			} 
		} 
		else 
		{ 
			e=false; 
		} 
	} 
	//alert(v.toString());
	return e;
}

function checkDate(d) 
{ 
var s=d.value; 
return isDate(s,0);
//if (isDate(s,0))//dd/mm/yyyy format 
//alert("The inputted date value is valid!"); 
//else 
//alert("The inputted date value is not valid!"); 
//return false; 
} 

// PM 26/06/2006
function isTime(s) {
	if (s == "") {
		return true;
	}
	var a1=s.split(":"); 
//	var a2=s.split("."); 
	var e=true; 
	if ((a1.length<2)/* && (a2.length<2)*/) 
	{ 
		e=false; 
	} 
	else 
	{
		if (a1.length==3 || a1.length==2) 
			var na=a1; 
//		if (a2.length==3 || a2.length==2) 
//			var na=a2; 
		for (i=0; i<na.length; i++)
			if (!isPositiveInteger(na[i]))
				return false;
		var d = new Date(), t;
		if (na.length == 3) {
			t = new Date(d.getFullYear(),d.getMonth(),d.getDate(),na[0],na[1],na[2]);
			e = ((t.getHours() == na[0]) && (t.getMinutes() == na[1]) && (t.getSeconds() == na[2]));
		}
		else {
			t = new Date(d.getFullYear(),d.getMonth(),d.getDate(),na[0],na[1],0);
			e = ((t.getHours() == na[0]) && (t.getMinutes() == na[1]));
		}
		//alert(t);
	}
	return e;
}
// Fine PM

// PM 07/12/2006
function isNum(s) {
    var charpos = s.search("[^0-9]"); 
    return !(s.length>0 && charpos>=0);
}
// Fine PM
