// Fixed Portal common javascript functions

function goToUrl (url){
}

function submitForm(url) {
}

function scrollEveryWhere(param1, param2) {
}

// Open a window centered in the screen
function openCenteredWindow(url, height, width, name, parms) {
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
	var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
	if (parms) { winParms += "," + parms; }
	var win = window.open(url, name, winParms);
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
	return win;
}


// Close the calling windows and reload parent
function closeAndOpenwindow(url)
{
	window.close();
	window.opener.location = url;
}

// Check login form empty fields
function validateLogin()
{
	var errorString = "";
	var alertMsg = "";
	document.formLogin.username.value = trimSpace(document.formLogin.username.value);
	if (document.formLogin.username.value=="")
	{
		errorString += "- Username\n";
	}
	document.formLogin.password.value = trimSpace(document.formLogin.password.value);
	if (document.formLogin.password.value=="") errorString += "- Password"
	if (errorString!="")
	{
		alert("Si prega voler compilare i seguenti campi obbligatori:\n"+errorString);
		return false;
	}
	else {
		return true;
	}
}

// Trim spaces
function trimSpace(passedVal)
{
    var i, j;
    for(i=0; i<passedVal.length; i++ ) {
         if (passedVal.charAt(i)!=" ")
              break;
    }
    for(j=passedVal.length-1; j>=0; j-- ) {
         if (passedVal.charAt(j)!=" ")
              break;
    }
    if (i > j)
         passedVal = "";
    else
         passedVal = passedVal.substring(i, j+1);
    return(passedVal);
}

/*************************************************************************
 * ServiceCenter - Validate Find        *
 *************************************************************************/
function validateFormShopAssistance()
{
  var errorMsg="";
  var alertMsg="";

  errorMsg=isEmptyProvince(document.coverageForm.provinceId)+isEmptyCity(document.coverageForm.cityId);
  if(!(document.coverageForm.shopFlag.checked || document.coverageForm.serviceFlag.checked ))
	errorMsg +=" - TIPO DI PUNTO VENDITA \n";

  if(errorMsg!="")
    alert("Prego voler inserire i seguenti campi obbligatori:\n"+errorMsg);
   else
    document.coverageForm.submit();
}

// Checks if city selected is empty

function isEmptyCity(obj)
{
  if(obj.selectedIndex==0)
    return " - COMUNE \n";
  else
    return "";
}

// Checks if province selected is empty
function isEmptyProvince(obj)
{
  if(obj.selectedIndex==0)
    return " - PROVINCIA \n";
  else
    return "";
}

function validateJobsAreas(){
   var intestazione = "";
   var errorString = "";

   //Job Area - Step 1: Validate option buttons
  // Option button Job Area - Validation
   for (i=0; i<document.jobForm.jobAreaSelected.length; i++){
      //Option Button not selected
      if (!document.jobForm.jobAreaSelected[i].checked) {
         if (errorString == "")
          errorString =  "Scegli l'area che ti interessa e inviaci i tuoi dati compilando il form \n";
      }
      //Option Button selected
      else {
         errorString = "none";
         break;
      }
   }
    if (errorString != "none")
   {
            alert(intestazione + errorString);
            return false;
   }
   return true;
}
/*************************************************************************
 * Validates the form for World3 Job Area       *
 *************************************************************************/
function validateJobsPositions(){
   var intestazione = " ";
   var errorString = "";
if (typeof document.jobForm.jobPositionSelected.length == 'undefined'){
    if (!document.jobForm.jobPositionSelected.checked) {
          errorString =  "Scegli la posizione che ti interessa \n";
    }
   else{
      errorString = "none";
   }
}
else{
  for (i=0; i<document.jobForm.jobPositionSelected.length; i++){
     if (!document.jobForm.jobPositionSelected[i].checked) {
         if (errorString == "")
          errorString =  "Scegli la posizione che ti interessa \n";
      }
       //Option Button selected
      else {
         errorString = "none";
         break;
      }
   }
}
   if (errorString != "none"){
            alert(intestazione + errorString);
            return false;
   }
   else{
            return true;
   }
}

var jobItalyNation="106";

function goBack(){
   document.jobForm.back.value='true';
   document.jobForm.submit();
}
function valorizePersonalDataHiddenField(){
   	//alert('valorizePersonalDataHiddenField Called');
	document.jobForm.nationDescription.value = document.jobForm.idNation.options[document.jobForm.idNation.selectedIndex].text;
	document.jobForm.descProvince.value = document.jobForm.idProvince.options[document.jobForm.idProvince.selectedIndex].text;
	document.jobForm.descCivilStatus.value = document.jobForm.idCivilStatus.options[document.jobForm.idCivilStatus.selectedIndex].text;
	document.jobForm.descMilitaryPosition.value = document.jobForm.idPosition.options[document.jobForm.idPosition.selectedIndex].text;
	document.jobForm.descResidenceProvince.value = document.jobForm.idResidenceProvince.options[document.jobForm.idResidenceProvince.selectedIndex].text;
	document.jobForm.descResidenceNation.value = document.jobForm.idResidenceNation.options[document.jobForm.idResidenceNation.selectedIndex].text;
	document.jobForm.descHomeProvince.value = document.jobForm.idHomeProvince.options[document.jobForm.idHomeProvince.selectedIndex].text;
	document.jobForm.descHomeNation.value = document.jobForm.idHomeNation.options[document.jobForm.idHomeNation.selectedIndex].text;
	//alert('submit');
        //document.jobForm.submit();
}
function checkNations()	{
   //alert('jobItalyNation='+jobItalyNation+' sel='+document.jobForm.idNation.value);
	if (document.jobForm.idNation.value != jobItalyNation) {
           document.jobForm.idProvince.selectedIndex=0;
           document.jobForm.idProvince.disabled=true;
      	}
        else{
           document.jobForm.idProvince.disabled=false;
         }
         if (document.jobForm.idResidenceNation.value != jobItalyNation) {
           document.jobForm.idResidenceProvince.selectedIndex=0;
           document.jobForm.idResidenceProvince.disabled=true;
      	}
        else{
           document.jobForm.idResidenceProvince.disabled=false;
         }
         if (document.jobForm.idHomeNation.value != jobItalyNation) {
           document.jobForm.idHomeProvince.selectedIndex=0;
           document.jobForm.idHomeProvince.disabled=true;
      	}
        else{
           document.jobForm.idHomeProvince.disabled=false;
         }
}

function protectedCatEnabled(){
      var myf = document.jobForm;
      for (var i=0;i<myf.protectedCategory.length;i++){
      	if (myf.protectedCategory[i].checked==true){
        	var rVal = myf.protectedCategory[i].value;
                if (rVal == 'Y'){
                	myf.protectedCategoryNotes.disabled = false;
               	}
                else {
                	myf.protectedCategoryNotes.value = '';
               	        myf.protectedCategoryNotes.disabled = true;
               }
         }

      }
}

function militaryPositionDefault(){
      var myf = document.jobForm;
      for (var i=0;i<myf.gender.length;i++){
      	if (myf.gender[i].checked==true){

        	var rVal = myf.gender[i].value;
                if (rVal == 'F'){
                   document.jobForm.idPosition.selectedIndex=1;

               	}
         }

      }
}

function jobProfExpValorizeHiddenField(){
   	//alert('jobSchoolValorizeHiddenField Called');
	document.jobForm.descPresentProfStatus.value = document.jobForm.presentProfStatus.options[document.jobForm.presentProfStatus.selectedIndex].text;
	document.jobForm.descPreferredSite.value = document.jobForm.preferredSite.options[document.jobForm.preferredSite.selectedIndex].text;
}

function jobProfExpValidate(){
   //alert('jobProfExpValidate');
   var objform=document.jobForm;
   var errorString='';
   var errorMessage='';


   if (objform.presentProfStatus.options[objform.presentProfStatus.selectedIndex].value=="-1"){
   	errorString+=" - Esperienze professionali - Campo Stato attuale.\n";
      	errorMessage='I campi con l\'asterisco sono obbligatori, quindi necessari per proseguire nella compilazione del form.\n'
      	alert(errorMessage+errorString);
        return false;
   }
   if ((objform.privacyAgreement[0].checked==false) || (objform.privacyAgreement[1].checked==true)){
      errorMessage='Attenzione non hai autorizzato al trattamento dei dati ai sensi della Legge 675/96 e quindi i tuoi dati non possono essere inviati.'
   	alert(errorMessage+errorString);
            return false;
   }

  replaceAllEuro();

  return true;
}

function replaceAllEuro() {
  var objform=document.jobForm;
  var euroChar = '€';
  var euroDecode = 'EUR';
  objform.presentJobFirm.value = replaceEuroChar(objform.presentJobFirm.value,euroChar,euroDecode);
  objform.presentJobField.value = replaceEuroChar(objform.presentJobField.value,euroChar,euroDecode);
  objform.presentJobFunction.value = replaceEuroChar(objform.presentJobFunction.value,euroChar,euroDecode);
  objform.presentJobActivity.value = replaceEuroChar(objform.presentJobActivity.value,euroChar,euroDecode);
  objform.presentJobFixedIncome.value = replaceEuroChar(objform.presentJobFixedIncome.value,euroChar,euroDecode);
  objform.presentJobVariableIncome.value = replaceEuroChar(objform.presentJobVariableIncome.value,euroChar,euroDecode);
  objform.presentJobQualification.value = replaceEuroChar(objform.presentJobQualification.value,euroChar,euroDecode);
  objform.presentJobLevel.value = replaceEuroChar(objform.presentJobLevel.value,euroChar,euroDecode);
  objform.presentJobContract.value = replaceEuroChar(objform.presentJobContract.value,euroChar,euroDecode);

  objform.firstPastJobFirm.value = replaceEuroChar(objform.firstPastJobFirm.value,euroChar,euroDecode);
  objform.firstPastJobField.value = replaceEuroChar(objform.firstPastJobField.value,euroChar,euroDecode);
  objform.firstPastJobFunction.value = replaceEuroChar(objform.firstPastJobFunction.value,euroChar,euroDecode);
  objform.firstPastJobActivity.value = replaceEuroChar(objform.firstPastJobActivity.value,euroChar,euroDecode);
  objform.firstPastJobFixedIncome.value = replaceEuroChar(objform.firstPastJobFixedIncome.value,euroChar,euroDecode);
  objform.firstPastJobVariableIncome.value = replaceEuroChar(objform.firstPastJobVariableIncome.value,euroChar,euroDecode);
  objform.firstPastJobQualification.value = replaceEuroChar(objform.firstPastJobQualification.value,euroChar,euroDecode);
  objform.firstPastJobLevel.value = replaceEuroChar(objform.firstPastJobLevel.value,euroChar,euroDecode);
  objform.firstPastJobContract.value = replaceEuroChar(objform.firstPastJobContract.value,euroChar,euroDecode);

  objform.secondPastJobFirm.value = replaceEuroChar(objform.secondPastJobFirm.value,euroChar,euroDecode);
  objform.secondPastJobField.value = replaceEuroChar(objform.secondPastJobField.value,euroChar,euroDecode);
  objform.secondPastJobFunction.value = replaceEuroChar(objform.secondPastJobFunction.value,euroChar,euroDecode);
  objform.secondPastJobActivity.value = replaceEuroChar(objform.secondPastJobActivity.value,euroChar,euroDecode);
  objform.secondPastJobFixedIncome.value = replaceEuroChar(objform.secondPastJobFixedIncome.value,euroChar,euroDecode);
  objform.secondPastJobVariableIncome.value = replaceEuroChar(objform.secondPastJobVariableIncome.value,euroChar,euroDecode);
  objform.secondPastJobQualification.value = replaceEuroChar(objform.secondPastJobQualification.value,euroChar,euroDecode);
  objform.secondPastJobLevel.value = replaceEuroChar(objform.secondPastJobLevel.value,euroChar,euroDecode);
  objform.secondPastJobContract.value = replaceEuroChar(objform.secondPastJobContract.value,euroChar,euroDecode);

  objform.jobNotes.value = replaceEuroChar(objform.jobNotes.value,euroChar,euroDecode);
}

function replaceEuroChar (stringaVecchia, stringaDaSostituire, stringaNuova) {
 re = new RegExp();
 re.compile(stringaDaSostituire, "g");
 return stringaVecchia.replace(re, stringaNuova);
}

function invia(){
   if(jobProfExpValidate()){
   	jobProfExpValorizeHiddenField();
        //alert('submit');
        document.jobForm.submit();
   }
}

function checkLen(field){
  if(field.value.length>255){
     var errorMessage='';
     alert('La descrizione deve essere al massimo lunga 255 caratteri.');
     myfield.value = myfield.value.substring(0,255);
     myfield.focus();
  }
}

function jobSchoolValorizeHiddenField(){
   	//alert('jobSchoolValorizeHiddenField Called');
	document.jobForm.descDiploma.value = document.jobForm.diploma.options[document.jobForm.diploma.selectedIndex].text;
	document.jobForm.descBachelor.value = document.jobForm.bachelor.options[document.jobForm.bachelor.selectedIndex].text;
	document.jobForm.descOtherExperience.value = document.jobForm.otherExperience.options[document.jobForm.otherExperience.selectedIndex].text;
}

function enableLaude(){
       var vote = document.jobForm.bachelorVote.value;
       var vmax = document.jobForm.bachelorVoteMax.options[document.jobForm.bachelorVoteMax.selectedIndex].text;

       if (vote == vmax)
       { document.jobForm.bachelorLaude.disabled = false;
       } else {
        document.jobForm.bachelorLaude.checked = false;
        document.jobForm.bachelorLaude.disabled = true;
        }

}
function goForward(){
   //alert('goForward step='+document.jobForm.jobStep.value);

   if(document.jobForm.jobStep.value=='1' ){
      if(validateJobsAreas()){
           document.jobForm.submit();
      }
   }
   else if(document.jobForm.jobStep.value=='2' ){
      if(validateJobsPositions()){
           document.jobForm.submit();
      }
   }
   else if(document.jobForm.jobStep.value=='3' ){
      if(validateJobPersonalDataFields()){
           valorizePersonalDataHiddenField();
           document.jobForm.submit();
      }
   }
   else if(document.jobForm.jobStep.value=='4' ){
      if(validateJobSchoolFields()){
           jobSchoolValorizeHiddenField();
           document.jobForm.submit();
        }
   }
}

/*************************************************************
 * Validate job Form
 ************************************************************/
 function validateJobSchoolFields(){
  var errorString="";
  var errorString2="";
  var intestazione="I campi con l'asterisco sono obbligatori, quindi necessari per proseguire nella compilazione del form:\n";
  var objform = document.jobForm;
   if (objform.diploma.options[objform.diploma.selectedIndex].value=="-1")
			errorString+=" - DIPLOMA\n";

   objform.diplomaVote.value = trimSpace(objform.diplomaVote.value);
    if (objform.diplomaVote.value=="")
    {
    	errorString+=" - VOTO DIPLOMA\n";
    }

    if (objform.diplomaVoteMax.options[objform.diplomaVoteMax.selectedIndex].value=="-1")
			errorString+=" - MASSIMO VOTO DIPLOMA\n";
    //#Defect 35091
    if (objform.diploma.options[objform.diploma.selectedIndex].value != "-1") {
       if (objform.diplomaVote.value <="0")
         errorString2+=" - Il campo VOTO DIPLOMA deve essere maggiore di 0 \n";
    }
    if (objform.bachelor.options[objform.bachelor.selectedIndex].value != "-1") {
       if (objform.bachelorVote.value <="0")
         errorString2+=" - Il campo VOTO LAUREA deve essere maggiore di 0 \n";
    }
    //End Defect # 35091

    if (errorString!="")
    	alert(intestazione+errorString);
    else if (errorString2!="")
        alert(errorString2);
    else
    	return true;

    return false;
 }

 function validateJobPersonalDataFields(){

    var errorString="";
    var alertString="";
    var intestazione="I campi con l'asterisco sono obbligatori, quindi necessari per proseguire nella compilazione del form:\n";
    var objform = document.jobForm;

    var jobItalyNation="106";

    /************Dati anagrafici**********/
    objform.firstName.value = trimSpace(objform.firstName.value);
    if (objform.firstName.value=="")
    {
    	errorString+=" - NOME\n";
    }
    objform.lastName.value = trimSpace(objform.lastName.value);
    if (objform.lastName.value==""){
    	errorString+=" - COGNOME\n";
    }

    if (objform.idNation.options[objform.idNation.selectedIndex].value=="-1")
			errorString+=" - NAZIONALITA'\n";

    if (objform.birthDay.options[objform.birthDay.selectedIndex].value=="-1")
            errorString+=" - GIORNO DI NASCITA\n";
    if (objform.birthMonth.options[objform.birthMonth.selectedIndex].value=="-1")
            errorString+=" - MESE DI NASCITA\n";
    if (objform.birthMonth.options[objform.birthMonth.selectedIndex].value=="-1")
            errorString+=" - ANNO DI NASCITA\n";

   objform.birthPlace.value = trimSpace(objform.birthPlace.value);
   if (objform.birthPlace.value=="")
			errorString+=" - LUOGO DI NASCITA\n";

   if(objform.idNation.options[objform.idNation.selectedIndex].value==jobItalyNation){
   	if (objform.idProvince.options[objform.idProvince.selectedIndex].value=="-1")
			errorString+=" - PROVINCIA DI NASCITA\n";
   }

   if (objform.idCivilStatus.options[objform.idCivilStatus.selectedIndex].value=="-1")
			errorString+=" - STATO CIVILE\n";

   if (objform.idPosition.options[objform.idPosition.selectedIndex].value=="-1")
			errorString+=" - POSIZIONE MILITARE\n";
   //residenza
   objform.residenceAddress.value = trimSpace(objform.residenceAddress.value);
   if (objform.residenceAddress.value=="")
			errorString+=" - RESIDENZA - VIA/PIAZZA\n";

  objform.residenceCivicNumber.value = trimSpace(objform.residenceCivicNumber.value);
  if (objform.residenceCivicNumber.value=="")
         		errorString+=" - RESIDENZA - NUMERO CIVICO\n";

   objform.residenceCity.value = trimSpace(objform.residenceCity.value);
   if (objform.residenceCity.value=="")
			errorString+=" - RESIDENZA - CITTA'\n";

   if (objform.idResidenceNation.options[objform.idResidenceNation.selectedIndex].value=="-1")
			errorString+=" - RESIDENZA - NAZIONE\n";

   if(objform.idResidenceNation.options[objform.idResidenceNation.selectedIndex].value==jobItalyNation){
   	if (objform.idResidenceProvince.options[objform.idResidenceProvince.selectedIndex].value=="-1")
			errorString+=" - RESIDENZA - PROVINCIA\n";


   	objform.residenceCap.value = trimSpace(objform.residenceCap.value);
   	if (objform.residenceCap.value=="")
			errorString+=" - CAP DOMICILIO\n";
   }

   objform.email.value = trimSpace(objform.email.value);
   if (objform.email.value=="")
		errorString+=" - E-MAIL\n";

   if (errorString!="") {
         alert(intestazione+errorString);
         return false;
   }

   var check = emailCheck(objform.email.value);
   if (!check){
   	errorString +=  "-  Attenzione, l'indirizzo e-mail indicato non è valido. \n";
   }
   if (errorString!="") {
         alert(errorString);
         return false;
   }

   return true;
}


/*************************************************************************
 * Validates the form Cards       *
 *************************************************************************/
function validateSendCardForm(operation)
{
   	//This sets "whereIam" in the Action Form which represents the current page
    	if (operation=="Invia")
         	document.sendCardForm.whereIAm.value = "cardsMain";
   	if (operation=="Invia1")
            	document.sendCardForm.whereIAm.value = "previewFrontCardMain";
         if (operation=="Invia2")
         	document.sendCardForm.whereIAm.value = "previewBackCardMain";
         if (operation=="Anteprima")
         	document.sendCardForm.whereIAm.value = "cardsMain";
         if (operation=="Anteprima1")
         	document.sendCardForm.whereIAm.value = "previewBackCardMain";

         //This sets "toDo" in the Action Form which represents the forward page
	if (operation=="Anteprima" || operation=="Anteprima1")
	    document.sendCardForm.toDo.value = "previewFrontCardMain";
         if (operation=="Indietro")
	    document.sendCardForm.toDo.value = "cardsMain";
	if (operation=="Invia" || operation=="Invia1" || operation=="Invia2")
	    document.sendCardForm.toDo.value = "cardsResultMain";
         if (operation=="Retro")
             document.sendCardForm.toDo.value = "previewBackCardMain";

         //These controls validate the form in CardsHome.jsp
         if (operation =="Anteprima" || operation =="Invia") {
         	var intestazione1 = "Prego voler compilare i seguenti campi obbligatori: \n";
         	var intestazione2 = "Attenzione: \n";
         	var errorString1 = "";
         	var errorString2 = "";

		// Checks sendername
		document.sendCardForm.nameSender.value = trimSpace(document.sendCardForm.nameSender.value);
		if (document.sendCardForm.nameSender.value=="")
			errorString1 +=  "- Nome Mittente \n";

        		// Checks sendermail
		document.sendCardForm.emailSender.value = trimSpace(document.sendCardForm.emailSender.value);
		if (document.sendCardForm.emailSender.value=="")
			errorString1 +=  "- E-Mail Mittente \n";
		else
	   	{
               		 var check = emailCheck(document.sendCardForm.emailSender.value);
                            if (!check)
	            		errorString2 +=  "-  L'indirizzo e-mail del mittente non è corretto o non è valido \n";
           	}

		// Checks receivername
		document.sendCardForm.nameReceiver.value = trimSpace(document.sendCardForm.nameReceiver.value);
		if (document.sendCardForm.nameReceiver.value=="")
			errorString1 +=  "- Nome Destinatario \n";

        		// Checks receivermail
		document.sendCardForm.emailReceiver.value = trimSpace(document.sendCardForm.emailReceiver.value);
		if (document.sendCardForm.emailReceiver.value=="")
			errorString1 +=  "- E-Mail Destinatario \n";
        		else
	   	{
                		var check = emailCheck(document.sendCardForm.emailReceiver.value);
	        	if (!check)
	            errorString2 +=  "-  L'indirizzo e-mail del destinatario non è corretto o non è valido \n";
           	}

		// Checks bodycard
		if (document.sendCardForm.bodyCard.value.length > 4000)
			errorString2 +=  "- Corpo del messaggio troppo lungo";

		if (errorString1 != "")
		{
			alert(intestazione1 + errorString1);
		}
		else if (errorString2 != "")
		{
			alert(intestazione2 + errorString2);
		}
		else
		{
			document.sendCardForm.submit();
		}
      }
      else  if (operation == "Cancella"){
            document.sendCardForm.nameSender.value="";
            document.sendCardForm.emailSender.value="";
            document.sendCardForm.nameReceiver.value="";
            document.sendCardForm.emailReceiver.value="";
            document.sendCardForm.bodyCard.value="";
            document.sendCardForm.subjectCard.value="";
      }
      else
      document.sendCardForm.submit();
}

function emailCheck(email)
{
 if ((navigator.appName.indexOf("Netscape")>-1) && (parseInt(navigator.appVersion) <= 4) )
 {
  var emailStr = email;
     var emailPat = /^([\!\#\$\%\&\'\*\+\-\/0-9\=\?A-Z\^\_\`a-z\{\|\}\~\.])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;

     var matchArray = emailStr.match(emailPat);
     if (matchArray == null) {
         return false;
     }

     return true;
 }
 return IsMailAddress(email);
}

function IsMailAddress(email)
{

    var emailStr = email;
    // checks if the e-mail address is valid
    var emailPat = /^([\!\#\$\%\&\'\*\+\-\/0-9\=\?A-Z\^\_\`a-z\{\|\}\~])+(([\.][\!\#\$\%\&\'\*\+\-\/0-9\=\?A-Z\^\_\`a-z\{\|\}\~]+)?)*@([\!\#\$\%\&\'\*\+\-\/0-9\=\?A-Z\^\_\`a-z\{\|\}\~])+(([\.][\!\#\$\%\&\'\*\+\-\/0-9\=\?A-Z\^\_\`a-z\{\|\}\~]{2,})*)$/;

    // var emailPat = /^([^\(\)\<\>\@\\[\],\;\:\\\.])+(([\.][^\(\)\<\>\@\\[\],\;\:\\\.]+)?)*@([^\(\)\<\>\@\\[\],\;\:\\\.])+(([\.][^\(\)\<\>\@\\[\],\;\:\\\.]+)?)$/;
    var matchArray = emailStr.match(emailPat);
    if (matchArray == null) {
        return false;
    }

    return true;
}

function isString(sText)
{
	if (sText.match("^[A-Za-z' \?\?\?\?\?]+$") == null)
	return false;
else
	return true;
}

function SetChar(textField) {
	if(textField.value.length > 4000){
		textField.value= textField.value.substring(0,4000);
		alert("Lunghezza massima raggiunta!")
		textField.blur();
	}
}

/*****************************************************************************
* Checks if the str is a valid phone number
*****************************************************************************/
function isValidPhoneNumber(str) {
	var pattern = "0123456789( )/-+";
	var i = 0;

	do {
		var pos = 0;
		for (var j=0; j<pattern.length; j++)
		if (str.charAt(i)==pattern.charAt(j)) {
			pos = 1;
			break;
		}
		i++;
	} while (pos==1 && i<str.length)
	if (pos==0)
	return "puo' contenere solo numeri o i caratteri ( )/-+ \n";
	if(str.length <6 || str.length >20)
	return "lunghezza non compresa tra 6 e 20 caratteri \n";
else
	return null;
}

/*****************************************************************************
* Checks if the code is a valid Vat Code (Partita IVA)
* It must be 11 chars long and must be a number.
*****************************************************************************/
function isValidVatCode(aVatCode) {
	if (!aVatCode || aVatCode.length != 11)
	return false;

	return isNumber(aVatCode);
}


/*****************************************************************************
* Checks if aName is a valid name (fisrtName or lastName)
*****************************************************************************/
function isValidName(aName) {
	var errorString;

	if (!isString(aName))
	{
		errorString = "puo' contenere solo caratteri alfabetici \n";
	}
else if(aName.length<2)
{
	errorString = "deve essere lungo almeno 2 caratteri \n";
}

return errorString;
}


/*****************************************************************************
* Checks if the value of the "comune" field of form is right.
*****************************************************************************/
function isRightComune(sText)
{

	var validChars=" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789.'";
	var isString=true;
	var character='';


	for (i=0;i<sText.length && isString==true;i++)
	{
		character=sText.charAt(i);
		if (validChars.indexOf(character)==-1)
		{
			isString=false;
		}
	}

	return isString;

}

/*****************************************************************************
* Controls if the value of one field of form is number.
* Returns "false" if contains any letter, otherwise"true"
*****************************************************************************/
function isNumber(sText)
{
	var  validChars="0123456789";
	var  isNumber=true;
	var  character='';

	for (i=0; i<sText.length && isNumber==true; i++)
	{
		character=sText.charAt(i);
		if (validChars.indexOf(character)==-1)
		{
			isNumber=false;
		}
	}

	return isNumber;
}

/*****************************************************************************
 * Checks if the value of the "username" field of form isright.
 *
 *****************************************************************************/
function isValidUsername(sText)
{

	if (isNumber(sText))
        {
          return false;
        }
	else if(sText.length<6)
	{
		isValid = false;
	}
   	else {

         var validChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
         var character ;
         var  isValid = true;


          for (i = 0; i < sText.length && isValid == true; i++)
          {
            character = sText.charAt(i);
            if (validChars.indexOf(character) == -1)
            {
              isValid = false;
            }
          }
          return isValid;
        }
}


/*****************************************************************************
 * Checks if the value of the "domanda" or "risposta" fields is right.
 *
 *****************************************************************************/
function isValidDomandaRisposta(sText)
{
	 var notValidChars = "0123456789";
         var character ;
         var  isValid = true;

	 for (i = 0; i < sText.length && isValid == true; i++)
         {
            character = sText.charAt(i);
            if (notValidChars.indexOf(character) != -1)
            {
              isValid = false;
            }
          }
          return isValid;

}

/*****************************************************
// Checks if password has valid format:
// At least 6 chhars long
// at least one number
// at least one alpha char
******************************************************/
function isValidPassword(sText)
{
var numberFound=0;


if(sText.length <6)
{
	return "- password e' piu' corta di 6 caratteri";
}

if(sText.length > 30)
{
	return "- password e' piu' lunga di 30 caratteri";
}

for (i=0; i<sText.length; i++)
{
  character=sText.charAt(i);

  if ((sText.charCodeAt(i) > 47 && sText.charCodeAt(i) < 58) )
  {
  		numberFound +=1;
  }
  else
  if(!((sText.charCodeAt(i) > 64 && sText.charCodeAt(i) < 91) ||
  		(sText.charCodeAt(i) > 96 && sText.charCodeAt(i) < 123)))
  {
  	return ("- password puo' contenere solo lettere e numeri");
  }
}

if(numberFound == 0)
{
	return ("- password deve contenere almeno un numero");
}
if(numberFound == sText.length)
{
	return ("- password non puo' contenere solo numeri");
}
return null;
}

/********************************************
Set combo.text value in hidden field in same form
********************************************/
      function setComboDesc(form, comboName, hiddenName){

       var selectedOption = form.elements[comboName].options[form.elements[comboName].selectedIndex];
       form.elements[hiddenName].value=selectedOption.text;

    }


 /*************************************************************************
	 * Validates the registration step 1 page.
	 *
	 *************************************************************************/
	function validateRegistration_step1()
	{

		/************Dati anagrafici**********/

		var errorString="";
		var alertString="";
		var intestazione="Prego voler compilare i seguenti campi obbligatori :\n";

		var objform=document.userProfileForm;

		objform.firstName.value = trimSpace(objform.firstName.value);
		if (objform.firstName.value=="")
		{
			errorString+=" - NOME\n";
		}
		else
		{
			if (!isString(objform.firstName.value))
			{
				alertString += " - Il formato del nome non e' corretto\n"
			}
			if(objform.firstName.value.length<2)
			{
				alertString +=" - La lunghezza del nome non può essere minore di 2\n"
			}
		}

		objform.lastName.value = trimSpace(objform.lastName.value);
		if (objform.lastName.value=="")
		{
			errorString+=" - COGNOME\n";
		}
		else
		{
			if (!isString(objform.lastName.value))
			{
				alertString += " - Il formato del cognome non e' corretto\n"
			}
			if(objform.lastName.value.length<2)
			{
				alertString +=" - La lunghezza del cognome non può essere minore di 2\n"
			}
		}



		if (objform.birthDay.options[objform.birthDay.selectedIndex].value=="-1")
			errorString+=" - GIORNO DI NASCITA\n";
		if (objform.birthMonth.options[objform.birthMonth.selectedIndex].value=="-1")
			errorString+=" - MESE DI NASCITA\n";
		if (objform.birthMonth.options[objform.birthMonth.selectedIndex].value=="-1")
			errorString+=" - ANNO DI NASCITA\n";
		if (objform.gender.value=="-1")
			errorString+=" - SESSO\n";

	    	objform.city.value = trimSpace(objform.city.value);
		if (objform.city.value=="")
			errorString+=" - COMUNE DOMICILIO\n";
		if (objform.provinceId.options[objform.provinceId.selectedIndex].value=="-1")
			errorString+=" - PROVINCIA DOMICILIO\n";
		if (objform.professionId.options[objform.professionId.selectedIndex].value=="-1")
			errorString+=" - PROFESSIONE\n";
		if (objform.schoolDegreeId.options[objform.schoolDegreeId.selectedIndex].value=="-1")
			errorString+=" - TITOLO DI STUDIO\n";

		objform.cap.value = trimSpace(objform.cap.value);
		if (objform.cap.value=="")
			errorString+=" - CAP DOMICILIO\n";
		 else
		{
			if (isNumber(objform.cap.value)==false)
				alertString+=" - Il formato del CAP deve essere numerico.\n";
			 else
			if (objform.cap.value.length!=5)
				alertString+=" - Il CAP non e' composto da 5 cifre.\n";
		}

		if (errorString!="")
		{
			alert(intestazione+errorString);
		}
		 else if (alertString!="")
		{
			alert(alertString);
		}
		 else
		{
			objform.submit();
		}

	}



	/*************************************************************************
 * Validates the registration step 2 page.
 *
 *************************************************************************/
function validateRegistration_step2()
{

	/************Email*****************/
	var errorMsg="";
	var alertMsg="";

	var objform=document.userProfileForm;

	objform.emailAddress.value = trimSpace(objform.emailAddress.value);
	if (objform.emailAddress.value=="")
	{
		errorMsg+=" - INDIRIZZO E-MAIL\n";
	}
	else
	{
		if (!emailCheck(objform.emailAddress.value))
		{
			alertMsg += "- indirizzo email errato\n"

		}
		if (objform.emailAddress.value!=objform.emailAddress2.value)
		{
			alertMsg +="- indirizzo email non è stato confermato correttamente\n";

		}

	}

	objform.emailAddress2.value = trimSpace(objform.emailAddress2.value);
	if (objform.emailAddress2.value=="")
	{
		errorMsg+=" - CONFERMA INDIRIZZO E-MAIL\n";
	}

	objform.username.value = trimSpace(objform.username.value);
	if (objform.username.value=="")
	{
		errorMsg+=" - USERNAME\n";
	}
	else
	{

		if (!isValidUsername(objform.username.value)){
			alertMsg +="- formato username errato o lunghezza minore di 6 caratteri\n";
		}

	}


	objform.password.value = trimSpace(objform.password.value);
	if (objform.password.value=="")
	{
		errorMsg+=" - PASSWORD\n";
	}
	objform.password2.value = trimSpace(objform.password2.value);
	if (objform.password2.value=="")		errorMsg+=" - CONFERMA PASSWORD\n";

	objform.recoveryQuestion.value = trimSpace(objform.recoveryQuestion.value);
	if (objform.recoveryQuestion.value=="")
	{
		errorMsg+=" - DOMANDA SEGRETA\n";
	}
	else
	{
		if (objform.recoveryQuestion.value.length < 2)
		{
			alertMsg += "- lunghezza della domanda minore di 2 caratteri\n";
		}
		else
		{
			if (!isValidDomandaRisposta(objform.recoveryQuestion.value))
			{
				alertMsg += "- domanda non può contenere numeri\n";
			}
		}
	}

	objform.recoveryAnswer.value = trimSpace(objform.recoveryAnswer.value);
	if (objform.recoveryAnswer.value=="")
	{
		errorMsg+=" - RISPOSTA SEGRETA\n";
	}
	else
	{
		if (objform.recoveryAnswer.value.length < 2)
		{
			alertMsg += "- lunghezza della risposta minore di 2 caratteri\n";
		}
		else
		{
			if (!isValidDomandaRisposta(objform.recoveryAnswer.value))
			{
				alertMsg += "- risposta non può contenere numeri\n";
			}
		}
	}


	if (errorMsg=="" && objform.password.value!=objform.password2.value)
	{
		alertMsg +="- il campo password e il campo conferma password devono essere uguali\n";
	}
	if(errorMsg=="" )
	{
	var pwdCheck = isValidPassword(objform.password.value);
	if(pwdCheck != null)
		alertMsg+= pwdCheck + "\n";
	}

	if (errorMsg!="")
	{
		alert("Prego voler inserire i seguenti campi obbligatori :\n"+errorMsg);
	}
	else if(alertMsg!="")
	{
		alert(alertMsg);
	}
	 else
	{
		objform.submit();
	}

}



/*************************************************************************
 * Validates the registration step 3 page.
 *
 *************************************************************************/
function validateRegistration_step3()
{

	var errorMsg="";
	var objform=document.userProfileForm;

	if ((objform.privacyAgreement[0].checked==false) || (objform.privacyAgreement[1].checked==true))
	{

		errorMsg+=" - autorizzare il trattamento dei dati personali\n";
	}


	if ((objform.transferAgreement[0].checked==false) || (objform.transferAgreement[1].checked==true))
	{

		errorMsg+=" - autorizzare il trasferimento dei dati personali a società estere del gruppo\n";
	}

	if ((objform.contractAgreement[0].checked==false) || (objform.contractAgreement[1].checked==true))
	{
		errorMsg+=" - accettare integralmente il contenuto delle condizioni";
	}


	if (errorMsg=="")
	{
		objform.submit();
	}
	else {

		alert("Per accedere al sito e' necessario :\n"+errorMsg);

	}

}

/*****************************************************************************
 * Checks if username and password input text of registration confirmation   *
 * form are empty. Returns "false" if are empty, otherwise "true" and cause submit *
 *****************************************************************************/
function validateConfirmRegistration()
{

	var errMsg = "";
	var missed = 0;
	var objform=document.userProfileForm;

	if (objform.username.value=="" || objform.username.value.length==0)
		missed = missed + 1;
	if (objform.password.value=="" || objform.password.value.length==0)
		missed = missed + 2;

	if (missed==0)
		return objform.submit();

	if (missed==1)
	{
		errMsg = "L'inserimento dello username è obbligatorio";
	}

	if (missed==2)
	{
		errMsg = "L'inserimento della password è obbligatorio";
	}

	if (missed==3)
	{
		errMsg = "L'inserimento dello username e della password è obbligatorio";
	}

	alert(errMsg);
	return false;

}


/*************************************************************************
 * Validates the "changeEmail" page controlls. Controls if the fields of form*
 * are empty and then if their values are equal.Returns "false" if one of*
 * the fields is empty or if their values are not equal.Otherwise calls  *
 * the "submit" method                                                   *
 *************************************************************************/
function validateChangeEmail()
{
	var objform=document.userProfileForm;

	objform.emailAddress.value = trimSpace(objform.emailAddress.value);
	objform.emailAddress2.value = trimSpace(objform.emailAddress2.value);

	if (isEmpty('Indirizzo e-mail',objform.emailAddress.value))
	{
		objform.emailAddress.focus();

	}

	else if (!emailCheck(objform.emailAddress.value))
	{
			window.alert ("Formato dell'indirizzo e-mail errato");
			objform.emailAddress.focus();
	}

	else if ( objform.emailAddress.value != objform.emailAddress2.value ){
		window.alert("I campi Indirizzo e-mail e Conferma Indirizzo e-mail devono essere uguali");
		objform.emailAddress2.focus();
	}

	else
	{
		objform.submit();
	}
}

/*****************************************************************************
 * Checks if one field of the form is empty.
 * Returns "false" if is empty, otherwise "true"
 *****************************************************************************/
function isEmpty(nameField,valueField)
{
	if (valueField.length<1){
		window.alert(nameField+" vuoto");
		return true;
	}
	 else return false;
}


/*************************************************************************
 * Validates the "changePwd" page controlles. Checks ls if the fields of form *
 * are empty                                                             *
 *************************************************************************/
function validateChangePassword()
{
	var errorString = "";
	var errorString2 = "";
	var intestazione1 = "Prego voler compilare i seguenti campi obbligatori: \n";

	var objform=document.userProfileForm;

	objform.oldPassword.value = trimSpace(objform.oldPassword.value);
	if(objform.oldPassword.value==""){
		errorString += " - VECCHIA PASSWORD\n"	;
	}
	objform.password.value = trimSpace(objform.password.value);
	if(objform.password.value==""){
		errorString += " - NUOVA PASSWORD\n"	;
	}
	objform.password2.value = trimSpace(objform.password2.value);
	if(objform.password2.value==""){
		errorString += " - CONFERMA NUOVA PASSWORD\n"	;
	}


	if ( objform.password.value != objform.password2.value )
	{
		errorString2 += "- I campi password e conferma password devono essere uguali\n";


	}

	var pwdCheck = isValidPassword(objform.password.value);
	if(pwdCheck != null)
		errorString2+= pwdCheck + "\n";


	objform.recoveryQuestion.value = trimSpace(objform.recoveryQuestion.value);
	if(objform.recoveryQuestion.value==""){
		errorString += " - DOMANDA SEGRETA\n";
	}
	objform.recoveryAnswer.value = trimSpace(objform.recoveryAnswer.value);
	if(objform.recoveryAnswer.value==""){
		errorString += " - RISPOSTA SEGRETA\n"	;
	}
//--------------------------------
	if(objform.recoveryQuestion.value.length < 3)
	{
		errorString2 += "- Il campo domanda deve essere di almeno 3 caratteri\n";
	}

	if(objform.recoveryAnswer.value.length < 3)
	{
		errorString2 += "- Il campo risposta deve essere di almeno 3 caratteri\n";
	}

	if(objform.recoveryQuestion.value.length > 200)
	{
		errorString2 += "- Il campo domanda non puo' eccedere i 200 caratteri\n";
	}

	if(objform.recoveryAnswer.value.length > 200)
	{
		errorString2 += "- Il campo risposta non puo' eccedere i 200 caratteri\n";
	}

//--------------------------------

	if(errorString!="")
	{
		alert(intestazione1 + errorString);
	}
	else if(errorString2!="")
	{
		alert(errorString2);
	}
	else
	{
		objform.submit();
	}

}


/*************************************************************************
* Validates the "forgottenUsernamePwd" page. Controls if at least one field of   *
* form is not empty.Returns "false" if all fields are empty.Otherwise calls   *
* the "submit" method                                                    *
*************************************************************************/
function validateRecoveryPrompt()
{

	var objform=document.userProfileForm;

	objform.username.value = trimSpace(objform.username.value);
	objform.emailAddress.value =    trimSpace(objform.emailAddress.value);

	if ((objform.username.value.length < 1) && (objform.emailAddress.value.length < 1)){
		window.alert("Username o Indirizzo e-mail deve essere riempito");
		objform.username.focus();

	}
	else
	if (objform.emailAddress.value.length > 0 && (!emailCheck(objform.emailAddress.value)))
	{
			window.alert ("Formato dell'indirizzo e-mail errato");
			objform.emailAddress.focus();
	}

	else
	{
		objform.submit();
	}
}

/*************************************************************************
* Validates the "initMigration" page. Controls if all fields of          *
* form is not empty.Returns "false" if all fields are empty.Otherwise calls   *
* the "submit" method                                                    *
*************************************************************************/
function validateMigrationPrompt()
{
	var objform=document.userProfileForm;

	objform.username.value = trimSpace(objform.username.value);
	objform.emailAddress.value = trimSpace(objform.emailAddress.value);

	if ((objform.username.value.length < 1) || (objform.emailAddress.value.length < 1)){
		window.alert("Username e Indirizzo e-mail devono essere compilati");
		objform.username.focus();
	}
	else if (objform.emailAddress.value.length > 0 && (!emailCheck(objform.emailAddress.value)))
	{
			window.alert ("Formato dell'indirizzo e-mail errato");
			objform.emailAddress.focus();
	}
	else
	{
		objform.submit();
	}
}
/*************************************************************************
 * Validates the "forgottenPwdStep2" page. Controls if the only field of  *
 * form is empty.Returns "false" if this field is empty.Otherwise calls   *
 * the "submit" method                                                    *
 *************************************************************************/
function validateQuestion()
{
	var objform=document.userProfileForm;

	if (isEmpty('Campo risposta',objform.recoveryAnswer.value))
	{
		objform.recoveryAnswer.focus();

	}
	else
	{
		objform.submit();
	}

}

/*************************************************************************
 * Validates the "editExternalProfile.jsp" page. Controls if fields of  *
 * form are empty.Returns "false" if requested field are empty.Otherwise calls   *
 * the "submit" method                                                    *
 *************************************************************************/
function validateExternalProfile()
{
	var objform=document.userProfileForm;
	if (!(typeof objform.msisdn == 'undefined') && isEmpty('Numero di telefono',objform.msisdn.value))
	{
		objform.msisdn.focus();

	}
        else if (!(typeof objform.selfCarePwd == 'undefined') && isEmpty('Password area clienti',objform.selfCarePwd.value))
	{
		objform.selfCarePwd.focus();

	}
	else
	{
		objform.submit();
	}

}
/*************************************************************************
 * Validates the search in 133risponde                                   *
 *************************************************************************/
function validate133Search()
{
	var errorMsg="";
	var alertMsg="";

	if(document.search133Form.queryString.value=="")
		errorMsg+=" - PAROLE CHIAVE \n";
	if (errorMsg!="")
		alert("Prego voler inserire i seguenti campi obbligatori:\n"+errorMsg);
	else if(alertMsg!="")
		alert(alertMsg);
	else
		document.search133Form.submit();
}

/*************************************************************************
 * Trim spaces
 *************************************************************************/
function spaceCanc(passedVal)
{
    var i, j;

    for(i=0; i<passedVal.length; i++ )
    {
         if (passedVal.charAt(i)!=" ")
              break;
    }

    for(j=passedVal.length-1; j>=0; j-- )
    {
         if (passedVal.charAt(j)!=" ")
              break;
    }

    if (i > j)
         passedVal = "";
    else
         passedVal = passedVal.substring(i, j+1);

    return(passedVal);
}
/*************************************************************************
 * Validates the Generic Search
 *************************************************************************/
function validateSearch()
{
	document.searchForm.queryString.value = spaceCanc(document.searchForm.queryString.value);

	if (document.searchForm.queryString.value.length<1){
		window.alert("Prego voler inserire i seguenti campi obbligatori:\n\n"+"- PAROLA CHIAVE");
		document.searchForm.queryString.focus();
	}

	 else document.searchForm.submit();
}
/*************************************************************************
 * Set search parameters to perform pagging.
 *************************************************************************/
function setSearch(querystring, pn)
{
	document.searchForm.queryString.value = querystring;
	document.searchForm.pageNumber.value = pn;
	document.searchForm.submit();
}

/*************************************************************************
* Validates the Business3 contact page.                                 *
*************************************************************************/
function validateBusinessInfoRequest()
{
	var errorMsg = "";
	var alertMsg = "";

	document.contactForm.firstName.value = trimSpace(document.contactForm.firstName.value);
	if (document.contactForm.firstName.value=="")
	{
		errorMsg += " - Nome\n";
	}
else
	{
		if(!isString(document.contactForm.firstName.value))
		{
			alertMsg += " - formato del nome non e' corretto\n";
		}
		if(document.contactForm.firstName.value.length<2)
		{
			alertMsg +=" - lunghezza del nome non puo' essere minore di 2\n";
		}
	}

	document.contactForm.lastName.value = trimSpace(document.contactForm.lastName.value);
	if (document.contactForm.lastName.value=="")
	{
		errorMsg += " - Cognome\n";
	}
else
	{
		if(!isString(document.contactForm.lastName.value))
		{
			alertMsg += " - formato del cognome non e' corretto\n";
		}
		if(document.contactForm.lastName.value.length<2)
		{
			alertMsg +=" - lunghezza del cognome non puo' essere minore di 2\n";
		}
	}

	document.contactForm.role.value = trimSpace(document.contactForm.role.value);
	if (document.contactForm.role.value=="")
	{
		errorMsg += " - Ruolo Aziendale\n";
	}
else
	{
		if(!isString(document.contactForm.role.value))
		{
			alertMsg += " - formato del ruolo aziendale non e' corretto\n";
		}
		if(document.contactForm.role.value.length<2)
		{
			alertMsg +=" - lunghezza del ruolo aziendale non puo' essere minore di 2\n";
		}
	}

	document.contactForm.companyName.value = trimSpace(document.contactForm.companyName.value);
	if (document.contactForm.companyName.value=="")
	{
		errorMsg += " - Ragione Sociale\n";
	}
else
	{
		if(!isString(document.contactForm.companyName.value))
		{
			alertMsg += " - formato della ragione sociale non e' corretto\n";
		}
		if(document.contactForm.companyName.value.length<2)
		{
			alertMsg +=" - lunghezza della ragione sociale non puo' essere minore di 2\n";
		}
	}

	if (document.contactForm.mailSubject.selectedIndex <= 0)
	errorMsg += " - Oggetto del messaggio\n";


	document.contactForm.mailBody.value = trimSpace(document.contactForm.mailBody.value);
	if (document.contactForm.mailBody.value=="")
	{
		errorMsg += " - Testo e-mail\n";
	}
else
	{
		if(document.contactForm.mailBody.value.length<2)
		{
			alertMsg +=" - lunghezza del testo della mail non puo' essere minore di 2\n";
		}
	}

	document.contactForm.mailFrom.value = trimSpace(document.contactForm.mailFrom.value);
	if (document.contactForm.mailFrom.value=="")
	{
		errorMsg += " - Indirizzo e-mail del mittente\n";
	}
else
	{
		if  (!emailCheck(document.contactForm.mailFrom.value))
		{
			alertMsg += " - L'indirizzo di posta elettronica del mittente non ha un formato corretto \n";
		}
	}

	if (errorMsg!="")
	{
		alert("Per procedere e' necessario specificare le seguenti informazioni :\n" + errorMsg);
	}
else if(alertMsg !="")
{
	alert("Prego voler controllare i seguenti campi: \n"+ alertMsg);
}
else
	{
		document.contactForm.submit();
	}
}

/*************************************************************************
* Validates the Business3 Commercial contact page.                      *
*************************************************************************/
function validateBusinessCommercialVisit()
{
	var errorString = "";
	var errorString2 = "";
	var intestazione1 = "Prego voler compilare i seguenti campi obbligatori : \n";
	var intestazione2 = "Prego voler controllare il formato dei seguenti campi : \n";
	var intestazione3 = "Prego voler inserire almeno uno dei seguenti campi : \n- E-MAIL\n- NUMERO DI TELEFONO\n- NUMERO DI CELLUARE";
	var atLeastOneContact = false;

	// Checks mandatory fields
	document.contactForm.firstName.value = trimSpace(document.contactForm.firstName.value);
	if (document.contactForm.firstName.value=="")
	errorString +=  "- NOME \n";

	document.contactForm.lastName.value = trimSpace(document.contactForm.lastName.value);
	if (document.contactForm.lastName.value=="")
	errorString +=  "- COGNOME \n";

	document.contactForm.companyName.value = trimSpace(document.contactForm.companyName.value);
	if (document.contactForm.companyName.value=="")
	errorString +=  "- NOME AZIENDA \n";

	document.contactForm.vatNumber.value = trimSpace(document.contactForm.vatNumber.value);
	if (document.contactForm.vatNumber.value=="")
	errorString +=  "- PARTITA IVA \n";

	document.contactForm.addressStreet.value = trimSpace(document.contactForm.addressStreet.value);
	if (document.contactForm.addressStreet.value=="")
	errorString +=  "- INDIRIZZO \n";

	document.contactForm.addressNumber.value = trimSpace(document.contactForm.addressNumber.value);
	if (document.contactForm.addressNumber.value=="")
	errorString +=  "- NUMERO CIVICO \n";

	document.contactForm.city.value = trimSpace(document.contactForm.city.value);
	if (document.contactForm.city.value=="")
	errorString +=  "- COMUNE \n";

	if (document.contactForm.idProvince.selectedIndex==0)
	errorString +=  "- PROVINCIA \n";

	document.contactForm.cap.value = trimSpace(document.contactForm.cap.value);
	if (document.contactForm.cap.value=="")
	errorString +=  "- C.A.P. \n";

	document.contactForm.addressNumber.value = trimSpace(document.contactForm.addressNumber.value);
	if (document.contactForm.addressNumber.value=="")
	errorString +=  "- NUMERO CIVICO \n";

	if (document.contactForm.idSite.selectedIndex==0)
	errorString +=  "- AREA DI APPARTENENZA \n";

	// Checks fields well-formedness
	document.contactForm.firstName.value = trimSpace(document.contactForm.firstName.value);
	var check = isValidName(document.contactForm.firstName.value);
	if (check != null)
	errorString2 +=  "- NOME : " + check;

	document.contactForm.lastName.value = trimSpace(document.contactForm.lastName.value);
	var check = isValidName(document.contactForm.lastName.value);
	if (check != null)
	errorString2 +=  "- COGNOME : " + check;

	document.contactForm.telephoneNumber.value = trimSpace(document.contactForm.telephoneNumber.value);
	if(document.contactForm.telephoneNumber.value!="") {
		var check = isValidPhoneNumber(document.contactForm.telephoneNumber.value);
		if (check != null)
		errorString2 +=  "- NUMERO DI TELEFONO : " + check;
	}

	document.contactForm.mobilePhoneNumber.value = trimSpace(document.contactForm.mobilePhoneNumber.value);
	if(document.contactForm.mobilePhoneNumber.value!="") {
		var check = isValidPhoneNumber(document.contactForm.mobilePhoneNumber.value);
		if (check != null)
		errorString2 +=  "- NUMERO DI CELLULARE : " + check;
	}

	document.contactForm.mailFrom.value = trimSpace(document.contactForm.mailFrom.value);
	if(document.contactForm.mailFrom.value!="") {
		var check = emailCheck(document.contactForm.mailFrom.value);
		if (!check)
		errorString2 += "- E-MAIL\n";
	}

	document.contactForm.city.value = trimSpace(document.contactForm.city.value);
	if (!isRightComune(document.contactForm.city.value))
	errorString2 += "- COMUNE\n";

	document.contactForm.cap.value = trimSpace(document.contactForm.cap.value);
	if (document.contactForm.cap.value=="" || !isNumber(document.contactForm.cap.value) || document.contactForm.cap.value.length!=5)
	errorString2 += "- CAP\n";

	document.contactForm.vatNumber.value = trimSpace(document.contactForm.vatNumber.value);
	if(document.contactForm.vatNumber.value!="") {
		var check = isValidVatCode(document.contactForm.vatNumber.value);
		if (!check)
		errorString2 += "- PARTITA IVA\n";
	}

	// Checks if at least one field among eMailAddress, telephoneNumber and mobilePhoneNumber is not empty
	if (document.contactForm.mailFrom.value != "" || document.contactForm.telephoneNumber.value != "" || document.contactForm.mobilePhoneNumber.value != "")
	atLeastOneContact = true;

	if (errorString != "")
	{
		alert(intestazione1 + errorString);

	}
else if (errorString2 != "")
{
	alert(intestazione2 + errorString2);

}
else if (atLeastOneContact == false)
{
	alert(intestazione3);
}
else
	{
		document.contactForm.submit();
	}
}

/*************************************************************************
* Contact Us form validation javascript
*************************************************************************/
function validateContactUs()
{
	var errorMsg = "";
	var alertMsg = "";

        // if numbers of elements = 8 the user is not loggeed
        if (document.contactForm.elements.length == 8) {
          document.contactForm.firstName.value = trimSpace(document.contactForm.firstName.value);
          if (document.contactForm.firstName.value=="")
          {
                  errorMsg += " - Nome\n";
          }
  else
          {
                  if(!isString(document.contactForm.firstName.value))
                  {
                          alertMsg += " - formato del nome non e' corretto\n"
                  }
                  if(document.contactForm.firstName.value.length<2)
                  {
                          alertMsg +=" - lunghezza del nome non puo' essere minore di 2\n"
                  }
          }

          document.contactForm.lastName.value = trimSpace(document.contactForm.lastName.value);
          if (document.contactForm.lastName.value=="")
          {
                  errorMsg += " - Cognome\n";
          }
  else
          {
                  if(!isString(document.contactForm.lastName.value))
                  {
                          alertMsg += " - formato del cognome non e' corretto\n"
                  }
                  if(document.contactForm.lastName.value.length<2)
                  {
                          alertMsg +=" - lunghezza del cognome non puo' essere minore di 2\n"
                  }
          }
        }

	if (document.contactForm.mailSubject.selectedIndex<=0)
	errorMsg += " - Oggetto del messaggio\n";


	document.contactForm.mailBody.value = trimSpace(document.contactForm.mailBody.value);
	if (document.contactForm.mailBody.value=="")
	{
		errorMsg += " - Testo e-mail\n";
	}
else
	{
		if(document.contactForm.mailBody.value.length<2)
		{
			alertMsg +=" - lunghezza del testo della mail non puo' essere minore di 2\n"
		}
	}

	document.contactForm.mailFrom.value = trimSpace(document.contactForm.mailFrom.value);
	if (document.contactForm.mailFrom.value=="")
	{
		errorMsg += " - Indirizzo e-mail del mittente\n";
	}
else
	{
		if  (!emailCheck(document.contactForm.mailFrom.value))
		{
			alertMsg += " - L'indirizzo di posta elettronica del mittente non ha un formato corretto \n";
		}
	}

	if (errorMsg!="")
	{
		alert("Per procedere e' necessario specificare le seguenti informazioni :\n" + errorMsg);
	}
else if(alertMsg !="")
{
	alert("Prego voler controllare i seguenti campi: \n"+ alertMsg);
}
else
	{
		document.contactForm.submit();
	}
}


/*************************************************************************
 * Validates the "3 a Webcam" contact page.                              *
 *************************************************************************/
function VideocallOnWebValidate() {

var errorMsg = "";
var alertMsg = "";

  document.userProfileForm.emailAddress.value = trimSpace(document.userProfileForm.emailAddress.value);
  if (document.userProfileForm.emailAddress.value=="")
  {
    errorMsg += " - Indirizzo e-mail\n";
  }
  if  (!emailCheck(document.userProfileForm.emailAddress.value))
  {
    alertMsg += "L'indirizzo di posta elettronica non ha un formato corretto\n";
  }
  if (errorMsg!="")
  {
    alert("Per procedere è necessario specificare le seguenti informazioni :\n" + errorMsg);
  }
  else if(alertMsg !="")
  {
    alert(alertMsg);
  }
  else
  {
    document.userProfileForm.submit();
  }
}
/*************************************************************************
 * Reset all fields "Become Partner Form".                              *
 *************************************************************************/
function resetBecomePartnerForm()
{
	document.contactForm.companyName.value='';
	document.contactForm.idLegalStatus.selectedIndex='0';
	document.contactForm.companyProfile.value='';
	document.contactForm.otherMandates.value='';
	document.contactForm.idSite.selectedIndex='0';
	document.contactForm.agentNumber.value='';
	document.contactForm.firstName.value='';
	document.contactForm.lastName.value='';
	document.contactForm.addressStreet.value='';
	document.contactForm.addressNumber.value='';
	document.contactForm.city.value='';
	document.contactForm.idProvince.selectedIndex='0';
	document.contactForm.idProvince.options.length='1';
	document.contactForm.telephoneNumber.value='';
	document.contactForm.mobilePhoneNumber.value='';
	document.contactForm.mailFrom.value='';
}

