//********************************************************************
//*-------------------------------------------------------------------
//* Licensed Materials - Property of IBM
//*
//* WebSphere Commerce
//*
//* (c) Copyright International Business Machines Corporation. 2003
//*     All rights reserved.
//*
//* US Government Users Restricted Rights - Use, duplication or
//* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//*
//*-------------------------------------------------------------------
//*


//////////////////////////////////////////////////////////
// Checks whether a string contains a double byte character
// target = the string to be checked
//
// Return true if target contains a double byte char; false otherwise
//////////////////////////////////////////////////////////
function containsDoubleByte (target) {
     var str = new String(target);
     var oneByteMax = 0x007F;

     for (var i=0; i < str.length; i++){
        chr = str.charCodeAt(i);
        if (chr > oneByteMax) {return true;}
     }
     return false;
}

//////////////////////////////////////////////////////////
// A simple function to validate an email address
// It does not allow double byte characters
// strEmail = the email address string to be validated
//
// Return true if the email address is valid; false otherwise
//////////////////////////////////////////////////////////
function isValidEmail(strEmail){
	// check if email contains dbcs chars
	if (containsDoubleByte(strEmail)){
		return false;
	}
	
	if(strEmail.length == 0) {
		return true;
	} else if (strEmail.length < 5) {
             return false;
       	}else{
           	if (strEmail.indexOf(" ") > 0){
                      	return false;
               	}else{
                  	if (strEmail.indexOf("@") < 1) {
                            	return false;
                     	}else{
                           	if (strEmail.lastIndexOf(".") < (strEmail.indexOf("@") + 2)){
                                     	return false;
                                }else{
                                        if (strEmail.lastIndexOf(".") >= strEmail.length-2){
                                        	return false;
                                        }
                              	}
                       	}
              	}
       	}
      	return true;
}


//////////////////////////////////////////////////////////
// Questa funzione controlla che in un campo numerico 
// non siano stati inseriti caratteri
//
// Return false is this input in not a number
// Otherwise return true...
//////////////////////////////////////////////////////////
function isAlphaDigit(onlyDigit, sField)
{
	var car;
	var carOk = true;
	var i;
	
	for (i = 0; i<sField.length; i++) {
		car = sField.charAt(i);
		
		// se il carattere non è compreso fra le lettere minuscole, e non è compreso fra le lettere maiuscole
		// e non è compreso fra i numeri, il carattere è errato		
		if (onlyDigit == false) {
			if ( !( car >= "a" && car <= "z" ) && !( car >= "A" && car <= "Z" ) && !( car >= "0" && car <= "9" ) ) {
				carOk = false;
				break;
			}		
		} else {
			if ( !( car >= "0" && car <= "9" ) ) {
				carOk = false;
				break;
			}		
		}
	}

	return carOk;
}



//////////////////////////////////////////////////////////
//
// Questa funzione controlla che un numero di telefono contenga solo cifre e il segno meno
//
//////////////////////////////////////////////////////////
function isCorrectPhoneNumber(sField,phoneType)
{
	var car;
	var carOk = true;
	var i = 0;
	var trovatoSeparatore = false;
	var posizioneSeparatore;
	
	if (sField.length > 0){
		
		while (i < sField.length && carOk) {
		
			car = sField.charAt(i);
		
			if ( !( car >= "0" && car <= "9" ) ) {
				carOk = false;
			}
			
			if (trovatoSeparatore == false && car == '-'){
				posizioneSeparatore = i;
				trovatoSeparatore = true;
				carOk = true;
			}
			else if (trovatoSeparatore == true && car == '-'){
				carOk = false;
			}
			
			i++;
				
		}
		
		if (!carOk){
			window.alert("Il campo " + phoneType + " non e' corretto.");
		}
		
		if (carOk && !trovatoSeparatore){
			carOk = false;
			window.alert("Il campo " + phoneType + " non e' corretto.\nUtilizza correttamente il separatore ( - )");
		}
		
		if (carOk && (sField.indexOf('-') < 2 || sField.indexOf('-') > 4 )){
			carOk = false;
			window.alert("Il campo " + phoneType + " non e' corretto.\nUtilizza correttamente il separatore ( - )");
		}
	}
	else {
		carOk = true;
	}

	return carOk;
}





//////////////////////////////////////////////////////////
// Questa funzione controlla che il cap esista e sia corretto
//
// Return false is this input in not a number
// Otherwise return true...
//////////////////////////////////////////////////////////
function cap(sCap)
{
	if (sCap.length == 0) {
		window.alert("Il campo CAP è obbligatorio");
		return false;
	} else if (sCap.length != 5) {	
		window.alert("Il campo CAP deve essere composto da 5 numeri");
		return false;
	}
	if (!isAlphaDigit(true, sCap)) {	
		window.alert("Il campo CAP deve essere composto da numeri");
		return false;		
	}
	return true;
}

//////////////////////////////////////////////////////////
// Questa funzione controlla che sia un codice fiscale corretto
// 
// Return false is this input in not a codiceFiscale
// Otherwise return true...
//////////////////////////////////////////////////////////
function codiceFISCALE(cfins)
{
   var cf = cfins.toUpperCase();
   if(cf.length == 11){
   		sz_Codice = cf;
   		var n_Val,n_Som1=0,n_Som2=0,lcv;
	if (sz_Codice.length!=11 || isNaN(parseFloat(sz_Codice)) || parseFloat(sz_Codice)<parseFloat(0))
		return false;
   
	for (lcv=0;lcv<9;lcv+=2)
	{
		n_Val=parseInt(sz_Codice.charAt(lcv));
		n_Som1+=n_Val;
		n_Val=parseInt(sz_Codice.charAt(lcv+1));
		n_Som1+=Math.floor(n_Val/5) + (n_Val<<1) % 10;
	}
	
	if (n_Som1 % 10 != 0)
		n_Som2 = 10 -(n_Som1 - 10 * parseInt((n_Som1 / 10),10));
	else
		n_Som2 = 0;
  
	n_Val=parseInt(sz_Codice.charAt(10));

	if (n_Som2==n_Val)
		return true;
	return false;
   }else{
	   var cfReg = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
	   if (!cfReg.test(cf))
	      return false;
	   var set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	   var set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	   var setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	   var setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	   var s = 0;
	   for( i = 1; i <= 13; i += 2 )
	      s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	   for( i = 0; i <= 14; i += 2 )
	      s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	   if ( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
	      return false;
	      return true;
	}
   
}

//////////////////////////////////////////////////////////
// Questa funzione controlla che la partita iva sia corretta
// 
// Return false is this input in not a partitaIva
// Otherwise return true...
//////////////////////////////////////////////////////////
function partitaIVA(sz_Codice)
{
	
	var n_Val,n_Som1=0,n_Som2=0,lcv;
	if (sz_Codice.length!=11 || isNaN(parseFloat(sz_Codice)) || parseFloat(sz_Codice)<parseFloat(0))
		return false;
   
	for (lcv=0;lcv<9;lcv+=2)
	{
		n_Val=parseInt(sz_Codice.charAt(lcv));
		n_Som1+=n_Val;
		n_Val=parseInt(sz_Codice.charAt(lcv+1));
		n_Som1+=Math.floor(n_Val/5) + (n_Val<<1) % 10;
	}
	
	if (n_Som1 % 10 != 0)
		n_Som2 = 10 -(n_Som1 - 10 * parseInt((n_Som1 / 10),10));
	else
		n_Som2 = 0;
  
	n_Val=parseInt(sz_Codice.charAt(10));

	if (n_Som2==n_Val)
		return true;
	return false;
}
//////////////////////////////////////////////////////////
// Questa funzione controlla che i dati fondamentali siano
// compilati.
// 
// arg1 Nome
// arg2 Cognome
// arg3 Indirizzo
// arg4 Provincia
// arg5 Città
// arg6 Cap
// Return false if one of this input is blanck
// Otherwise return true...
//////////////////////////////////////////////////////////
function checkFondamentaliBilling(firstName,lastName,priazi,pIva,codFisc,ragsoc,address1,state,city,zipCode){
	if (firstName.length == 0) {
			window.alert("Il campo NOME è obbligatorio!");
			return false;
		}
		if (lastName.length == 0) {
			window.alert("Il campo COGNOME è obbligatorio!");
			return;
		}
		if (address1.length == 0) {
			window.alert("Il campo INDIRIZZO è obbligatorio!");
			return false;	
		}
		if (state.length == 0) {
			window.alert("Selezionare una PROVINCIA!");
			return false;	
		}
		if (city.length == 0) {
			window.alert("Il campo CITTA' è obbligatorio!");
			return false;	
		}
		if (zipCode.length == 0) {
			window.alert("Il campo CAP è obbligatorio!");
			return false;	
		}
				// Controllo il codice fiscale / partita iva
		if (priazi == "Privato") {
		
			if (codFisc.length == 0){
				alert("Il campo CODICE FISCALE e' obbligatorio.");
				return false;
			}
		
			if ( !codiceFISCALE( codFisc ) ){
				alert("Codice Fiscale errato."); 
				return false; 
			}
		}
		else {
			if (pIva.length == 0){
				alert("Il campo PARTITA IVA e' obbligatorio.");
				return false;
			}
			
			if (codFisc.length == 0){
				alert("Il campo CODICE FISCALE e' obbligatorio.");
				return false;
			}
			if (ragsoc.length == 0){
				alert("Il campo RAGIONE SOCIALE e' obbligatorio.");
				return false;
			}
		
			if ( !partitaIVA( pIva ) ) {
				alert("Partita IVA errata.");
				return false;
			} 
			
			if ( !codiceFISCALE( codFisc ) ){
				alert("Codice Fiscale errato."); 
				return false; 
			}
		}
	return true;
}
//////////////////////////////////////////////////////////
// Questa funzione controlla che i dati fondamentali siano
// compilati.
// 
// arg1 Nome
// arg2 Cognome
// arg3 Indirizzo
// arg4 Provincia
// arg5 Città
// arg5b zipCode (cap)
// arg6 email1
// arg7 phone1 (telefono)
// arg8 phone2 (cellulare)
// arg9 logonId (user)
// arg10 logonPassword 
// arg11 logonPasswordVerify
// Return false if one of this input is blanck
// Otherwise return true...
//////////////////////////////////////////////////////////
function checkFondamentali(firstName,lastName,tipoCod,pIva,codFisc,address1,addressNumber,state,city,zipCode,email1,phone1,phone2,logonId,logonPassword,logonPasswordVerify){
		var numeri = "0123456789";
		var logon=logonId.length;		
		var password=logonPassword.length;
		var passwordverify=logonPasswordVerify.length;
		
		

		// Controllo il nome
		if (firstName.length == 0) {
			window.alert("Il campo NOME è obbligatorio.");
			return false;
		}
		
		// Controllo il cognome
		if (lastName.length == 0) {
			window.alert("Il campo COGNOME è obbligatorio.");
			return false;
		}
		
		// Controllo il codice fiscale / partita iva
		if (tipoCod == "Privato") {
		
			if (codFisc.length == 0){
				alert("Il campo CODICE FISCALE e' obbligatorio.");
				return false;
			}
			var first_numero = true;
			var str="";
			str = codFisc.toLowerCase();
			lettere = str.substring(0,1);
			 for (i=0;i<1;i++){
		         if (lettere.charCodeAt(i)<97 || lettere.charCodeAt(i)>122){
		         	first_numero=false;
		         }
			}
			
			if(first_numero){
				if ( !codiceFISCALE( codFisc ) ){
					alert("Codice Fiscale errato."); 
					return false; 
				}
			}else{
					alert("Codice Fiscale errato."); 
					return false; 
			}			
		}
		else {
			if (pIva.length == 0){
				alert("Il campo PARTITA IVA e' obbligatorio.");
				return false;
			}
			
			if (codFisc.length == 0){
				alert("Il campo CODICE FISCALE e' obbligatorio.");
				return false;
			}
		
			if ( !partitaIVA( pIva ) ) {
				alert("Partita IVA errata.");
				return false;
			} 
			
			if ( !codiceFISCALE( codFisc ) ){
				alert("Codice Fiscale errato."); 
				return false; 
			}
		}
		
		// Controllo l'indirizzo
		if (address1.length == 0) {
			window.alert("Il campo INDIRIZZO è obbligatorio.");
			return false;	
		}
		
		// Controllo il numero civico
		if (addressNumber.length == 0) {
			window.alert("Il campo NUMERO CIVICO è obbligatorio.");
			return false;	
		}
		
		// Controllo la provincia
		if (state.length == 0) {
			window.alert("Il campo PROVINCIA è obbligatorio.");
			return false;	
		}
		
		// Controllo la citta'
		if (city.length == 0) {
			window.alert("Il campo CITTA' è obbligatorio.");
			return false;	
		}
		
		// Controllo il cap
		if ( !cap(zipCode) ){
			return false;
		}
		
		// Controllo che almeno un telefono sia stato inserito
		if (phone1.length == 0 && phone2.length == 0) {
			window.alert("Un recapito TELEFONICO è obbligatorio.");
			return false;	
		}
		
		// Controllo il telefono fisso
		if ( !isCorrectPhoneNumber(phone1,'TELEFONO FISSO')){
			return false;
		}
		
		// Controllo il cellulare
		if ( !isCorrectPhoneNumber(phone2,'TELEFONO CELLULARE')){
			return false;
		}
		
		// Controllo se il campo email e' stato compilato
		if (email1.length == 0) {
			window.alert("Il campo E-MAIL è obbligatorio.");
			return false;	
		}
		
		// Controllo se l'email e' corretta
		if (email1.length == 0){
			window.alert("Il campo E-MAIL e' obbligatorio.");
			return false;	
		}
		
		if (!isValidEmail(email1)) {
			window.alert("Il campo E-MAIL non e' corretto.");
			return false;	
		}
		
		// Controllo lo user id
		if (logon == 0){
			window.alert("Devi inserire uno USERNAME");
			return false;	
		}
		
		if (logonPassword != '************' && logonPasswordVerify != '************' ){
		
			// Controllo la password
			if (logonPassword.length == 0){
				window.alert("Il campo PASSWORD e' obbligatorio.");
				return false;	
			}
			
			// Controllo la password di verifica
			if (logonPasswordVerify.length == 0){
				window.alert("Il campo VERIFICA PASSWORD e' obbligatorio.");
				return false;	
			}
	
			// Controllo la password
			if (logonPassword.length < 6){
				window.alert("La PASSWORD deve essere di almeno 6 caratteri e deve contenere almeno una cifra!");
				return false;	
			}
			
			// Controllo la password
			if (logonPasswordVerify.length < 6){
				window.alert("La PASSWORD deve essere di almeno 6 caratteri e deve contenere almeno una cifra!");
				return false;	
			}
	
			
			// Controllo che le due password siano identiche
			if (logonPassword != logonPasswordVerify){
				window.alert("Verifica PASSWORD non corretta.");
				return false;	
			}
			
			// Controllo la password
			if (logonPassword == logonPasswordVerify){
				check = false;
				i = 0;
				for (i = 0 ; i < logonPassword.length ; i++){
					if (numeri.indexOf(logonPassword.charAt(i)) != -1){
						check = true;
					}
				}
				if (!check){
					window.alert("La PASSWORD deve contenere almeno una cifra!");
					return false;
				}
			}
		}
		

		return true;
}


//////////////////////////////////////////////////////////
// This function will count the number of bytes
// represented in a UTF-8 string
//
// arg1 = the UTF-16 string
// arg2 = the maximum number of bytes allowed in your input field
// Return false is this input string is larger then arg2
// Otherwise return true...
//////////////////////////////////////////////////////////
function isValidUTF8length(UTF16String, maxlength) {
    if (utf8StringByteLength(UTF16String) > maxlength) return false;
    else return true;
}

//////////////////////////////////////////////////////////
// This function will count the number of bytes
// represented in a UTF-8 string
//
// arg1 = the UTF-16 string you want a byte count of...
// Return the integer number of bytes represented in a UTF-8 string
//////////////////////////////////////////////////////////
function utf8StringByteLength(UTF16String) {
  if (UTF16String === null) return 0;
  var str = String(UTF16String);
  var oneByteMax = 0x007F;
  var twoByteMax = 0x07FF;
  var byteSize = str.length;

  for (i = 0; i < str.length; i++) {
    chr = str.charCodeAt(i);
    if (chr > oneByteMax) byteSize = byteSize + 1;
    if (chr > twoByteMax) byteSize = byteSize + 1;
  }  
  return byteSize;
}

//////////////////////////////////////////////////////////
// Questa funzione controlla se l'utente è privato o azieda
// 
// arg1 nomeForm
// arg2 ordine (0 -> privato; 1 -> azienda)
// Return false if one of this input is blanck
// Otherwise return true...
//////////////////////////////////////////////////////////
function abilitaRacsocOPiva(nomeForm, ordine){
	if (ordine==0){
		nomeForm.addressField3.disabled=true;
		nomeForm.addressField1.disabled=true;
		nomeForm.addressField1.focus()
	}else{
		nomeForm.addressField1.disabled=false;
		nomeForm.addressField3.disabled=false;
		nomeForm.addressField3.focus()
	}
}
//////////////////////////////////////////////////////////
// Questa funzione apre un finestra di pop-up
// 
// theURL --> url della finestra che deve aprire
// winName --> Nome della finestra che deve aprire
// features --> attributi x esempio ('width=650,height=420,scrollbars=no')
// Otherwise return true...
//////////////////////////////////////////////////////////
function MM_openBrWindow(theURL,winName,features){ 
  window.open(theURL,winName,features);
}
function MM_openBrWindowNew(theURL,winName){
  window.open(theURL,winName);
}


function MM_openBrWindowNavigator(theURL,winName,features){
	if(navigator.appName == "Netscape"){
		features = features + ",screenY=10,screenX=700";
	}else{
		features = features + ",top=10,left=700";
	}
	window.open(theURL,"NEW",features);
}





















