/*controllo avanzato delle forms*/

/*function removeError(el, class){
 el.setAttribute('class', class);
 $(el.id + '_status_img').visible='false';
}
*/
function getAttributeM(el, attr){
 if ( 
     (el.getAttribute(attr) != null) &&
     (el.getAttribute(attr) != undefined) &&
     (el.getAttribute(attr) != '')){
   return el.getAttribute(attr);
  }else{
   return false;
 }
}

function checkFiscalCode(cf){
	var validi, i, s, set1, set2, setpari, setdisp;
	if( cf == '' )  return '';
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return "La lunghezza del codice fiscale non è\n"
		+"corretta: il codice fiscale dovrebbe essere lungo\n"
		+"esattamente 16 caratteri.\n";
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return "Il codice fiscale contiene un carattere non valido `" +
				cf.charAt(i) +
				"'.\nI caratteri validi sono le lettere e le cifre.\n";
	}
	set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	s = 0;
	for( i = 1; i <= 13; i += 2 )
		s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	for( i = 0; i <= 14; i += 2 )
		s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
		return "Il codice fiscale non è corretto:\n"+
			"il codice di controllo non corrisponde.\n";
	return "";
}


function checkVatNumber(pi)
{
	if( pi == '' )  return '';
	if( pi.length != 11 )
		return "La lunghezza della partita IVA non è\n" +
			"corretta: la partita IVA dovrebbe essere lunga\n" +
			"esattament4e 11 caratteri.\n";
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return "La partita IVA contiene un carattere non valido `" +
				pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n";
	}
	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) )
		return "La partita IVA non è valida:\n" +
			"il codice di controllo non corrisponde.\n";
	return '';
}


function checkFiscalId(pi){
  var cod = pi;
  var err = ''; 
  var skipLenghtCheck = false;
  if( cod == '' ){
  	err = "Il campo partita iva è vuoto\n";  
  }else{
   switch (cod.substring(0, 2)){
     case 'SM': err = '';
	            skipLenghtCheck = true;
                break;
     case 'FR': err = '';
	            skipLenghtCheck = true;
                break;
   }
  }
  if (skipLenghtCheck == false){
   if( cod.length == 16 ){
 	 err = checkFiscalCode(cod);
   }else{
    if( cod.length == 11 ) {
	 err = checkVatNumber(cod);
	}else{
	 err = "Il codice introdotto non è valido:<br />" +
	       "  - un codice fiscale deve essere lungo 16 caratteri.<br />" +
		   "  - una partita IVA deve essere lunga 11 caratteri.<br />";
   }
  }
  }
  if( err !== '' ){
	return ("valore errato\n\n" + err + "\nCorreggi e riprova!");
  }else{
   return true;
  }
}

   function emailCheck (emailStr){
      var emailPat=/^(.+)@(.+)$/
      var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
      var validChars="\[^\\s" + specialChars + "\]"
      var quotedUser="(\"[^\"]*\")"
      var atom=validChars + '+'
      var word="(" + atom + "|" + quotedUser + ")"
      var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
      var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
      var matchArray=emailStr.match(emailPat)
      if (emailStr.length < 2){
       return("L'indirizzo e-mail è obbligatorio");
      }
      
      if (matchArray==null) {
       return("L'indirizzo e-mail errato (controlla @ e .)");
      }
      var user=matchArray[1]
      var domain=matchArray[2]
      if (user.match(userPat)==null) {
       return("L'indirizzo e-mail è errato");      
      }

      var domainArray=domain.match(domainPat)
      if (domainArray==null) {
	     return("L'indirizzo e-mail ha il nome di dominio errato");       
      }

      var atomPat=new RegExp(atom,"g")
      var domArr=domain.match(atomPat)
      var len=domArr.length
      if (domArr[domArr.length-1].length<2 || 
          domArr[domArr.length-1].length>4) {
       return("L'indirizzo e-mail deve terminare con un dominio o con il codice di una nazione (.it o .com as esempio)");       
      }

      if (len<2) {
       return("L'indirizzo e-mail ha il nome host errato");
      }
    
		  return true;
     }

     function showMessage(messageid, elId){		  
			var message = '';
			var el = '';			
			message = document.getElementById(messageid);			
			if (message.style.display == 'block'){			 
			 message.style.display = 'none';			 
			 if (elId != ''){
   			el = document.getElementById(elId);
			  el.setAttribute('src', '/images/plus_info.gif');
			 }
		  }else{
			 if (elId != ''){
   			el = document.getElementById(elId);
			  el.setAttribute('src', '/images/minus_info.gif');
			 }
		   message.className = 'messages';
       message.style.display = 'block';
			}			
		 }

     function addStatus(appendTo, labelId, imageId,statusText){
      var errSpan = document.createElement('span');			      
      var img='';
			var parentNode='';
			errSpan.setAttribute("id", labelId);      
      img=document.createElement('img');
      img.setAttribute('id', imageId);
      img.alt=statusText;
      img.title='verifica campo';
      errSpan.appendChild(img);
      parentNode = appendTo.parentNode;
      parentNode.insertBefore(errSpan, appendTo.nextSibling);
     }	 

     function advFormCheck(formToCheck){       
  	  var num_of_elements = formToCheck.length;		  
	  var form_id=formToCheck.id;
	  var reqElementsCount = 0;
	  var totalpack = 0;
	  var errorMessages = '';
	  var errorMessageDefaultText = '';
	  var errorCount=0;			
	  var errorMessageBox = document.getElementById('errorMessage');
	  var illegalChars = /\W/; // allow letters, numbers, underscores  		  
	  //var illegalChars = /[A-Za-z0-9\_]/; //Supports alphabets and numbers no special characters except underscore('_') min 3 and max 20 characters. 
      var errorStyle = "BORDER-RIGHT: #FF8000 1px solid; BORDER-TOP: #FF8000 1px solid; MARGIN: 0px; BORDER-LEFT: #FF8000 1px solid; BORDER-BOTTOM: #FF8000 1px solid; COLOR: #FF8000; BACKGROUND-COLOR: #FFFFD7";
      var defaultStyle = "";
      
			for (var i=0; i<num_of_elements; i++) {   		
			 var theElement = formToCheck.elements[i];
   		 var elType = theElement.type;
	   	 var elName = theElement.name;
		   var elValue = theElement.value;
		   var elDescription = theElement.getAttribute('description');
			 var elId = theElement.id
			 var elStatusName = elId + '_status';
			 var imageError = '/images/checkko.gif';
			 var imageOk = '/images/checkok.gif';
			 var imageBlank = '/images/2pix.gif';
       var elStatus = ''
       var elStatusImg = '';
			 var elStatusImgId=elId + '_status_img';
			 var mailError = '';       
       var elChecked = false; //messo a true quando il campo viene verificato, in questo modo skippo il controllo "generico"
       var checkIf = getAttributeM(theElement, 'checkIf');
       var checkIfExists = ($(checkIf) != null);
       elId.Style = '';       
			 if ((elName != undefined) &&
			     (elId != '')){
  		  if (elId.indexOf('req_') != -1){
  			 //creo lo span con immagine l'immagine  ha il nome dell'elemento da controllare + status_img
					if (document.getElementById(elStatusName) == null){
				  addStatus(theElement, elStatusName, elStatusImgId, 'in verifica...');
			   }
			   elStatusImg = document.getElementById(elStatusImgId);
  			 if (((elValue == '') ||
		          (elValue == '0') ||
				 	    (elValue == '0.0') || 
					    (elValue == '0.00')||
						  (elValue == '9999') ||
              (elValue == 'none') ) &&
						  (!checkIf)){
 				  errorCount += 1; 				  
			    theElement.setAttribute('style', errorStyle);
          elStatusImg.setAttribute('src', imageError);
          if (theElement.getAttribute('errormessage') != null){
           errorMessages = errorMessages + '- ' + theElement.getAttribute('errormessage');
          }
         }else{
         
			    theElement.setAttribute('style', errorStyle);
          elStatusImg.setAttribute('src', imageOk);
			    
          //verifica radio button
			    if (elType == 'radio'){
           var btnYesId=elId.substring(0, elId.length-1) + 'Y';
					 var btnNoId=elId.substring(0, elId.length-1) + 'N';
					 var btnHiddenId=elId.substring(0, elId.length-1) + 'H';					 
					 if (elId != btnHiddenId){					 
					  if ((!document.getElementById(btnYesId).checked) &&
					      (!document.getElementById(btnNoId).checked)){
					   errorCount += 1;
						 errorMessages = errorMessages + '<li>' + 'Dovete scegliere se accettare o meno la proposta' + '</li>';
						 document.getElementById(elId).setAttribute('style', errorStyle);
             elStatusImg.setAttribute('src', imageError);
					   }
					 }
  				}
          
					// verifica username
					if (elId.indexOf('username') != -1){
					 if (illegalChars.test(elValue)){					  
					  errorCount += 1;
					  errorMessages = errorMessages + '<li>' + 'Il nome utente deve contenere solo numeri o lettere o il simbolo "_"' + '</li>';
                      document.getElementById(elId).setAttribute('style', errorStyle);
                      elStatusImg.setAttribute('src', imageError);
					 }
 					 if (elValue.length < 6){
					  errorCount += 1;
						errorMessages = errorMessages + '<li>' + 'Il nome utente deve esse lungo almeno 6 caratteri' + '</li>';
            document.getElementById(elId).setAttribute('style', errorStyle);
						elStatusImg.setAttribute('src', imageError);
					 }
					}
					
          //verifica password
					if ((elId.indexOf('password') != -1) &&
	            (elId.indexOf('check') == -1)){					 
					 if (illegalChars.test(elValue)){
					  errorCount += 1;
						errorMessages = errorMessages + '<li>' + 'La password deve contenere solo numeri o lettere e il simbolo "_"' + '</li>';
						document.getElementById(elId).setAttribute('style', errorStyle);
            elStatusImg.setAttribute('src', imageError);
					 }else{
            if (elValue.length<6){
 					   errorCount += 1;
						 errorMessages = errorMessages + '<li>' + 'La password deve essere lunga almeno 6 caratteri' + '</li>';
						 document.getElementById(elId).setAttribute('style', errorStyle);
						 elStatusImg.setAttribute('src', imageError);
						}					 
					 } 
					}
				
					//verifica della password di controllo.			
					if (elId.indexOf('password_check') != -1){			     
					 if (elValue != document.getElementById('req_password').value){
					  errorCount += 1;
						errorMessages = errorMessages + '<li>' + 'Le password immesse non coincidono' + '</li>';
						document.getElementById(elId).setAttribute('style', errorStyle);
						elStatusImg.setAttribute('src', imageError);					  
					 }
					}
          
					//verifica e-mail					
					if (elId.indexOf('email') != -1){					 
           var checkMail = true;           
					 if (checkIf != false){
					  if (theElement.getAttribute('checkIf') != ''){              
               if (($(checkIf).type == 'checkbox') ||
                   ($(checkIf).type == 'radio')) {                 
                checkMail = $(checkIf).checked;
                // se il campo checkIf alla fine termina con _Y effettuo il controllo solo se il campo indicato in
                //checkif è a true (checked)
                if(checkIf.substr(-2) == '_Y'){                
                 if ($(checkIf).checked){
                  checkMail = $(checkIf).checked;
                 }else{                 
                  checkMail = false;
                 }
                }
						   }else{                
                checkMail = ($(checkIf).value.trim().length > 0);
               }              
				    }else{
					   checkMail = true;
					  }
				   }
           
				   if (checkMail){          
            mailError = emailCheck(elValue);
					  if ( mailError !== true ){
					   errorCount += 1;
						 errorMessages = errorMessages + '<li>' + mailError;						
						 document.getElementById(elId).setAttribute('style', errorStyle);
						 elStatusImg.setAttribute('src', imageError);					 
				 	  }else{
					   document.getElementById(elId).setAttribute('style', errorStyle);
             elStatusImg.setAttribute('src', imageOk); 
					  }
			     }					
          }
          
          //verifica del campo di check incrociato della mail
          if (checkMail){
           if (elId.indexOf('email_check') != -1){
            mailError = emailCheck(elValue);					  
            if ( mailError !== true ){
					   errorCount += 1;
						 errorMessages = errorMessages + '<li>' + mailError;            
						 document.getElementById(elId).setAttribute('style', errorStyle);
						 elStatusImg.setAttribute('src', imageError);					 
				 	  }else{
					   document.getElementById(elId).setAttribute('style', errorStyle);
             elStatusImg.setAttribute('src', imageOk); 
					 }
			    }
          }
                    
					// verifica partita iva o codice fiscale.
					if (elId.indexOf('vatnumber') != -1){
           var validateVatNumber = true;
					 if (checkIf != false){					               
             if ($(checkIf).value != ''){
              validateVatNumber = false;
             }            
           }
           if (validateVatNumber){
            var vatError = checkFiscalId(elValue);
					  if ( vatError !== true ){
					   errorCount += 1;
					 	 errorMessages = errorMessages + '<li>' + vatError;						
						 document.getElementById(elId).setAttribute('style', errorStyle);
						 elStatusImg.setAttribute('src', imageError);					 
				 	  }else{
						 document.getElementById(elId).setAttribute('style', errorStyle);
             elStatusImg.setAttribute('src', imageOk); 
					  }
			     }
          }
					
          //verifica del tipo checkbox          
  		    if (elType == 'checkbox'){
					 var checkCombo = true;				   
					 if (checkIf != false){
					   if($(checkIf).checked){
					    checkCombo = true;
						 }else{
						  checkCombo = false;
						 }
				    }else{
					   checkCombo = true;
					  }
				   }
           
					 if (checkCombo){
			      if (elStatus != undefined){
				     if (theElement.checked == true){
  		        elStatusImg.setAttribute('src', imageOk);
  		       }else{
  		        errorCount += 1;
  		        if (theElement.getAttribute('errormessage')){
						   errorMessages = errorMessages + '<li>' + theElement.getAttribute('errormessage');
						  }
						  document.getElementById(elId).setAttribute('style', errorStyle);
						  elStatusImg.setAttribute('src', imageError);
				     }
			      }
			     }
			    //fine checkbox
          					
          if (checkIf != false){
           if ($(checkIf) != null){             
            if ($(checkIf).value != ''){
             validateVatNumber = false;             
            }
           }
          }          
   
					 if (checkIf != false){
             if($(checkIf) != null ){
              if(checkIf.substr(checkIf.length - 2) == '_Y'){
               if ($(checkIf).checked){
                if (theElement.value.trim() != theElement.value.trim()){
    				     errorCount += 1;
                 errorMessages = errorMessages + '<li>' + theElement.getAttribute('errormessage');
						     document.getElementById(elId).setAttribute('style', errorStyle);
			    		   elStatusImg.setAttribute('src', imageError);
                }
               }              
              }else{              
              if (($(checkIf).type == 'checkbox') ||
                  ($(checkIf).type == 'radio')) {
               if (!$(checkIf).checked){
                errorCount += 1;
                errorMessages = errorMessages + '<li>' + theElement.getAttribute('errormessage');
						    document.getElementById(elId).setAttribute('style', errorStyle);
			    	    elStatusImg.setAttribute('src', imageError);             
               }
  				    }else{
               if ($(checkIf).value.trim() != theElement.value.trim()){
    				    errorCount += 1;
                errorMessages = errorMessages + '<li>' + theElement.getAttribute('errormessage');
						    theElement.setAttribute('style', errorStyle);
			    		  elStatusImg.setAttribute('src', imageError);
               }               
              }
              
              
             }             
            }
      
          
          }          
          
         }
        }
       }
      }
		  // se ci sono errori ritorno false
      if (errorCount > 0){
       //theElement.addEvent('enter', 'removeError(\'this\')');
	     // se all'interno della pagina è stato definito un elemento errorMessage
	     // scrivo nel box il messaggio di errore.			 
       if (errorMessageBox != null){
        // se ci sono errori specifici, li mostro
				errorMessageDefaultText = '<fieldset>' + 
                       '<legend>Errore di compilazione della form</legend>' + 
                       'I campi contrassegnati da una X rossa non sono compilati correttamente<br />' +
				 		 				   'ti preghiamo di verificare i dati immessi';					 						 
           					 						 
				if (errorMessages.length > 0){
				 errorMessageDefaultText = errorMessageDefaultText +
				                           '<br /><br />Si sono verificati i seguenti errori specifici: <ul>' +
																	 errorMessages  +
																	 '</ul>'; 
				} 
				errorMessageDefaultText = errorMessageDefaultText + '</fieldset><br /><br />';
				errorMessageBox.className = 'errormessagewhite';
			  errorMessageBox.style.visibility = 'visible';
        errorMessageBox.innerHTML = errorMessageDefaultText.replace('<li>null', ''); 
		   }
			 return false;
		  }     
		 if (errorMessageBox != null){
      errorMessageBox.style.visibility = 'hidden';
		  errorMessageBox.className = '';
		  errorMessageBox.innerHTML = '';
     }
     return true;
    }
/*fine controllo avanzato delle form*/