//============================================================+
//
// Begin       : 2008-01-03
// Last Update : 2005-04-09
// Author      : Magnosys S.r.l. [sviluppo@magnosys.net] [http://www.magnosys.net]
// Version     : 1.0.0.0001 [Beta]
// License     : Magnosys S.r.l. (Private License)
//               
//============================================================+

	function formatIndirizzo(percorso){
		percorso = percorso.replace("\\","/");
		return percorso;
	}

	function intercetta() {
	    for (var i=0; i<document.links.length; i++)
	        if (document.links[i].className=="blank") {
	            document.links[i].target="_blank";
	        }
	}

	// ************************************************************************************************************************************
	// ************************************************************************************************************************************
	// ************************************************************************************************************************************
	// funzioni per il calendario
		var oldLink = null;
		function setActiveStyleSheet(link, title) {
			var i, a, main;
			for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		    	if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
		      		a.disabled = true;
		      		if(a.getAttribute("title") == title){
		      			a.disabled = false;
		      		}
		    	}
		  	}
		  	if (oldLink){
		  		oldLink.style.fontWeight = 'normal';
		  	}
		  	oldLink = link;
		  	link.style.fontWeight = 'bold';
		  	return false;
		}

		// This function gets called when the end-user clicks on some date.
		function selected(cal, date) {
		  	cal.sel.value = date; // just update the date in the input field.
		  	if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3")){
		    	cal.callCloseHandler();
		    }
		}

		function closeHandler(cal) {
		  	cal.hide();                        // hide the calendar
		  	_dynarch_popupCalendar = null;
		}

		function showCalendar(id, format, showsTime, showsOtherMonths) {
		  	var el = document.getElementById(id);
		  	if (_dynarch_popupCalendar != null) {
		    	// we already have some calendar created
		    	_dynarch_popupCalendar.hide();                 // so we hide it first.
		  	}else{
		    	// first-time call, create the calendar.
		    	var cal = new Calendar(1, null, selected, closeHandler);
		    	// uncomment the following line to hide the week numbers
		    	// cal.weekNumbers = false;
		    	if (typeof showsTime == "string") {
		      		cal.showsTime = true;
		      		cal.time24 = (showsTime == "24");
		    	}
		    	if (showsOtherMonths) {
		      		cal.showsOtherMonths = true;
		    	}
		    	_dynarch_popupCalendar = cal;                  // remember it in the global var
		    	cal.setRange(1900, 2070);        // min/max year allowed.
		    	cal.create();
		  	}
		  	_dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
		  	_dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
		  	_dynarch_popupCalendar.sel = el;                 // inform it what input field we use
		  	
		  	_dynarch_popupCalendar.idInputDateVisible	= document.getElementById(id);
		  	_dynarch_popupCalendar.idInputDateHidden	= document.getElementById(id.substring(2));

		  	_dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar
		  			  	
		  	return false;
		}

		var MINUTE = 60 * 1000;
		var HOUR = 60 * MINUTE;
		var DAY = 24 * HOUR;
		var WEEK = 7 * DAY;

		function isDisabled(date) {
		  	var today = new Date();
		  	return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
		}

		function flatSelected(cal, date) {
		  	var el = document.getElementById("preview");
		  	el.innerHTML = date;
		}

		function showFlatCalendar() {
		  	var parent = document.getElementById("display");

		  	var cal = new Calendar(0, null, flatSelected);

		  	cal.weekNumbers = false;

		  	cal.setDisabledHandler(isDisabled);
		  	cal.setDateFormat("%A, %B %e");

		  	cal.create(parent);

		  	cal.show();
		}
		
		
	// ************************************************************************************************************************************
	// ************************************************************************************************************************************
	// ************************************************************************************************************************************			
	
	
	
	// ************************************************************************************************************************************
	
	// Funzione che permette di visualizzare un messaggio di informazione per l'utente
	function altMessageReplace(messaggio,obj,height,width,offsetX){
		if(messaggio!=null){
			if(height==null){
				height = 20;
			}
			if(width==null){
				width = 200;
			}
			if(offsetX==null){
				offsetX = 110;
			}
			var posX 			= findPosX(obj);
			var posY 			= findPosY(obj);						
			var div  			= document.createElement("div");
			posY				= posY - (height-16)/2;
			posX 				= posX + offsetX;
			div.style.position  = "absolute";
			div.id				= "idDivInfo";
			div.style.zIndex	= 999999999;
			div.style.top 		= posY+"px";
			div.style.left 		= posX+"px";
			div.style.height	= height+"px";
			div.style.width		= width+"px";
			div.innerHTML 		= messaggio;
			div.style.background= "#EDEDEE";
   			div.style.border 	= "4px solid #FFFFFF";
   			div.style.color 	= "#000000";			
			document.body.appendChild(div);
			
			window.setTimeout("removeElement('"+div.id+"')",1000);
		}
	}
	
	
	function removeElement(elementId) {
	  	var element = document.getElementById(elementId);
	  	document.body.removeChild(element);
	}


	// ************************************************************************************************************************************
	
	// Funzione per la gestione dei TAB
	function hideShowHTMLItem(objectID , parDisplay) {
	    htmlObject = document.getElementById(objectID);
	    if (htmlObject) {
	    	if(parDisplay == null){
		      	if (htmlObject.style.display == '') {	// hide
		        	htmlObject.style.display 	= 'none';
				}else {  								// show
					htmlObject.style.display 	= '';
				}
			}else{				
				htmlObject.style.display 	= parDisplay;
			}
		}
	}
	
	
	
	// permette di impostare la variabile hidden associata ad un checkbox con il valore 'T' o 'F' a seconda se il checkbox è ceccato o meno
	function setChkBoxTFHiddenValue(idChk){		
		if (document.getElementById(idChk).checked == true){
			document.getElementById(idChk.substring(4)).value = 'T';
		}else{
			document.getElementById(idChk.substring(4)).value = 'F';
		}
	} 
	
	
	
	
	// ************************************************************************************************************************************
	
	// permette di impostare la variabile hidden associata ad un checkbox con il valore '1' o '0' a seconda se il checkbox è ceccato o meno
	function setChkBox10HiddenValue(idChk){
		if (document.getElementById(idChk).checked == true){
			document.getElementById(idChk.substring(4)).value = '1';
		}else{
			document.getElementById(idChk.substring(4)).value = '0';
		}
	} 	
			
	
	
	// ************************************************************************************************************************************
	
	// funzione che effettua il redirect verso una specifica pagina web all'interno di uno specifico frame
	function MyRedirectToAFrame(urlBase,pageUrl,frameName){
		urlFinale = (urlBase + pageUrl);
		window.open(urlFinale.substring(9),frameName);
	}
	


	// ************************************************************************************************************************************

	
	// funzione che effetttua il redirect verso una specifica pagina web
	function MyRedirect(urlBase,pageUrl,parent){
		urlFinale = (urlBase + pageUrl);
		if(parent==null){			
			document.location.href = urlFinale.substring(9);
		}else{
			parent.document.location.href = urlFinale.substring(9);
		}
	}
		
	
	// ************************************************************************************************************************************
	
	// permette di impostare la variabile hidden associata ad un checkbox con il valore 'T' o 'F' a seconda se il checkbox è ceccato o meno
	function setChkBoxHiddenValue(idChk){
		if (document.getElementById(idChk).checked == true){
			document.getElementById(idChk.substring(4)).value = 'T';
		}else{
			document.getElementById(idChk.substring(4)).value = 'F';
		}
	} 
	
	
	
	
	// ************************************************************************************************************************************
	
	// permette di impostare la variabile hidden associata ad un checkbox con il valore '1' o '0' a seconda se il checkbox è ceccato o meno
	function setChkBoxIntegerHiddenValue(idChk){
		if (document.getElementById(idChk).checked == true){
			document.getElementById(idChk.substring(4)).value = '1';
		}else{
			document.getElementById(idChk.substring(4)).value = '0';
		}
	} 	
	
	
	
	// ************************************************************************************************************************************
	
	// permette di impostare la variabile hidden associata ad un checkbox con il valore 'S' o 'N' a seconda se il checkbox è ceccato o meno
	function setChkBoxSNHiddenValue(idChk){
		if (document.getElementById(idChk).checked == true){
			document.getElementById(idChk.substring(4)).value = 'S';
		}else{
			document.getElementById(idChk.substring(4)).value = 'N';
		}
	} 		
	
	
	
	// ************************************************************************************************************************************
	
	// permette di verificare che un valore sia float e poi lo tronca
	function troncaFloat(idTextFloat,nDecimal){
		if(nDecimal==null || nDecimal==''){
			nDecimal = 2;
		}
		try{
			var float = parseFloat(document.getElementById(idTextFloat).value);
			document.getElementById(idTextFloat).value = truncateFloat(float,nDecimal);
			if(document.getElementById(idTextFloat).value.indexOf("NaN") >= 0){
				document.getElementById(idTextFloat).value = '0.00';
			}
		}catch(err){
			alert('Valore non corretto');
			document.getElementById(idTextFloat).value = '0.00';
		}				
	}	
	
	
	
	// ************************************************************************************************************************************
	
	// permette di verificare che un valore sia float e poi lo tronca
	function troncaFloatInnerHTML(idTextFloat,nDecimal){
		if(nDecimal==null || nDecimal==''){
			nDecimal = 2;
		}
		try{
			var float = parseFloat(document.getElementById(idTextFloat).innerHTML);
			document.getElementById(idTextFloat).innerHTML = truncateFloat(float,nDecimal);
			if(document.getElementById(idTextFloat).innerHTML.indexOf("NaN") >= 0){
				document.getElementById(idTextFloat).innerHTML = '0.00';
			}
		}catch(err){
			alert('Valore non corretto');
			document.getElementById(idTextFloat).innerHTML = '0.00';
		}				
	}
			
			
	// ************************************************************************************************************************************
	
	
	// permette di verificare che un valore sia integer e poi lo tronca
	function troncaInteger(idTextInteger,whatIs){
		if(whatIs == null || whatIs == '' || whatIs == 'undefined'){
			whatIs = 'number';
		}				
		try{
			var integer = parseInt(document.getElementById(idTextInteger).value);
			document.getElementById(idTextInteger).value = truncateInteger(integer);			
			if (document.getElementById(idTextInteger).value == 'NaN'){
				if(whatIs == 'integer'){
					document.getElementById(idTextInteger).value = '';
				}else{
					document.getElementById(idTextInteger).value = '0';
				}				
			}
		}catch(err){
			alert('Valore non corretto');
			document.getElementById(idTextInteger).value = '0';
		}				
	}
			
			
	// ************************************************************************************************************************************
	
	// tronca il valore passato in input allo stato Integer (VALIDO SOLO PER I CAMPI DI RICERCA POP UP VELOCI)
	function truncateInteger_POPUPVELOCI(num) {
		string = "" + num;
		if (string.indexOf('.') == -1){
			if(isNaN(parseInt(num))){
				if(trim(num)==''){
					return '0';
				}else{
					return '';
				}
			}else{
         		return string;
         	}
		}else{
			seperation = string.indexOf('.');
			return string.substring(0 , seperation);
		}
	}
	
	
	// ************************************************************************************************************************************
	
					
	// tronca il valore passato in input allo stato Float (VALIDO SOLO PER I CAMPI DI RICERCA POP UP VELOCI)
	function truncateFloat_POPUPVELOCI(num) {
		string = "" + num;
		if (string.indexOf('.') == -1){
			if(isNaN(parseFloat(num))){
				if(trim(num)==''){
					return '0.00';
				}else{
					return '';
				}
			}else{
         		return string + '.00';
         	}
         	
		}
		seperation = string.length - string.indexOf('.');
                 
		if (seperation > 3){
			return string.substring(0,string.length-seperation+3);
		}else{ 
			if (seperation == 2){
				return string + '0';
			}else{
				return string;
			}
		}		
	}
	
	
	
	// ************************************************************************************************************************************	
	
	
	// tronca il valore passato in input allo stato Integer
	function truncateInteger(num,arrotonda) {
		if(arrotonda=='undefined' || arrotonda==null || arrotonda=='null' || arrotonda=='false'){
			string = "" + num;
			if (string.indexOf('.') == -1){
	         	return string;
			}else{
				seperation = string.indexOf('.');
				return string.substring(0 , seperation);
			}
		}else{
			string = "" + num;
			if (string.indexOf('.') == -1){
	         	return string;
			}else{
				seperation = string.indexOf('.');
				var primoDecimale = string.substring(seperation+1,seperation+2);
				if(parseInt(primoDecimale)<5){
					return parseInt(string.substring(0 , seperation));
				}else{
					return parseInt(string.substring(0 , seperation))+1;
				} 				
			}
		}
	}
	
	
	// ************************************************************************************************************************************
	
					
	// tronca il valore passato in input allo stato Float
	function truncateFloat(num,nDecimal) {
		string = "" + num;
		if (string.indexOf('.') == -1){
			switch(nDecimal){
				case 3:
						return string + '.000';
					break;
				default:
						return string + '.00';
					break;
			}
		}
		seperation = string.length - string.indexOf('.');
		
		switch(nDecimal){
			case 3:
					if (seperation > 4){
						var quartoDecimale = string.substring(string.length-seperation+4,string.length-seperation+5);
						if(quartoDecimale>='5'){
							var numeroInFloat 	= string.substring(0,string.length-seperation+4);
							//numeroInFloat 		= numeroInFloat + 0.001;
							return truncateFloat(numeroInFloat,3);
						}else{
							return string.substring(0,string.length-seperation+4);
						}
					}else{
						switch(seperation){
							case 3:
										return string + '0';
								break;
							case 2:
										return string + '00';
								break;
							default:
										return string;
								break;		
						}
					}
				break;
			default:
					if (seperation > 3){
						var terzoDecimale = string.substring(string.length-seperation+3,string.length-seperation+4);
						if(terzoDecimale>='5'){
							var numeroInFloat = parseFloat(string.substring(0,string.length-seperation+3));
							numeroInFloat = parseFloat(numeroInFloat + parseFloat(0.01));	
							return truncateFloat(numeroInFloat);
						}else{
							return string.substring(0,string.length-seperation+3);
						}
					}else{ 
						if (seperation == 2){
							return string + '0';
						}else{
							return string;
						}
					}
				break;
		}
	}
	
	
	function roundTo(value, decimalpositions){
	     var i 	= value * Math.pow(10,decimalpositions);
	     i 		= Math.round(i);
	     return i / Math.pow(10,decimalpositions);
	}

	// ************************************************************************************************************************************
	
	// Funzione trim in javascript
	function trim(stringa){
		if (stringa != ''){
			while (stringa.substring(0,1) == '\n'){
				stringa = stringa.substring(1, stringa.length);
			}
			while (stringa.substring(0,1) == ' '){
				stringa = stringa.substring(1, stringa.length);
			}
			while (stringa.substring(stringa.length-1, stringa.length) == '\n'){
				stringa = stringa.substring(0,stringa.length-1);
			}
			while (stringa.substring(stringa.length-1, stringa.length) == ' '){
				stringa = stringa.substring(0,stringa.length-1);
			}
		}
		return stringa;
	}
	

	// ************************************************************************************************************************************
	
	function WindowSize(){
		var w = 0;
		var h = 0;
					
		if(!window.innerWidth){
			//IE			
			if(!(document.documentElement.clientWidth == 0)){
				//strict mode
				w = document.documentElement.clientWidth;
				h = document.documentElement.clientHeight + 88;
			}else{
				//quirks mode
				w = document.body.clientWidth;
				h = document.body.clientHeight + 88;
			}
		}else{
			//w3c
			w = window.innerWidth;
			h = window.innerHeight;
		}
		return {width:w,height:h};
	}
	
	
	function Centering(width , height){
		if(width == null){
			width = 0;
		}
		if(height == null){
			height = 0;
		}
	
		var windowSize = WindowSize();
		var _x = 0;
		var _y = 0;
		var offsetX = 0;
		var offsetY = 0;
			
		if(!window.pageYOffset){
			//IE			
			if(!(document.documentElement.scrollTop == 0)){
				//strict mode
				offsetY = document.documentElement.scrollTop;
				offsetX = document.documentElement.scrollLeft;
			}else{
				//quirks mode
				offsetY = document.body.scrollTop;
				offsetX = document.body.scrollLeft;
			}
		}else{
			//w3c
			offsetX = window.pageXOffset;
			offsetY = window.pageYOffset;
		}
			
		_x = ((windowSize.width-width)/2)+offsetX;
		_y = ((windowSize.height-height)/2)+offsetY;
	
		return{x:_x,y:_y};
	}
	
	
	function findPosX(obj){
    	var curleft = 0;
    	if(obj.offsetParent){
        	while(1){
          		curleft += obj.offsetLeft;
          		if(!obj.offsetParent){
            		break;
            	}
          		obj = obj.offsetParent;
        	}
    	}else{ 
    		if(obj.x){
        		curleft += obj.x;
        	}
        }
    	return curleft;
  	}

  	
  	function findPosY(obj){
    	var curtop = 0;
    	if(obj.offsetParent){
        	while(1){
          		curtop += obj.offsetTop;
          		if(!obj.offsetParent){
            		break;
            	}
          		obj = obj.offsetParent;
        	}
    	}else{ 
    		if(obj.y){
        		curtop += obj.y;
        	}
        }
    	return curtop;
  	}
	
		
		
	// funzione che ritorna le dimensioni del Document corrente
	function DocumentSize(){
		var _w = 0;
		var _h = 0;
		var scnWid;
		var scnHei;
		if (self.innerHeight){
			// all except Explorer
			_w = self.innerWidth - 35;
			_h = self.innerHeight;
		}else{
			if (document.documentElement && document.documentElement.clientHeight){
				// Explorer 6 Strict Mode				
				_w = document.documentElement.offsetWidth - 40;
				_h = document.documentElement.offsetHeight;								
			}else{
				if (document.body){
					// other Explorers
					_w = document.body.offsetWidth - 40;
					_h = document.body.offsetHeight;						
				}
			}
		}
		return{width:_w,height:_h}; 
	}
	
	// ************************************************************************************************************************************	
	// apre una finestra di PopUp ma per effettuare una ricerca veloce del dato
	function RicercaVeloce(urlBase , pagina , campoChiaveDB , valoreCampoChiave , tabella , campiTabella , nomeCampoDBRic , nomeCampoFormRic , nomePopUp){
		if(valoreCampoChiave!=null && valoreCampoChiave!=''){
			if(nomePopUp == ''){
				nomePopUp = "popUpRicVel";
			}
			pagina = pagina 
					+ '?campoChiave='			+ campoChiaveDB			// nome su DB del campo chiave di ricerca veloce (il codice univoco)
					+ '&valoreCampoChiave='		+ valoreCampoChiave		// valore che deve assumere il campo chiave
					+ '&tabella='				+ tabella				// tabella di riferimento per la ricerca veloce
					+ '&campiTabella='			+ campiTabella			// elenco dei campi che la tabella deve avere per poi farne l'import
					+ '&nomeCampoDBRic='		+ nomeCampoDBRic		// id del campo in questo specifico file
					+ '&nomeCampoFormRic='		+ nomeCampoFormRic		// id del campo in questo specifico file
					;	
			MyRedirectToAFrame(urlBase,pagina,'ricFrame');
		}else{
			return false;
		}
	}
	
	// ************************************************************************************************************************************	
	// apre una finestra di PopUp ma per effettuare una ricerca di doppioni
	function RicercaDoppione(urlBase , pagina , campoDB , valoreCampoDB , tabella , nomePopUp , nomeCampoFormRic , campoKeyDB , valoreCampoKeyDB){
		if(valoreCampoDB!=null && valoreCampoDB!=''){
			if(campoKeyDB == ''){
				campoKeyDB = 'nogo';
			}
			if(valoreCampoKeyDB == ''){
				valoreCampoKeyDB = 'nogo';
			}
			if(nomePopUp == ''){
				nomePopUp = "popUpRicDoppione";
			}
			
			pagina = pagina 
					+ '?campoDB='			+ campoDB			// nome del campo su DB da controllare
					+ '&valoreCampoDB='		+ valoreCampoDB		// valore da controllare
					+ '&tabella='			+ tabella			// tabella di riferimento per la ricerca doppione
					+ '&nomeCampoFormRic='	+ nomeCampoFormRic	// nome campo form opener da controllare
					+ '&campoKeyDB='		+ campoKeyDB		// nome campo chiave su DB per il controllo sulla modifica
					+ '&valoreCampoKeyDB='	+ valoreCampoKeyDB	// valore campo chiave su DB per il controllo sulla modifica
					;
			MyRedirectToAFrame(urlBase,pagina,'ricFrame');
		}else{
			return false;
		}
	}
	

	// ************************************************************************************************************************************	
	// apre una finestra di PopUp
	function Popup(pagina , campoRicerca , tabella , campiTabella , nomeCampiTabella, nomeCampoForm , titoloPagina , nomePopUp , width , height , 
					paginaNuovo , widthPaginaNuovo, heightPaginaNuovo , statoTemplateCorrente , statoTemplatePassato , 
					campiDaValorizzare , campoDefaultRicerca , campiDataDaFormattare , valoreDefaultRicerca) {
		if(nomePopUp == ''){
			nomePopUp = "popUpPage";
		}
		
		if(paginaNuovo == ''){
			paginaNuovo = '#nogo';
		}
		
		if(widthPaginaNuovo == ''){
			widthPaginaNuovo = '800';
		}
		
		if(heightPaginaNuovo == ''){
			heightPaginaNuovo = '600';
		}
		
		if(campoDefaultRicerca=='' || campoDefaultRicerca=='undefined' || campoDefaultRicerca==undefined){
			campoDefaultRicerca = '#nogo';
		}
		
		if(valoreDefaultRicerca=='' || valoreDefaultRicerca=='undefined' || campoDefaultRicerca==undefined){
			valoreDefaultRicerca = '#nogo';
		}
											
		pagina = pagina 
				+ '?tabella=' 				+ tabella 				//nome della tabella che la pagina di popUp deve aprire
				+ '&campoRicerca=' 			+ campoRicerca 			//campo che la pagina di popUp deve ritornare
				+ '&campiTabella=' 			+ campiTabella 			//elenco campi della tabella da visualizzare nella popUp
				+ '&nomiCampiTabella='	 	+ nomeCampiTabella 		//nomi da associare all'elenco campi della tabella da visualizzare nella popUp
				+ '&idCampoForm=' 			+ nomeCampoForm			//id del campo in questo specifico file
				+ '&titoloPagina=' 			+ titoloPagina			//titolo della pagina di popUp
				+ '&paginaNuovo=' 			+ paginaNuovo			//pagina che deve essere aperta quando si fa nuovo
				+ '&widthPaginaNuovo=' 		+ widthPaginaNuovo		//width pagina nuovo
				+ '&heightPaginaNuovo='		+ heightPaginaNuovo		//height pagina nuovo
				+ '&statoTemplateCorrente=' + statoTemplateCorrente	//stato del template in questo momemento
				+ '&statoTemplatePassato='	+ statoTemplatePassato	//stato del template al passo precedente
				+ '&campiDaValorizzare=' 	+ campiDaValorizzare    //indica di quali campi di "campoRicerca" la PopUp deve restituire il valore
				+ '&nomeCampoRicerca='   	+ campoDefaultRicerca		
				+ '&campiDataDaFormattare=' + campiDataDaFormattare	//indica la posizione dei campi Data da formattare
				+ '&valoreDefaultRicerca=' 	+ valoreDefaultRicerca	//indica qual'è il valore per il campo di default per la ricerca
				;	
			
		var w = 800;	
		if(width != null){
			w = width;
		}
		var h = 600;
		if(height != null){
			h = height;
		}				
		var point = Centering(w,h);
		var l = point.x;
   		var t = point.y;
   		var rand_no = parseInt(Math.random() * 10000);
    	window.open(pagina,rand_no,"width=" + w + ",height=" + h + ",top=" + t + ",left=" + l + ",status=yes, menubar=no, toolbar=no, scrollbars=yes, resizable=yes");      			
	}
			
	// apre una finestra di popUp semplicissima		
	function PopupSemplicissima(pagina , nomePopUp , width , height , top , left) {
		if(nomePopUp == ''){
			nomePopUp = "popUpPageSemplicissima";
		}					
			
		var w = 800;	
		if(width != null){
			w = width;
		}
		var h = 600;
		if(height != null){
			h = height;
		}
		if(top != null && left != null){
			var l = left;
   			var t = top;
		}else{				
			var point = Centering(w,h);
			var l = point.x;
   			var t = point.y;
   		}
   		
   		var rand_no = parseInt(Math.random() * 10000);
    	window.open(pagina,rand_no,"width=" + w + ",height=" + h + ",top=" + t + ",left=" + l + ",status=yes, menubar=no, toolbar=no, scrollbars=yes, resizable=yes");      			
	}
	
	// Popup fancybox con dimensioni prestabilite
	function PopupFancyBox(pagina , width , height , onClosed) {
		var w = 800;
		var h = 600;
		
		$(document).width();
		
		if(width != null){
			w = width;
		}else{
			w = $(document).width();	
		}
		if(height != null){
			h = height;
		}else{
			h = $(document).height();
		}
		
		if(onClosed == null){
	   		$.fancybox({
				'type' 		: 'iframe'	,
				'width'		: w			,
				'height'	: h			,
				'href'		: pagina
			});
		}else{
	   		$.fancybox({
				'type' 		: 'iframe'	,
				'width'		: w			,
				'height'	: h			,
				'onClosed'	: onClosed	,
				'href'		: pagina
			});
		}
	}
	
	
	// cancella i dati provenienti da una finestra di popUp
	function EliminaDatiPopUp(campoText , campoHidden){
		document.getElementById(campoText).value = '';
		if (campoHidden != null && campoHidden != ''){
			document.getElementById(campoHidden).value = '';
		}
	}
	
	
	
	// ************************************************************************************************************************************
	
	
	// apre una seconda finestra di popUp 
	function PopupNew(pagina , campoRicerca , tabella , campiTabella , nomeCampiTabella, nomeCampoForm , nCampiVisibili) {				
		pagina = pagina 
				+ '?tabella=' + tabella 						//nome della tabella che la pagina di popUp deve aprire
				+ '&campoRicerca=' + campoRicerca 				//campo che la pagina di popUp deve ritornare
				+ '&campiTabella=' + campiTabella 				//elenco campi della tabella da visualizzare nella popUp
				+ '&nomiCampiTabella=' + nomeCampiTabella 		//nomi da associare all'elenco campi della tabella da visualizzare nella popUp
				+ '&idCampoForm=' + nomeCampoForm				//id del campo in questo specifico file
				+ '&nCampiVisibili=' + nCampiVisibili
				;	
		var w = 810;
		var h = 610;
   		var l = Math.floor((screen.width-w)/2);
 		var t = Math.floor((screen.height-h)/2);
		window.open(pagina,"popUpPageNew","width=" + w + ",height=" + h + ",top=" + t + ",left=" + l + ",status=yes, menubar=no, toolbar=no, scrollbars=yes, resizable=yes");      			
	}
	
	// ************************************************************************************************************************************
	
	// Funzione che prende in input una data scritta in inglese e la converte in una data scritta in italiano
	function dateInglToIta(dateIngl){
		dateIngl = trim(dateIngl);
		if(dateIngl != '' && dateIngl != null && dateIngl != 'undefined'){
			// 2008-11-21
			if(dateIngl.substring(4,5) == '-' && dateIngl.substring(7,8) == '-'){
				var anno 	= dateIngl.substring(0,4);
				var mese 	= dateIngl.substring(5,7);
				var giorno 	= dateIngl.substring(8,10);
				var dataIta = giorno + '/' + mese + '/' + anno;
				return dataIta;			
			}else{
				return dateIngl;
			}
		}else{
			return '';
		}
	}
	
	// Funzione che prende in input una data scritta in italiano e la converte in una data scritta in inglese
	function dateItaToIngl(dateIta){
		dateIta = trim(dateIta);
		if(dateIta != '' && dateIta != null && dateIta != 'undefined'){
			// 18/02/1983
			if(dateIta.substring(2,3) == '/' && dateIta.substring(5,6) == '/'){
				var anno 	= dateIta.substring(6,10);
				var mese 	= dateIta.substring(3,5);
				var giorno 	= dateIta.substring(0,2);
				var dataIngl = anno + '-' + mese + '-' + giorno;
				return dataIngl;			
			}else{
				return dateIta;
			}
		}else{
			return '';
		}
	}

	// ************************************************************************************************************************************
	
	// formatta la data in esame
	function formatData(idCampoData){		
		var campoVis = document.getElementById('r_' + idCampoData).value;
		if(campoVis.length==2 || campoVis.length==5){
			campoVis = campoVis + "/";
		}
		document.getElementById('r_' + idCampoData).value = campoVis;
		
		if(campoVis.length==10){
			controllaData(idCampoData,'1');
		}
	}
	
	// controlla la data in esame
	function controllaData(idCampoData , isNew){
		var campoVis = document.getElementById('r_' + idCampoData);
		var campoHid = document.getElementById(idCampoData);				 
		var data  	 = campoVis.value;
		data = trim(data);
						
		if( 
			(data.length == 10) // controllo che ci siano 10 caratteri
			 &&
			( (data.substring(2,3) == '/') && (data.substring(5,6) == '/') ) // controllo la presenza delle doppie barre
			 &&
			( (data.substring(0,2) <= '31') && (data.substring(0,2) > '0') ) 
			 && 
			( (data.substring(3,5) <= '12') && (data.substring(3,5) > '0') ) 
			 && 
			( (data.substring(6,10) <= '5000') && (data.substring(6,10) > '0') ) 
			 &&
			( 
			 data.substring(0,1) == '1' || data.substring(0,1) == '2' || data.substring(0,1) == '3' || data.substring(0,1) == '4' ||
			 data.substring(0,1) == '5' || data.substring(0,1) == '6' || data.substring(0,1) == '7' || data.substring(0,1) == '8' ||
			 data.substring(0,1) == '9' || data.substring(0,1) == '0'  
			)
			 &&
			( 
			 data.substring(1,2) == '1' || data.substring(1,2) == '2' || data.substring(1,2) == '3' || data.substring(1,2) == '4' ||
			 data.substring(1,2) == '5' || data.substring(1,2) == '6' || data.substring(1,2) == '7' || data.substring(1,2) == '8' ||
			 data.substring(1,2) == '9' || data.substring(1,2) == '0' 
			) 
			 &&
			( 
			 data.substring(3,4) == '1' || data.substring(3,4) == '2' || data.substring(3,4) == '3' || data.substring(3,4) == '4' ||
			 data.substring(3,4) == '5' || data.substring(3,4) == '6' || data.substring(3,4) == '7' || data.substring(3,4) == '8' ||
			 data.substring(3,4) == '9' || data.substring(3,4) == '0'  
			)
			 &&
			( 
			 data.substring(4,5) == '1' || data.substring(4,5) == '2' || data.substring(4,5) == '3' || data.substring(4,5) == '4' ||
			 data.substring(4,5) == '5' || data.substring(4,5) == '6' || data.substring(4,5) == '7' || data.substring(4,5) == '8' ||
			 data.substring(4,5) == '9' || data.substring(4,5) == '0' 
			)
			 &&
			( 
			 data.substring(6,7) == '1' || data.substring(6,7) == '2' || data.substring(6,7) == '3' || data.substring(6,7) == '4' ||
			 data.substring(6,7) == '5' || data.substring(6,7) == '6' || data.substring(6,7) == '7' || data.substring(6,7) == '8' ||
			 data.substring(6,7) == '9' || data.substring(6,7) == '0'  
			)
			 &&
			( 
			 data.substring(7,8) == '1' || data.substring(7,8) == '2' || data.substring(7,8) == '3' || data.substring(7,8) == '4' ||
			 data.substring(7,8) == '5' || data.substring(7,8) == '6' || data.substring(7,8) == '7' || data.substring(7,8) == '8' ||
			 data.substring(7,8) == '9' || data.substring(7,8) == '0' 
			) 
			 &&
			( 
			 data.substring(8,9) == '1' || data.substring(8,9) == '2' || data.substring(8,9) == '3' || data.substring(8,9) == '4' ||
			 data.substring(8,9) == '5' || data.substring(8,9) == '6' || data.substring(8,9) == '7' || data.substring(8,9) == '8' ||
			 data.substring(8,9) == '9' || data.substring(8,9) == '0'  
			)
			 &&
			( 
			 data.substring(9,10) == '1' || data.substring(9,10) == '2' || data.substring(9,10) == '3' || data.substring(9,10) == '4' ||
			 data.substring(9,10) == '5' || data.substring(9,10) == '6' || data.substring(9,10) == '7' || data.substring(9,10) == '8' ||
			 data.substring(9,10) == '9' || data.substring(9,10) == '0' 
			) 
		  ){
			// Data Corretta
			campoHid.value = campoVis.value.substring(6,10) 
							  + '-' +
							 campoVis.value.substring(3,5)
							  + '-' +
							 campoVis.value.substring(0,2);
			if(isNew == 1){
				campoHid.value = campoVis.value;
			}
		}else{
			// Formato data Incorretto
			if(data.length > 0){
				alert('Data Non Corretta');
			}
			campoVis.value = '';
			campoHid.value = '';
		}
	}
	
	// funzione che confronta 2 date e ritorna l'indice di quella più grande
	function confronta_data(data1, data2){
		if(data1!="" && data2!=""){
			data1	 = dateInglToIta(data1);
			data2	 = dateInglToIta(data2);
			if(data1!="" && data2!=""){
		        data1str = data1.substr(6)+data1.substr(3,2)+data1.substr(0,2);
				data2str = data2.substr(6)+data2.substr(3,2)+data2.substr(0,2);
		        if (data2str-data1str>0){
		            return 2;
		        }else{
		        	if (data2str-data1str<0){
						return 1;
					}else{
						return 0;
					}
		        }	    
		    }else{
		    	return -1;
		    }   
	    }else{
	    	return -1;
	    }
	}

	// Funzione che controlla se un particolare valore è settato
	function checkIfValueIsSet(value){
		var ritorno = false;
		if(		value		!= null
			&& 	trim(value) != ''
			&& 	trim(value) != 'null'
		){
			ritorno = true;
		}
		
		return ritorno;
	}
	

	// Funzione che controlla se una particolare data è settata
	function checkIfDataIsSet(value){
		var ritorno = false;
		if(		value		!= null
			&& 	trim(value) != '-'
			&& 	trim(value) != ''
			&& 	trim(value) != 'null'
		){
			ritorno = true;
		}
		
		return ritorno;
	}	
		
	
	// ************************************************************************************************************************************
	
	
	// formatta l'ora in esame
	function formatOra(idCampoOra){
		var campoVis = document.getElementById(idCampoOra).value;
		if(campoVis.length==2){
			campoVis = campoVis + ":";
		}
		document.getElementById(idCampoOra).value = campoVis;
	}
	
	// controlla l'ora in esame
	function controllaOra(idCampoOra){
		var campoOra = document.getElementById(idCampoOra);
		var ora = campoOra.value;				
		if( 
			(ora.substring(2,3) == ':')
			  &&
			( (ora.substring(0,2) < '24') && (ora.substring(0,2) >= '0') )
			  &&
			( (ora.substring(3,5) < '60') && (ora.substring(3,5) >= '0') )
		  	  &&
			( ora.substring(0,1) == '1' || ora.substring(0,1) == '2' || ora.substring(0,1) == '0' )
			  &&
			( 
			 ora.substring(1,2) == '1' || ora.substring(1,2) == '2' || ora.substring(1,2) == '3' || ora.substring(1,2) == '4' ||
			 ora.substring(1,2) == '5' || ora.substring(1,2) == '6' || ora.substring(1,2) == '7' || ora.substring(1,2) == '8' ||
			 ora.substring(1,2) == '9' || ora.substring(1,2) == '0' 
			) 
		  	  &&
			( 
			 ora.substring(3,4) == '1' || ora.substring(3,4) == '2' || ora.substring(3,4) == '3' || ora.substring(3,4) == '4' ||
			 ora.substring(3,4) == '5' || ora.substring(3,4) == '0'  
			)
			  &&
			( 
			 ora.substring(4,5) == '1' || ora.substring(4,5) == '2' || ora.substring(4,5) == '3' || ora.substring(4,5) == '4' ||
			 ora.substring(4,5) == '5' || ora.substring(4,5) == '6' || ora.substring(4,5) == '7' || ora.substring(4,5) == '8' ||
			 ora.substring(4,5) == '9' || ora.substring(4,5) == '0' 
			) 					
		  ){
		  // tutto ok, quindi non faccio niente
		}else{
			alert('Formato Ora non corretto');
			campoOra.value = '';
		}
	}
	
	
	// formatta il contenuto di un edit-text, di una text-are, ecc.. mettendo l'UPPER CASE, DOWN CASE, ecc..
	function formatUpperDownCASE(idCampo,tipoFormat){
		var scritta = document.getElementById(idCampo).value;
		switch(tipoFormat){
			case 'UPPER':
					document.getElementById(idCampo).value = scritta.toUpperCase();
				break;
			case 'DOWN':
					document.getElementById(idCampo).value = scritta.toLowerCase();
				break;
		}
	}
	
	// funzione che calcola la differenza in ore e minuti tra due ore
	function timeDiff( idTimeInizio, idTimeFine ){
		var timeInizio	= $('#'+idTimeInizio).val();
		var timeFine 	= $('#'+idTimeFine).val();
		if( trim(timeInizio)=='' || trim(timeFine)=='' ){
			//ora non inserita correttamente e quindi svuotata dalla funzione controllaOra
		}else{
			//converte a intero in base 10
			var oraInizio 	= parseInt( timeInizio.substring(0,2) , 10 );
			var oraFine 	= parseInt( timeFine.substring(0,2) , 10 );
			var minInizio 	= parseInt( timeInizio.substring(3,5) , 10 );
			var minFine 	= parseInt( timeFine.substring(3,5) , 10);
			if( oraFine < oraInizio){
				oraFine += 24;
			}
			if( oraFine == oraInizio){
				if( minFine < minInizio ){
					oraFine += 24;
				}
			}
			//converto i due orari in minuti
			var totMinInizio		= oraInizio*60+minInizio;
			var totMinFine			= oraFine*60+minFine;
			//differenza tra i due orari in minuti
			var totMinIntermedi 	= totMinFine-totMinInizio;
			
			//alert('oi: '+oraInizio+' mi: '+minInizio+' of: '+oraFine+' mf '+minFine+'      '+totMinInizio+' '+totMinFine+' '+totMinIntermedi);
			
			//riformatto in hh:mm per ritornare il valore
			var returnOra			= parseInt( totMinIntermedi/60 , 10);
			var returnMin			= parseInt( totMinIntermedi%60 , 10);
			if( returnOra < 10){returnOra='0'+returnOra;}
			if( returnMin < 10){returnMin='0'+returnMin;}
			return(returnOra+':'+returnMin);
		}
	}
	
	// funzione che calcola la differenza in ore, minuti e secondi tra due ore
	function timeDiffSec( idTimeInizio, idTimeFine ){
		var timeInizio	= $('#'+idTimeInizio).val();
		var timeFine 	= $('#'+idTimeFine).val();
		if( trim(timeInizio)=='' || trim(timeFine)=='' ){
			//ora non inserita correttamente e quindi svuotata dalla funzione controllaOra
		}else{
			//converte a intero in base 10
			var oraInizio 	= parseInt( timeInizio.substring(0,2) , 10 );
			var oraFine 	= parseInt( timeFine.substring(0,2) , 10 );
			var minInizio 	= parseInt( timeInizio.substring(3,5) , 10 );
			var minFine 	= parseInt( timeFine.substring(3,5) , 10);
			if( oraFine < oraInizio){
				oraFine += 24;
			}
			if( oraFine == oraInizio){
				if( minFine < minInizio ){
					oraFine += 24;
				}
			}
			//converto i due orari in minuti
			var totMinInizio		= oraInizio*60+minInizio;
			var totMinFine			= oraFine*60+minFine;
			//differenza tra i due orari in minuti
			var totMinIntermedi 	= totMinFine-totMinInizio;
			
			//alert('oi: '+oraInizio+' mi: '+minInizio+' of: '+oraFine+' mf '+minFine+'      '+totMinInizio+' '+totMinFine+' '+totMinIntermedi);
			
			//riformatto in hh:mm per ritornare il valore
			var returnOra			= parseInt( totMinIntermedi/60 , 10);
			var returnMin			= parseInt( totMinIntermedi%60 , 10);
			if( returnOra < 10){returnOra='0'+returnOra;}
			if( returnMin < 10){returnMin='0'+returnMin;}
			return(returnOra+':'+returnMin);
		}
	}
	
	
	// ************************************************************************************************************************************
	// FUNZIONI SPECIFICHE PER LA GESTIONE DEI PDF
	// ************************************************************************************************************************************	
	
	
	// apre la finestra di popUp con la stampa PDF del registro dei verbali
	function PDFPopup(pagina) {				
		var w = screen.width;
		var h = screen.height;
		var l = 0;
   		var t = 0;
    	window.open(pagina,'filePDF',"width=" + w + ",height=" + h + ",top=" + t + ",left=" + l + ",status=yes, menubar=no, toolbar=no, scrollbars=yes, resizable=yes");      			
	}
	
	// ************************************************************************************************************************************	
	
	
	// ************************************************************************************************************************************
	// FUNZIONI SPECIFICHE PER LA GESTIONE DELLE ICONE PER I FILES
	// ************************************************************************************************************************************	
	
	// Funzione che data in input un'estensione ritorna il nome della relativa icona immagine associata
	function getNameOfImageByFileExtension(nomeFile){
		var nomeImmagine = '';
		if(nomeFile!=null && nomeFile!=''){
			var nomeImgLength			= nomeFile.length;
			var posOfPunto				= nomeFile.lastIndexOf('.');
			var estensioneFile 			= nomeFile.substring(posOfPunto);
			switch(estensioneFile){
				case '.exe':
								nomeImmagine = 'file_exe.png';
							break;
				case '.pdf':
								nomeImmagine = 'file_pdf.png';
							break;
				case '.doc':
								nomeImmagine = 'file_word.png';
							break;
				case '.zip':
								nomeImmagine = 'file_zip.png';
							break;
				case '.txt':
				case '.cnc':
				case '.cnc':
								nomeImmagine = 'file_generico.png';
							break;
				case '.png':
				case '.jpg':
				case '.jpeg':
				case '.gif':
								nomeImmagine = 'file_image.png';
							break;
			}
		}
		
		return nomeImmagine;
	}


////// Check tipologia chiamata
	
	function checktel(){
		var obj = document.getElementById('i_tipologia');
		if(obj.selectedIndex == 1)
			telefonata();
		if(obj.selectedIndex == 0) 
			teleassistenza();
	}
	
	function telefonata() 
	{ 
		if (document.getElementById) 
		{ // DOM3 = IE5, NS6 
			document.getElementById('attivitate').style.display = 'none';
			document.getElementById('attivitata').style.display = '';
		} 
		else 
		{ 
			if (document.layers) 
			{ // Netscape 4 
				document.attivitate.display = 'none';
				document.attivitata.display = '';
			} 
			else 
			{ // IE 4 
				document.all.attivitate.style.display = 'none';
				document.all.attivitata.style.display = '';
			} 
		} 
	}

	function teleassistenza() 
	{ 
		if (document.getElementById) 
		{ // DOM3 = IE5, NS6 
			document.getElementById('attivitate').style.display = '';
			document.getElementById('attivitata').style.display = 'none';
		} 
		else 
		{ 
			if (document.layers) 
			{ // Netscape 4 
				document.attivitate.display = '';
				document.attivitata.display = 'none';
			} 
			else 
			{ // IE 4 
				document.all.attivitate.style.display = '';
				document.all.attivitata.style.display = 'none';
			} 
		} 
	} 
	
	//funzione che somma i giorni ad una data
	function dateAdd(data, gg){
		data = dateInglToIta(data);
		var split_char = '/';
		var datasplit = data.split(split_char); 
		var newdata = new Date(datasplit[2], (datasplit[1] - 1), datasplit[0]);
		newdata.setDate(newdata.getDate() + parseInt(gg));
		var sGiorno = (newdata.getDate() < 10) ? "0" + newdata.getDate().toString() : newdata.getDate().toString(); 
		var sMese = (newdata.getMonth() < 9) ? "0" + (newdata.getMonth() + 1).toString() : (newdata.getMonth() + 1).toString();
		var sAnno = newdata.getFullYear().toString();
		var sDataCompleta = "".concat(sGiorno,split_char,sMese,split_char,sAnno);
		return sDataCompleta;
	}
	
	// funzione che apre una fancy box richiamando la pagina message.php di dialogo con l'utente
	function drawMessage(page , title , message , type , onClosed , width , height){
		//alert(''+page+'?title='+title+'&message='+message+'&type='+type +''+onClosed+width+height);
		$.fancybox( {
						'type' 				: 	'iframe'												,
						'width'				: 	width													,
						'height'			: 	height													,
						'href'				: 	page+'?title='+title+'&message='+message+'&type='+type	,
						'onClosed'			: 	onClosed												,
						'overlayOpacity'	:	0.3														,
						'showCloseButton'	:   false													,
						'transitionIn'		: 	'elastic'												,
						'transitionOut'		: 	'none'													,
						'modal'				:  	true													,
						'index'				:	Math.floor(Math.random()*11)
					});
		
	}
	
	// funzione che apre una fancy box richiamando la pagina chooseStampa.php di dialogo con l'utente
	function chooseStampa(page , title , message , type , onClosed , width , height){
		$.fancybox(	{
						'type' 				: 	'iframe'												,
						'width'				: 	width													,
						'height'			: 	height													,
						'href'				: 	page+'?title='+title+'&message='+message+'&type='+type	,
						'onClosed'			: 	onClosed												,
						'overlayOpacity'	:	0.3														,
						'showCloseButton'	:   false													,
						'index'				:	Math.floor(Math.random()*11)
					});
	}
		
	// funzione che visualizza all'utente il documento da scaricare oppure emette un messaggio di errore
	function showDownloadFileOrErrorDownload(url_message , title , content , type , url_download , frame_to_open){
		drawMessage(url_message,
			title	,
			content	,
			type	,
			function(){
				switch(risp_message){
					case 'DOWNLOAD':
									MyRedirectToAFrame('Location: ',url_download,frame_to_open);
							break;
					case 'ANNULLA':
									
						break;
				} 
			},
			450,
			180
		);
	}
	
	function OpenCloseDiv(divId){ 
		if ($("#" + divId).is(":visible")){
			$("#" + divId).hide("slow");
		}else{
			$("#" + divId).show("slow");
		}
	};

