

//======================================
//  FUNZIONE GENERALI TRIM
//======================================
function Ltrim(s){
	
	var s1
	var re;
  
  	re=/^\s+/g;
  	
	s1 = s.replace(re,"");
	
	return s1;
}

function Rtrim(s){
	
	var s1
	var re;
  
  	re=/\s+$/g;
  	
	s1 = s.replace(re,"");
	
	return s1;
}

function trim(s){
	
	var s1
	var re;
	
	re = /\s+$|^\s+/g;
  	s1 = s.replace(re,"");
	
	return s1;
}

//======================================
//  FUNZIONE CHE CONTROLLA LA LOGIN 
//======================================
function checkLogin(){
	
	var userid, psw, msg;
	
	msg = '';
	userid = trim(document.frm_login.userid.value);
	psw = trim(document.frm_login.psw.value);
	
	if (psw.length == 0) msg='Inserire la password';
	if (userid.length == 0) msg='Inserire il nome utente';
	
	if (msg != '' ){
		alert(msg);
		return false;
	}else
		return true;
}

//======================================
//  FUNZIONE CHE APRE UNA FINESTRA 
//======================================
function apripagina(pagina,dx,dy,rsz,scrl,pos,menub){
	
	var settings, TopPosition, LeftPosition;

	//	screen.width    DIMENSIONE DELLO SCHERMO IN LARGHEZZA	
	//	screen.height  	DIMENSIONE DELLO SCHERMO IN ALTEZZA
	//	dx				DIMENSIONE DELLA FINESTRA IN LARGHEZZA
	//	dy				DIMENSIONE DELLA FINESTRA IN ALTEZZA
    if (pos==""){
		pos = "center";
	}
	if (pos=="center"){
		// allineamento della finestra in mezzo
		TopPosition = ((screen.height) / 2) - (dy/2);
		// allineamento della finestra in mezzo
		LeftPosition = ((screen.width) / 2) - (dx/2);
	}
	if (pos=="right"){
		// allineamento della finestra in alto a destra
		TopPosition = 0;
		// allineamento della finestra a destra
		LeftPosition = (screen.width) - dx -10;
	}
	if (pos=="left"){
		// allineamento della finestra in alto a sinistra
		TopPosition = 0;
		// allineamento della finestra a destra
		LeftPosition = 0;
	}
	
	if (menub==""){
		menub = "yes";
	}
		
	// settaggio delle caratteristiche della finestra da aprire
	settings ='height='+dy+',width='+dx+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scrl+',resizable='+rsz+',titlebar=no,status=yes,menubar='+menub;	
	
	// se esite gia' una finestra aperta allora la chiudo e la distruggo;
	//if (win != null){
	//	win.close();
	//	win = null;
	//}
	
	// apro una nuova finestra e le assegno il focus il nome della nuova finestra
	// (secondo campo nell'elenco parametri) non deve contenere nulla ;
	// se il campo nomepagina non è vuoto apro sempre nella stessa finestra che 
	// ha sempre lo stesso nome 
	
	//win = window.open(pagina,'',settings)
	win = window.open(pagina,'ciccio',settings)
	win.window.focus();
}

//==========================================
//  FUNZIONE CHE RIDIMENSIONA UNA FINESTRA 
//==========================================

function ridimensiona(objName, pos) {
	
	var objImg = document.getElementById(objName);
    
    var x = objImg.width;
    var y = objImg.height;
    
	if (pos==""){
		pos = "center";
	}
	if (pos=="center"){
		// allineamento della finestra in mezzo
		self.moveTo((screen.width - x)/2, (screen.height - y)/2)
	}
	if (pos=="right"){
		// allineamento della finestra in alto a destra
		self.moveTo((screen.width) - x -10, 0)
	}
	if (pos=="left"){
		// allineamento della finestra in alto a sinistra
		self.moveTo(0 , 0)
	}
}

//=====================================================
//  FUNZIONE CHE CONTROLLA IL CAMPO EMAIL DI UN FORM
//=====================================================			
function isEmailOk(data) {
  if (data.indexOf(".") != -1) {
      if (data.indexOf("@") != -1)  { 
	      return true;
		  }
		}
	else return false;	  
}

//=============================================================
//  FUNZIONE CHE CONTROLLA IL RIEMPIMENTO DEL CAMPO DI UN FORM
//=============================================================		
function isSpace(data) {
	var contr2=0;
   	for(var i=0; i < data.length; i++){
		if(data.substring(i, i+1) != " ")
	   		contr2=1; 
	}   
	if  (contr2==1)   
		return(false);  
return(true);
}

//=============================================================
//  FUNZIONE CHE CONTROLLA IL CODICE FISCALE
//=============================================================		
function codiceFISCALE(cfins) {
	
	   var cf = cfins.toUpperCase();
	   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;
	}
	
//=============================================================
//  FUNZIONE CHE CONTROLLA LA PARTITA IVA
//=============================================================		
	
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;
   }
   n_Som2 = 10 - (n_Som1 % 10);
   n_Val=parseInt(sz_Codice.charAt(10));
   if (n_Som2==n_Val)
      return true;
   return false;
}

//=============================================================
//  FUNZIONE CHE CONTROLLA LA LOGIN AL WORKSPACE
//=============================================================		
function controlla_login(lang){

	var message = new Array();
	var msg;
	var errorLevel;
	
	message[0]  = "";
	
	switch (lang) {
		case "IT":
			message[1] = "IL CAMPO LOGIN E' OBBLIGATORIO !";
			message[2] = "IL CAMPO PASSWORD E' OBBLIGATORIO !";
			break; 
	   	case "UK":
			message[1] = "FIELD LOGIN REQUIRED !";
			message[2] = "FIELD PASSWORD REQUIRED !";
			break; 
		default :
	    	message[1] = "IL CAMPO LOGIN E' OBBLIGATORIO !";
			message[2] = "IL CAMPO PASSWORD E' OBBLIGATORIO !";
		break; 
	} 	
		
	errorLevel = 0;
	if ((errorLevel == 0) && ((document.FormN.username.value.length == 0) || isSpace(document.FormN.username.value))) errorLevel = 1;	
	if ((errorLevel == 0) && ((document.FormN.password.value.length == 0) || isSpace(document.FormN.password.value))) errorLevel = 2;	
	
	if (errorLevel > 0 ) { 
		alert(message[errorLevel]); 
	}else{
		user = document.FormN.username.value
		pass = document.FormN.password.value
		lingua = document.FormN.lingua.value
		
		apripagina('/'+lingua+'/workspace/login.asp?username='+user+'&password='+pass,'795','480','yes','no','center','no');
	} 
}	
	
//=============================================================
//  FUNZIONE CHE CONTROLLA I CAMPI DI UN FORM ( FormN )
//=============================================================			
function checkRequiredFields(lang, tipo) {
		
	var message = new Array();
	var errorLevel;
	
	message[0]  = "";
	
	switch (lang) {
		case "it":
			message[1] = "IL COMPO PROVINCIA E' OBBLIGATORIO !";
	    	message[2] = "IL COMPO E-MAIL E' OBBLIGATORIO !";
			message[3] = "INDIRIZZO EMAIL non corretto";
			message[4] = "IL COMPO AZIENDA E' OBBLIGATORIO !";
			message[5] = "IL COMPO TELEFONO E' OBBLIGATORIO !";
			message[6] = "IL COMPO INTERESSATO A E' OBBLIGATORIO !";
			message[7] = "IL COMPO DESIDERA E' OBBLIGATORIO !";
			message[8] = "L'AUTORIZZAZIONE AL TRATTAMENTO DATI E' OBBLIGATORIA !";
			break; 
	   	case "uk":
			message[1] = "FIELD (*) REQUIRED !";
	    	message[2] = "FIELD E-MAIL REQUIRED !";
			message[3] = "FIELD E-MAIL IS WRONG";
			message[4] = "FIELD (*) REQUIRED !";
			message[5] = "FIELD (*) REQUIRED !";
			message[6] = "FIELD (*) REQUIRED !";
			message[7] = "FIELD (*) REQUIRED !";
			message[8] = "FIELD (*) REQUIRED !";
			break; 
	   	default :
	    	message[1] = "IL COMPO PROVINCIA E' OBBLIGATORIO !";
	    	message[2] = "IL COMPO E-MAIL E' OBBLIGATORIO !";
			message[3] = "INDIRIZZO EMAIL non corretto";
			message[4] = "IL COMPO AZIENDA E' OBBLIGATORIO !";
			message[5] = "IL COMPO TELEFONO E' OBBLIGATORIO !";
			message[6] = "IL COMPO INTERESSATO A E' OBBLIGATORIO !";
			message[7] = "IL COMPO DESIDERA E' OBBLIGATORIO !";
			message[8] = "L'AUTORIZZAZIONE AL TRATTAMENTO DATI E' OBBLIGATORIA !";
			break; 
	} 
		
				 
	errorLevel = 0;  

	if ((errorLevel == 0) && ((document.FormN.provincia.value.length == 0) || isSpace(document.FormN.provincia.value))) {
		errorLevel = 1;	
	}
	if ((errorLevel == 0) && ((document.FormN.email.value.length == 0) || isSpace(document.FormN.email.value))) {
		errorLevel = 2;	
	}
	if ((errorLevel == 0) && (!(isEmailOk(document.FormN.email.value)))) {
		errorLevel = 3;
	}
	if ((errorLevel == 0) && ((document.FormN.azienda.value.length == 0) || isSpace(document.FormN.azienda.value))) {
		errorLevel = 4;	
	}
	if ((errorLevel == 0) && ((document.FormN.telefono.value.length == 0) || isSpace(document.FormN.telefono.value))) {
		errorLevel = 5;	
	}
	
	if ((errorLevel == 0) && (document.FormN.ch1.checked != true) && (document.FormN.ch2.checked != true) && (document.FormN.ch3.checked != true) && (document.FormN.ch4.checked != true) && (document.FormN.ch5.checked != true) && (document.FormN.ch6.checked != true) && (document.FormN.ch7.checked != true) && ((document.FormN.altro.value.length == 0) || isSpace(document.FormN.altro.value))) {
		errorLevel = 6;	
	}
	if ((errorLevel == 0) && (document.FormN.ch8.checked != true) && (document.FormN.ch9.checked != true) && (document.FormN.ch10.checked != true) && (document.FormN.ch11.checked != true) && ((document.FormN.altro2.value.length == 0) || isSpace(document.FormN.altro2.value))){
		errorLevel = 7;	
	}
	
	if ((errorLevel == 0) && (document.FormN.ch12.checked != true )){
		errorLevel = 8;	
	}
	
	if (errorLevel > 0 ) { 
		alert(message[errorLevel]); 
		
		if (tipo == 'submit') {
			return false;
		}
	} else{
		if (tipo == 'link') {
			document.FormN.submit();
		} else{
			return true;
		}
	}
}

//=============================================================
//  FUNZIONE CHE CONTROLLA IL RIEMPIMENTO DEL CAMPO DI UN FORM 
//  DI RICERCA NEL CATALOGO
//=============================================================		
function search(lang){
	keywords = document.frm_ricerca.keywords.value;
	min_len_keywords = document.frm_ricerca.min_len_keywords.value;
	
	if (min_len_keywords == ""){
		min_len_keywords = 2;
	}
	
	if ((keywords == "") || (isSpace(keywords)) || (keywords.length < min_len_keywords)){
		
		switch (lang) {
			case "IT":
		    	alert("Inserire una chiave di ricerca con almeno "+min_len_keywords+" caratteri");
				break; 
		   	case "UK":
		    	alert("Insert keywords");
				break;
		   	default :
		    	alert("Inserire una chiave di ricerca con almeno "+min_len_keywords+" caratteri");
				break;
		} 
	}else{
		document.frm_ricerca.submit();
	}
}



//=============================================================
//  FUNZIONE CHE CONTROLLA LA QUANTITA MAX ORDINABILE
//=============================================================			
function controlla_qta(nomeform) {
		
	var message = new Array();
	var errorLevel;
	
	stringa = "document." + nomeform + ".qta_max.value";
	stringa2 = "document." + nomeform + ".quantita.value";
	stringa3 = "document." + nomeform + ".quantita.selectedIndex="+(eval(stringa)-1);
	
	message[0]  = "";
	message[1] = "La quantita massima ordinabile è di "+eval(stringa)+" unità!";

	errorLevel = 0;  

	if (eval(stringa2) > eval(stringa)) {
		errorLevel = 1;	
		eval(stringa3);
	}

	if (errorLevel > 0 ) { 
		alert(message[errorLevel]); 
		return false;
	} else{
		return true;
	}
}	

//=============================================================
//  FUNZIONE CHE SVUOTA IL CAMPO DI UN FORM DALL'IMPOSTAZIONE
//  DI DEFAULT INSERISCI ....
//=============================================================		
function compilazione1(t){

	switch (t.name){

		case "username":
			if (t.value == "Inserisci E-mail") t.value="";
			//if (document.form_catalogo.username.value == "") document.form_catalogo.password.value="";
			break;
		case "password":
			if (t.value=="Inserisci Password") t.value="";
			//if (document.form_catalogo.username.value=="") document.form_catalogo.username.value="Inserisci E-mail";
			break;
	}
}


function isDateField(date_field, desc, CheckSQLServerDateTimeRange) {

	 if (!date_field.value)  
	 	return true;
	 var in_date = stripCharString(date_field.value," ");
	 
	 var date_is_bad = 0;  
	 if (!allowInString(in_date,"/0123456789+-"))
		date_is_bad = 1; // caratteri non validi
	 
	 if (!date_is_bad) {
	         var date_pieces = new Array();
	         date_pieces = in_date.split("/");
	         if (date_pieces.length == 2) {
	                 var d = new Date();
	                 in_date = in_date + "/" + get_full_year(d);
	                 date_pieces = in_date.split("/");
	         }
	         if (date_pieces.length != 3 || parseInt(date_pieces[0],10) < 1 || parseInt(date_pieces[0],10) > 31 
	                         || parseInt(date_pieces[1],10) < 1 || parseInt(date_pieces[1],10) > 12 
	                         || (date_pieces[2].length != 2 && date_pieces[2].length != 4 && date_pieces[2].length != 3)) {
	                 date_is_bad = 6;  // data non nel formato g/m/a
	         }
	 }
	 if (date_is_bad) {
	         alert(desc + " deve essere nel formato gg/mm/aa oppure gg/mm/aaaa.");
	         date_field.focus();
	         return (false);
	 }
	// scambio il mese con l'anno per il parse
	 in_date = date_pieces[1] + "/" + date_pieces[0] + "/" + date_pieces[2];
	 var ms = Date.parse(in_date);
	 var d = new Date();
	 d.setTime(ms);
	var return_date = d.toLocaleString();
	var return_month = parseInt(d.getMonth() + 1).toString();
	return_month = (return_month.length==1 ? "0" : "") + return_month; 
	var return_date =  parseInt(d.getDate()).toString();
	return_date = (return_date.length==1 ? "0" : "") + return_date; 
	
	//var anno =  get_full_year(d,date_pieces[2])
	//alert(date_pieces[2]);
	var anno = date_pieces[2];
	
	return_date = return_date + "/" + return_month + "/" + anno;
	if ( !CheckSQLServerDateTimeRange || anno >= 1760  ) 
	{
		date_field.value = return_date;
	     return true;
	}
	else
	{
		alert(desc + " non può essere inferiore all''anno 1760.");		
		return (false);
	}
}

function get_full_year(d,AnnoInStringa) 
{
/*
	AnnoInStringa deve essere una stringa (non è obbligatorio ma se non viene specificato, non viene sistemato il bug 
	descritto successivamente (*)
*/
	var y = ""
	//	Estraggo l'anno scritto nella data (2 o 4 cifre)
	y = d.getYear();
	/*	
		(*) Si noti che se è stato scritto un numero compreso tra 1900 e 1999 la funzione ritorna il valore in modulo a 100 (00-99)
		pertanto si rende necessario il controllo successivo. 	
	*/
	if (y>=0 && y<100 && d.getFullYear() >= 1900 && d.getFullYear() < 2000 && AnnoInStringa.length==4 )
		y += 1900;

	// Sistemo il secolo per l'anno a due cifre
	if (y <= 69)
	{
		y += 2000;
	}
	else
		if (y > 69 && y < 100)
			y += 1900;
	
	// eseguo il padding a 4 cifre
	y = (y.length==1 ? "000" : "")+y;
	y = (y.length==2 ? "00" : "")+y;
	y = (y.length==3 ? "0" : "")+y;

	return y;
}

function stripCharString (InString, CharString)  {
	var OutString="";
   	for (var Count=0; Count < InString.length; Count++)
	{
    	var TempChar=InString.substring (Count, Count+1);
      	var Strip = false;
      	for (var Countx = 0; Countx < CharString.length; Countx++)
		{
        	var StripThis = CharString.substring(Countx, Countx+1)
         	if (TempChar == StripThis)
			{
            	Strip = true;
            	break;
         	}
      	}
      	if (!Strip)
        	OutString=OutString+TempChar;
   }
   return (OutString);
}

function allowInString (InString, RefString)  {
        if(InString.length==0) return (false);
        for (var Count=0; Count < InString.length; Count++)  {
        var TempChar= InString.substring (Count, Count+1);
      if (RefString.indexOf (TempChar, 0)==-1)  
        return (false);
   }
   return (true);
}

function IsNumber(num,ConsentiDecimali,ConsentiNegativi)
{

   var i = 0;
   var letter;

   while (i < num.length)
   {
      letter = num.charAt(i);
 
      if ((letter == '0') || (letter == '1') || (letter == '2') ||
          (letter == '3') || (letter == '4') || (letter == '5') ||
          (letter == '6') || (letter == '7') || (letter == '8') ||
          (letter == '9') || (ConsentiDecimali && letter == ',') || (ConsentiNegativi && letter== '-'))
      {
         i++;
      }
      else
      {
         return false;
      }
   }
   
   

   return true;
}

function isNumberField(campo)
{
	 if (!IsNumber(campo.value,false))
	 {
	    alert("Il campo può contenere solamente cifre e non sono consentiti ne numeri negativi ne numeri con decimali!");
		campo.focus(); 
		campo.select();
		return false;
	}    
	else
	{
		return true;
	}
}