<!--
//------------------------------------------------------------------------------
//             Funzioni di utilita' per le operazioni lato client
//                    (c) 2003-2007 Kosmous Srl Ver 2.00
//------------------------------------------------------------------------------

// Impostazioni internazionali
var DECIMAL_SEPARATOR = ",";
var THOUSANDS_SEPARATOR = ".";
var DATE_MASK = "gg/mm/aaaa";
var DATE_REGEXP = "^[ ]*[0]?(\\d{1,2})\\/(\\d{1,2})\\/(\\d{4,})[ ]*$";

// Pattern di sostituzione utilizzati
var RE_CROP_DECIMAL_SEPARATOR = new RegExp("\\" + DECIMAL_SEPARATOR, "gi");
var RE_CROP_THOUSANDS_SEPARATOR = new RegExp("\\" + THOUSANDS_SEPARATOR, "gi");
var RE_LTRIM = new RegExp("^\\s+", "gi");
var RE_RTRIM = new RegExp("/\\s+$/", "gi");
var RE_GLOBALTRIM = new RegExp("\\s", "gi");

//
// Validazione dei moduli
//
var GLOBAL_VALIDATION_ERROR_MSG = "";
function formValidate(objForm){
	var empty_fields = "";
	var errors = "";
	var msg = "";
	var pwdArray = new Array();
	var selSelected = true;
	var pwd_len = 0;
	for(var ElementIndex = 0; ElementIndex < objForm.length; ElementIndex++){
		var CurrElement = objForm.elements[ElementIndex];
		test_var = "";
		if(CurrElement.value){
			test_var = CurrElement.value;
		}
		//Valida i campi di tipo testo
		if (((CurrElement.type == "text") || (CurrElement.type == "textarea") || (CurrElement.type == "password") || (CurrElement.type == "file")) && CurrElement.validate){
			//Verifica se sono vuoti
			if ((CurrElement.value == null) || (CurrElement.value == "") || IsBlank(CurrElement.value)){
				if (CurrElement.description != null){
					empty_fields += "\n\t> " + CurrElement.description;
				}
				else{
					empty_fields += "\n\t> " + CurrElement.name;
				}
				continue;
			}
			//Verifica i campi di tipo numerico
			if (CurrElement.isNumeric || CurrElement.isInteger || (CurrElement.min != null) || (CurrElement.max != null) || (CurrElement.lunghezza != null)){
				// Esegue il trim ed elimina il separatore delle migliaia
				test_var = test_var.replace(RE_LTRIM, "");
				test_var = test_var.replace(RE_RTRIM, "");
				if(CurrElement.isInteger){
					intregex = /^[0-9]*$/;
					int_msg = "intero ";
				}
				else{
					intregex = /^[0-9]*((\.|,)[0-9][0-9]?)?$/;
					int_msg = "";
					test_var = test_var.replace(RE_CROP_THOUSANDS_SEPARATOR, "");
					// Rimpiazza il separatore decimale col punto
					test_var = test_var.replace(DECIMAL_SEPARATOR, ".");
				}
				var match = test_var.match(intregex);
				if(match != null){
					var ValueElement = parseFloat(test_var);
					var aggiunta = 0; //risolve problema della stampa del punto ogni volta che si controlla un intero
					if (isNaN(ValueElement) || ((CurrElement.min != null) && (ValueElement < CurrElement.min)) ||
					((CurrElement.max != null) && (ValueElement > CurrElement.max)) || ((CurrElement.lunghezza != null)&&(CurrElement.value.length != CurrElement.lunghezza))){
						if (CurrElement.description != null){
							errors += "- Il campo \"" + CurrElement.description + "\" deve essere un numero";
							aggiunta = 1;
						}
						else{
							errors += "- Il campo \"" + CurrElement.name + "\" deve essere un numero";
							aggiunta = 1;
						}
						if(CurrElement.min != null) errors += " maggiore di " + CurrElement.min;
						if((CurrElement.max != null) && (CurrElement.min != null)){
							errors += " e minore di " + CurrElement.max;
						}
						else if(CurrElement.max != null){
							errors += " minore di " + CurrElement.max;
						}
						if(ValueElement.length != CurrElement.lunghezza){
							errors += " e deve essere composto da " + CurrElement.lunghezza + " cifre";
						}
					}
				}
				else{
					if (CurrElement.description != null){
						errors += "- Il campo \"" + CurrElement.description + "\" deve essere un numero " + int_msg + "in forma corretta";
						aggiunta = 1;
					}
					else{
						errors += "- Il campo \"" + CurrElement.name + "\" deve essere un numero " + int_msg + "in forma corretta";
						aggiunta = 1;
					}
				}
				if(aggiunta == 1){
					errors += ".\n";
				}
			}
			//Memorizza i campi di tipo password
			if (CurrElement.type == "password"){
				pwdArray[pwdArray.length] = CurrElement.value;
				if(CurrElement.minLength != null){
					pwd_len = CurrElement.minLength;
				}
			}
      //Verifica i campi di tipo Float
      if (CurrElement.isFloat != null){
				// Esegue il trim ed elimina il separatore delle migliaia
				test_var = test_var.replace(RE_LTRIM, "");
				test_var = test_var.replace(RE_RTRIM, "");
				// Esegue la sostituzione del separatore delle migliaia solo alla
				// sinistra del separatore decimale se esiste
				if(test_var.indexOf(DECIMAL_SEPARATOR) != -1){
					tmp_01 = test_var.substr(0, test_var.indexOf(DECIMAL_SEPARATOR));
					tmp_02 = test_var.substr(test_var.indexOf(DECIMAL_SEPARATOR));
					test_var = tmp_01.replace(RE_CROP_THOUSANDS_SEPARATOR, "") + tmp_02;
				}
				else{
					test_var = test_var.replace(RE_CROP_THOUSANDS_SEPARATOR, "");
				}
				
				// Rimpiazza il separatore decimale col punto
				test_var = test_var.replace(DECIMAL_SEPARATOR, ".");
         match = !isNaN(test_var);
         if(!match){
           if (CurrElement.description != null){
             errors += "- Il campo \"" + CurrElement.description + "\" non \350 un valore numerico valido.\n";
           }
           else{
             errors += "- Il campo \"" + CurrElement.name + "\" non \350 un valore numerico valido.\n";
           }
         }
      }

      //Verifica i campi Partita iva
			var chk_picf = false;
      if(CurrElement.isPiva != null){
				if(CurrElement.value.match(/^itn:.+/i)){
					chk_picf = false;
				}
				else{
					chk_picf = !checkPartitaIva(CurrElement); //funzione in cod_fisc.js
					chk_picf = chk_picf && !checkCF(CurrElement); //funzione in cod_fisc.js
				}
			}
      if(chk_picf == true){
        if(CurrElement.description != null){
           errors += "- Il campo \"" + CurrElement.description + "\" non ha una forma corretta.\n";
        }
        else{
           errors += "- Il campo \"" + CurrElement.name + "\" non ha una forma corretta.\n";
        }
     }
			
			//Verifica i campi di tipo e-mail
			if (CurrElement.isMail != null){
        var mailErr = true;
        var trim = / /g;
				var appoMail = CurrElement.value.replace(trim, "");
        var mailregex=/.+@.+\..+/;
        var match = appoMail.match(mailregex);
				if (!match){
					if (CurrElement.description != null){
						errors += "- Il campo \"" + CurrElement.description + "\" non \350 un indirizzo e-mail valido.\n";
					}
					else{
						errors += "- Il campo \"" + CurrElement.name + "\" non \350 un indirizzo e-mail valido.\n";
					}
				}
			}
			
			//Verifica i campi di tipo data
			if (CurrElement.isDate != null){
				var dateErr = true;
				var buf_regexp = DATE_REGEXP;
				var dateregex = new RegExp(buf_regexp, "");
				var match = CurrElement.value.match(dateregex);
				if(match){
					var tmpdate = new Date(parseInt(match[3], 10), parseInt(match[2], 10) - 1, parseInt(match[1], 10));
					if (tmpdate.getDate() == parseInt(match[1], 10) && tmpdate.getFullYear() == parseInt(match[3], 10) && (tmpdate.getMonth()+1) == parseInt(match[2], 10)){
						dateErr = false;
					}
				}
				if (dateErr){
					if (CurrElement.description != null){
						errors += "- Il campo \"" + CurrElement.description + "\" non \350 una data valida espressa nel formato \"" + DATE_MASK + "\".\n";
					}
					else{
						errors += "- Il campo \"" + CurrElement.name + "\" non \350 una data valida espressa nel formato \"" + DATE_MASK + "\".\n";
					}
				}
			}
		}
		//Verifica le caselle a discesa
		else if (((CurrElement.type == "select-one") || (CurrElement.type == "select-multiple")) && CurrElement.validate){
			selSelected = false;
			if (CurrElement.options.length > 0){
				for (var CountOpt = 0; CountOpt < CurrElement.options.length; CountOpt++){
					if ((CurrElement.options[CountOpt].selected) && (CurrElement.options[CountOpt].value != "")){
						selSelected = true;
						break;
					}
				}
			}
			else{
				selSelected = true;
			}
			if (!selSelected){
				if (CurrElement.description != null){
					errors += "- Non \350 stata selezionata alcuna voce per il campo \"" + CurrElement.description + "\".\n";
				}
				else{
					errors += "- Non \350 stata selezionata alcuna voce per il campo \"" + CurrElement.name + "\".\n";
				}
			}
		}
	}
	
	//Verifica i campi di tipo password
	if (pwdArray.length > 0){
		var pwdOne = pwdArray[0];
		var pwd_err = false;
		for (var CountPwd = 1; CountPwd < pwdArray.length; CountPwd++){
			if (pwdArray[CountPwd] != pwdArray[0]){
				errors += "- Le password inserite non coincidono.\n";
				pwd_err = true;
			}
		}
		if(!pwd_err){
            var pwdregex = /^[0-9a-zA-Z]*$/;
			if((pwdOne.length < pwd_len) || (!pwdOne.match(pwdregex))){
				errors += "- La password deve essere costituita di almeno " + pwd_len + " caratteri alfanumerici.\n";
			}		
		}
	}
	
	//Se non ci sono errori esce con successo
	if (!empty_fields && !errors && selSelected && (GLOBAL_VALIDATION_ERROR_MSG == "")){
		return(true);
	}
	
	//Stampa il messaggio di errore
	msg = "I dati non possono essere inviati:\n\n"
	if (empty_fields){
		msg += "- I seguenti campi obbligatori risultano vuoti:" + empty_fields + "\n";
		if (errors) msg += "\n";
	}
	msg += errors + GLOBAL_VALIDATION_ERROR_MSG;
	alert(msg);
	return(false);
}

//
// Verifica se la stringa e' composta di soli spazi
//
function IsBlank(strParam){
	return(strParam.match(/^\s*$/));
}

//
// Validazione data
//
function isDate(param){
    var dateErr = true;
    var buf_regexp = DATE_REGEXP;
		var dateregex = new RegExp(buf_regexp, "");
    var match = param.match(dateregex);
    if (match) {
			var tmpdate = new Date(parseInt(match[3], 10), parseInt(match[2], 10)-1, parseInt(match[1], 10));
			if(tmpdate.getDate() == parseInt(match[1], 10) && tmpdate.getFullYear() == parseInt(match[3], 10) && (tmpdate.getMonth()+1) == parseInt(match[2], 10)){
				dateErr = false;
			}
    }
    return(!dateErr);
}

//
// Confronta due date restituendo la differenza in giorni (dateFrom - dateTo)
// (Utilizza la funzione isDate())
// interval: intervallo di misurazione (giorni = "d", ore = "h", minuti = "m", secondi = "s")
// dateFrom: data di partenza
// dateTo: (opzionale) data di differenza (se omessa vale la data corrente)
// rounding: arrotondamento
//
function dateDiff(interval, dateFrom, dateTo, rounding){
    if(arguments.length == 2){
        var oggi = new Date();
        dateTo = oggi.getDate() + "/" + (oggi.getMonth() + 1) + "/" + oggi.getFullYear();
    }
    else if(arguments.length == 3){
        rounding = false;
    }
    else if(arguments.length < 2){
        alert("Errato numero di parametri passato alla funzione dateDiff");
        return(null);
    }
    if(!isDate(dateFrom) || !isDate(dateTo)){
        alert("I parametri passati alla funzione dateDiff non rispettano il formato \"" + DATE_MASK + "\"");
        return(null);
    }
		var buf_regexp = DATE_REGEXP;
		var idateregex = new RegExp(buf_regexp, "");
		var imatch = dateFrom.match(idateregex);
    var dateFromD = new Date(parseInt(imatch[3], 10), parseInt(imatch[2], 10) - 1, parseInt(imatch[1], 10));
    var imatch = dateTo.match(idateregex);
    var dateToD = new Date(parseInt(imatch[3] , 10), parseInt(imatch[2], 10) - 1, parseInt(imatch[1], 10));
    var number = dateFromD - dateToD ;
    switch (interval){
        case 'd': case 'D':
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
            alert("Intervallo passato alla funzione dateDiff non valido.") ;
            return(null);
    }
    return(iOut);
}

//
// Download aggiornamento
//
function downloadStart(IdAgg){
	var ErrCode = 0;
	if(!(dbox = document.getElementById("box_download"))){ErrCode += 1;}
	if(!(ifbox = document.getElementById("if_download"))){ErrCode += 2;}
	if((stop = document.body.scrollTop) == undefined){stop = 0; ErrCode += 4;}
	if((sleft = document.body.scrollLeft) == undefined){sleft = 0; ErrCode += 8;}
	if((wwidth = document.body.clientWidth) == undefined){wwidth = 1000; ErrCode += 16;}
	if((wheight = document.body.clientHeight) == undefined){wheight = 550; ErrCode += 32;}
	box_left = sleft + ((wwidth - 300) / 2);
	box_top = stop + ((wheight - 180) / 2);

	if((ErrCode & 2) == 2){
		alert("Impossibile avviare il download dell'aggiornamento richiesto.\nVerificare che il browser in uso supporti i requisiti minimi necessari all'uso di questa Area Riservata.\n\nIl codice di errore \350: 0X" + ErrCode.toString(16));
	}
	else{
		ifbox.src = "download-update.asp?idAggiornamento_Download=" + IdAgg;
		if((ErrCode == 0) || ((ErrCode & 1) == 0)){
			dbox.style.left = box_left + "px";
			dbox.style.top = box_top + "px";
			dbox.style.display = "inline";
            setTimeout("downloadEnd();", 7000);
		}
		if(ErrCode != 0){
			alert("Il download partir\340 a breve.\n\nQualora il download non dovesse partire in automatico comunicare il seguente codice di errore: 0X" + ErrCode.toString(16));
		}
	}
}

//
// End doenload
//
function downloadEnd(){
	if(dbox = document.getElementById("box_download")){
			dbox.style.display = "none";
			dbox.style.left = "-400px";
			dbox.style.top = "-200px";
	}
}

//
// Funzione di gestione tab
//
function SelectTab(tab){
	var ctab = 1;
	while(curr = document.getElementById("TAB_" + ctab)){
		// Nasconde o visualizza eventuali elementi correlati al tab corrente
		var ctab_child = 1;
		while(curr_child = document.getElementById("TAB_" + ctab + "_" + ctab_child)){
			if(tab == ctab){
				curr_child.style.display = "";
			}
			else{
				curr_child.style.display = "none";
			}
			ctab_child++;
		}
		// Nasconde o visualizza il tab corrente e cambia le immagini
		var img = document.getElementById("IMG_TAB_" + ctab);
		var img_src = img.src;
		if(tab == ctab){
			curr.style.display = "";
			img.src = img_src.replace(/_disabled.gif$/gi, ".gif");
		}
		else{
			curr.style.display = "none";
			img_src = img_src.replace(/_disabled\.gif$/gi, ".gif");
			img.src = img_src.replace(/\.gif$/gi, "_disabled.gif");
		}
		ctab++;
	}
}

//
// Crea l'IFRAME per l'apertura del calendario
//
var CALENDAR_IFRAME = false;
function initializeCalendar(idcampo){
	var page = "/popup_calendar.job?iframe=true&idcampo=" + idcampo;
	if(!(document.getElementById("calendar")) && document.createElement){
		var tempIFrame = document.createElement("IFRAME");
		tempIFrame.setAttribute("id","calendar");
		tempIFrame.setAttribute("scrolling","no");
		tempIFrame.setAttribute("frameborder","0");
		tempIFrame.style.position = "absolute";
		tempIFrame.style.left = "0px";
		tempIFrame.style.top = "0px";
		tempIFrame.style.width = "202px";
		if(document.all){
			tempIFrame.style.height = "186px";
		}
		else{
			tempIFrame.style.height = "185px";
		}
		tempIFrame.style.border = "0";
		tempIFrame.style.display = "none";
		IFrameObj = document.body.appendChild(tempIFrame);
		var cal = document.getElementById("calendar");
		if(cal) {
			CALENDAR_IFRAME = true;
			cal.src = page;
		}
	}
}

// Chiude il calendario aperto in IFRAME
function closeCalendar(){
	var cal = document.getElementById("calendar");
	if(cal){
		cal.style.display = "none";
	}
}

// Gestisce l'apertura del calendario
function openData(ev, leftS, oldy, idcampo){
	CLICK_F = true;
	getWindowSize();
	getWindowScroll();
	var offset_x = 0;
	if(window.screenLeft){
		offset_x = window.screenLeft;
	}
	else if(window.screenX){
		offset_x = window.screenX;
	}
	leftS -= offset_x;
	var page = "/popup_calendar.job?idcampo=" + idcampo;
	if(ev.pageY){topS = ev.pageY + 0 + 10; }
	else{topS = ev.clientY + WINDOW_SCROLLY + 10;}
	// Tenta di aprire il calendario nell'iframe...
	initializeCalendar(idcampo);
	var cal = document.getElementById("calendar");
	if(cal){
		var doc;
	  if(cal.contentDocument){
	    doc = cal.contentDocument;  // NS6
	  }else if(cal.contentWindow){
	    doc = cal.contentWindow.document; // IE5.5 - IE6
	  }else if(cal.document){
	    doc = cal.document; // IE5
	  }
		if(doc && doc.frmcalendario && doc.frmcalendario.idcampo){
			doc.frmcalendario.idcampo.value = idcampo;
		}
		cal.style.left = (leftS + WINDOW_SCROLLX) + "px";
		cal.style.top = topS + "px";
		cal.style.display = "inline";
	}
	else{
		// ...altrimenti lo apre in una popup
   	var dx = 200;
   	var dy = 172;
   	var winOpen = window.open(page,"calendario","width=" + dx +",height=" + dy + ",resizable=no,scrollbars=no,left=" + leftS + ",top=" + topS);
	}
}

// Pulisce il campo data
function emptyDateFormat(obj){
  if(obj.value == DATE_MASK){
    obj.value = "";
  }
}

// Riformatta il campo data
function fillDateFormat(obj){
  if(obj.value == ""){
    obj.value = DATE_MASK;
  }
}

//
// Impostazione dimensione area visibile della finestra
//
var WINDOW_WIDTH = 0;
var WINDOW_HEIGHT = 0;
var WINDOW_SCROLLX = 0;
var WINDOW_SCROLLY = 0;

function getWindowSize(){
  if(typeof(window.innerWidth) == 'number'){
    //Non-IE
    WINDOW_WIDTH = window.innerWidth;
    WINDOW_HEIGHT = window.innerHeight;
		if(typeof(window.outerWidth) == 'number'){
	    WINDOW_WIDTH = WINDOW_WIDTH - (window.outerWidth - WINDOW_WIDTH) - 8;
		}
  }
	else if((document.documentElement != 'undefined') && ((document.documentElement.clientWidth != 'undefined') && (document.documentElement.clientHeight != 'undefined')) && (document.documentElement.clientWidth != 0)){
    //IE 6+ in 'standards compliant mode'
    WINDOW_WIDTH = document.documentElement.clientWidth;
    WINDOW_HEIGHT = document.documentElement.clientHeight;
  }
	else if((document.body != 'undefined') && ((document.body.clientWidth != 'undefined') && (document.body.clientHeight != 'undefined'))){
    //IE 4 compatible
    WINDOW_WIDTH = document.body.clientWidth;
    WINDOW_HEIGHT = document.body.clientHeight;
  }
}

function getWindowScroll(){
  if(typeof(window.pageYOffset) == 'number'){
    //Netscape compliant
    WINDOW_SCROLLY = window.pageYOffset;
    WINDOW_SCROLLX = window.pageXOffset;
  }else if((document.body != 'undefined') && ((document.body.scrollLeft != 'undefined') && (document.body.scrollTop != 'undefined'))){
    //DOM compliant
    WINDOW_SCROLLY = document.body.scrollTop;
    WINDOW_SCROLLX = document.body.scrollLeft;
  }else if((document.documentElement != 'undefined') && ((document.documentElement.scrollLeft!= 'undefined') && (document.documentElement.scrollTop != 'undefined'))){
    //IE6 standards compliant mode
    WINDOW_SCROLLY = document.documentElement.scrollTop;
    WINDOW_SCROLLX = document.documentElement.scrollLeft;
  }
}

-->

