//Libreria di classi utilizzate nel portale
//***** inizio della classe cookie **********************************************************************
function cookie(name,expires,path,domain,secure)
	{
	//proprietà dell'oggetto
	this.varValue = ""; 	//valore del cookie intero
	this.varName = name; 	//nome del valore memorizzato
	this.expString = ((expires == null) ? "" : ("; expires=" + expires.toGMTString()));	//durata del cookie
	this.pathString = ((path == null) ? "" : ("; path=" + path));			//percorso per il cookie
	this.domainString = ((domain == null) ? "" : ("; domain=" + domain));		//dominio del cookie
	this.secureString = ((secure == true) ? "; secure" : "");				//cookie sicuro?
	this.deleted = ((document.cookie.indexOf(name) != -1) ? false : true)       //controlla se il coockie è presente	
	
	//metodi dell'oggetto
	this.getVal = function()//funzione di recupero del valore memorizzato; 
	{
		if (this.deleted) return null
		
		offset = this.varName.length+1;
		this.varValue = new String(document.cookie+";");
		
		inizio = this.varValue.indexOf(this.varName);
	
		if (inizio!=-1) 
			{
			fine = this.varValue.indexOf(";",inizio)
			result = this.varValue.substring((inizio+offset),fine);
			return unescape(result);
			}
		else return null
	}
	
	this.setVal = function() // funzione di impostazione del valore del cookie
	{
		this.deleted = false
		this.varValue = value;
		document.cookie = this.varName+"="+escape(value)+this.expString+this.pathString+this.domainString+this.secureString;
	}
	
	this.delCookie = function() //funzione di cancellazione: imposta la data di scadenza del cookie 3gg addietro, così il browser lo cancella
	{
		this.deleted=true;
		expDate= new Date();
		expDate.setTime(expDate.getTime()-3*24*60*60*1000);
		expDate.toGMTString();
		document.cookie=this.varName+"=null"+"; expires="+expDate.toGMTString()
	}

	this.isset = function() //ritorna true se il cookie è presente
	{
		return !this.deleted;
	}
	
	this.getName = function() //ritorna il nome del cookie (che è il primo argomento del costruttore)
	{
		return this.varName;
	}
}
//***** fine della classe cookie **********************************************************************

//***** inizio della classe expDate **********************************************************************
function expDate(mesi,giorni,ore,minuti)
{
	//proprietà dell'oggetto
	this.mesi = mesi;
	this.giorni = giorni;
	this.ore = ore;
	this.minuti = minuti;
	
	//metodi dell'oggetto
	this.get= function()
	{
		var mesi = this.mesi*30*24*60*60*1000;
		var giorni = this.giorni*24*60*60*1000;
		var ore = this.ore*60*60*1000;
		var minuti = this.minuti*60*1000;
		var result = new Date();
		result.setTime( result.getTime() + mesi + giorni + ore + minuti );
		return result;
	}	
}
//***** fine della classe expDate **********************************************************************

//***** inizio della classe htmlUtil **********************************************************************
function htmlUtl()
{
	var htmlIn = null;
	
	this.evidenzia = function () 
	{
		if (!document.browser.detect( "ie6 || ie55 || ns6 || op7" )) return;
		
		var elementId = "corpo";
		
		//purifica la stringa di ricerca da eventuali caratteri sensibili per le espressioni regolari
		var searchStr = document.getElementById("frmCerca").query.value.replace(/([\[|\]|\%|\^\?\\|\.|\||\-|\(|\)]){1,}/gi,"\\$1").replace(/ {1,}/gi,"|").replace(/^\|/gi,"")
		if (searchStr.length < 3 ) return ; //se la stringa di ricerca è minore di 3 caratteri, l'evidenziazione non viene effettuata
			
		if (htmlIn == null) htmlIn = new String(document.getElementById(elementId).innerHTML);
		
		//gestisce il colore del testo evidenziato in pagine normali o ad alto contrasto
		var evidenziato = "<span class='evidenziatore'>$1</span>"; //pagine normali
		
		var pattern = new RegExp("(" + searchStr + ")","gi"); //crea l'espressione regolare con la stringa di ricerca
		var htmlOut = "";
		var deltaS = 0; //contiene cicilicamente la poizione di un carattere "<" che delimita l'inizio di un tag
		var deltaE = 0;	//contiene cicilicamente la poizione di un carattere ">" che delimita la fine di un tag
		//var loop = true;
		//var inTag = (htmlIn.substr(0,1) == "<" ? true : false); 
		var tagNum = (htmlIn.replace(/[^<]*/gi,"")).length; //conta quanti tag sono presenti in innerHTML
		var tagStart = new Array(); //array contenente gli indici a cui inizia ogni tag
		var tagEnd = new Array(); //array contenente gli indici a cui finisce ogni tag
					
		if (tagNum > 0) //se ci sono tag
		{	
			for (i = 0; i < tagNum; i++) //trova gli indivi di inizio e di fine dei tag
			{	
				tagStart[i] = htmlIn.indexOf("<", deltaS)
				tagEnd[i] = htmlIn.indexOf(">", deltaE) + 1
				
				deltaS = htmlIn.indexOf("<", deltaS) + 1
				deltaE = htmlIn.indexOf(">", deltaE) + 1
			}
			
			htmlOut = (htmlIn.substr(0, tagStart[0]-1)).replace(pattern, evidenziato); //effettua l'evidenziazione del testo davanti al primo tag della stringa
			
			for (i = 0; i < tagNum; i ++) //percorre tutti i tag della stringa
			{
				htmlOut += htmlIn.substring(tagStart[i], tagEnd[i]) //all'interno dei tag non effettua sostituzioni per evidenziare
				
				if (tagStart[i+1]) //tra i tag sostituisce la stringa di ricerca con l'equivalente evidenziata
					htmlOut += (htmlIn.substring(tagEnd[i], tagStart[i+1])).replace(pattern, evidenziato);	
			}
			
			//correzione bachi di opera nella stringa innerHTML
			if (window.opera) htmlOut = htmlOut.replace(/width=["|']\-([0-9]{1,3})["|']/gi, 'width="$1%"').replace(/<([a-zA-Z]{1,4})><\/([a-zA-Z]{1,4})>/gi, "<$1>&nbsp;</$1>");
			
			htmlOut += (htmlIn.substr(htmlIn.lastIndexOf(">")+1,htmlIn.length)).replace(pattern, evidenziato); //effettua l'evidenziazione dopo l'ultimo tag
		}	
		else htmlOut = htmlIn.replace(pattern, evidenziato); //se nella stringa non ci sono tag, effettua direttamente l'evidenziazione
		
		document.getElementById(elementId).innerHTML = htmlOut; //imposta nella pagina la stringa con l'evidenziazione
		return ;
	}
}
//***** fine della classe htmlUtli **********************************************************************

//***** inizio della classe httpUrl **********************************************************************
function httpUtl(rootDir)
{
	//(private)
	var url = document.location;
	var host = document.location.host;
	var path = document.location.pathname;
	var query = document.location.search;
	var root = rootDir;
	
	//metodi pubblici
	this.getUrl = function (absoluteServerPath) //restituisce un url relativo alla root del server o il percorso completo di una cartella
	{
		var folder;
		
		if (!host)
		{
			folder = path.substring(0, path.indexOf(root) + root.length);
			return folder + absoluteServerPath
		}
		else return absoluteServerPath;
	}
	
	this.getPagePath = function() //restituisce il path della pagina dalla root del server in giù, o dalla cartella di lavoro in giù
	{
		if (!host)
			return path.substring(path.indexOf(root) + root.length);
		else 
			return document.location.pathname;
	}
}
//***** fine della classe httpUrl **********************************************************************

//***** inizio della classe browserDetect **********************************************************************
function browserDetect()
{
	var browsers = "(ie4|ie55|ie5|mac5|ie6|ns6|ns4|op6|op7|opera|explorer|netscape)"
		
	var token = new RegExp(browsers);
	var tokenSintax = new RegExp (browsers + "| " , "gi")
	var operatorsSintax = /(\(|\)|&&|\|\||!)/g;
	
	//definizione delle variabili di detection del browser
	var ie4  =  (document.all && !window.opera ? true : false);
	var ie5  =  (document.all && !document.fireEvent && !window.opera ? true : false);
	var mac5 = (document.all && document.getElementById && !document.mimeType && !window.opera);
	var ie55 =  (document.all && document.fireEvent && !document.createComment ? true : false);
	var ie6  =  (document.all && document.fireEvent && document.createComment ? true : false);
	
	var ns6  =  (!document.all && !window.opera && document.getElementById ? true : false);
	var ns4  =  (document.layers ? true : false);
	
	var op6  =  (window.opera && !document.createComment ? true : false);
	var op7  =  (window.opera && document.createComment ? true : false);
	
	var explorer = ie4 || ie5 || ie55 || ie6;
	var netscape = ns6 || ns4;
	var opera = (navigator.userAgent.indexOf("Opera") != -1 ? true : false);
	
	this.detect = function(expression) 
	//restituisce true se l'espressione passata è vera. 
	//i token dell'espressione equivalgono alle variabili di detection
	//gli operatori sono:
	// && = and
	// || = or
	// ( ) = parentesi per sottoespressione
	// ! = not
	{
		var sintaxError = "";
		sintaxError = expression.replace(tokenSintax,"");
		sintaxError = sintaxError.replace (operatorsSintax, "");
		
		if (sintaxError.length > 0) 
		{
			//alert ("Errore: il comando " + sintaxError.toUpperCase() + " non è riconosciuto")
			return false;
		}
				
		while (token.test(expression))
		{
			last = token.exec(expression)
			expression = expression.replace(last[0], eval(last[0])) //rimpiazza nella stringa dell'espressione il valore della variabile corrispondente
		}
		return eval(expression) ? true : false
	}
}
//***** fine della classe browserDetect **********************************************************************

//***** inizio della classe baseLayer **********************************************************************
function baseLayer( layerName ) //classe che gestisce il posizionamento indipendentemente dalla dimensione del browser
{
	//propertyes dell'oggetto
	this.layerName = layerName; 	//contiene il nome del layer
	this.enabled = true;			//abilita le funzioni di visualizzazione / spegnimento del livello
	
	//methods dell'oggetto
	this.show = function () //visualizza il livello
	{
		this.visibility("visible");
	}

	this.hide = function () //nasconde il livello
	{
		this.visibility("hidden");
	}
						
	this.swap = function () //inverte il flag visibility del livello
	{
		this.crossbrowserCommand("visibility", null, "getValue") == "visible" ? this.hide() : this.show();
	}
						
	this.visibility = function (status) //imposta la visibilità del livello (hidden o visible)	
	{
		if ( !this.enabled ) return;
		this.crossbrowserCommand("visibility", status);
	}
						
	this.getPosition = function()
	{
		var pos = new Object();
		
		pos.x = parseInt(this.crossbrowserCommand("left",null,"getValue"));
		pos.y = parseInt(this.crossbrowserCommand("top",null,"getValue"));
		
		return pos;
	}
	
	this.getLayerReference = function()
	{
		var lyrRef = null;
		
		if (document.browser.detect("op6 || op7 || ie6 || ns6 || ie55")) lyrRef = document.getElementById(this.layerName);
		else if (document.browser.detect("ie5")) lyrRef = document.all[this.layerName];
		else if (document.browser.detect("ns4")) lyrRef = document.layers[this.layerName];
		
		return lyrRef;
	}
		
	this.crossbrowserEvent = function(e) //richiede come parametro un oggetto evento. 
	{
		var crossEvent = new Object();
		var pos = this.getPosition()
		//posizione del mouse all'atto dell'evento
		crossEvent.X = e.clientX;
		crossEvent.Y = e.clientY;
		crossEvent.offX = crossEvent.X - pos.x;
		crossEvent.offY = crossEvent.Y - pos.y;
		
		return crossEvent;
	}
	
	this.crossbrowserCommand = function (property, value, flag)
	{
		/*
			crea una riga di comando javascript compatibile tra i browser.
			può eseguire la riga, ritornare il valore di una proprietà, ritornare la stringa di comando stessa
		*/
		
		var object = null;	//contiene la proprietà da modificare o ritornare
		var command = null;	//contiene l'intera stringa di comando ("layer.proprietà = valore")
		
		if (document.browser.detect("op6 || op7 || ie6 || ns6 || ie55"))
			{
				object = "document.getElementById('" + this.layerName + "').style." + property;
				command = object + " = '" + value + "'";
			}
		else if (document.browser.detect("ie5"))
			{
				object = "document.all['" + this.layerName + "'].style." + property;
				command = object + " = '" + value + "'";
			}
		else if (document.browser.detect("ns4"))
			{
				object = "document.layers['" + this.layerName + "']." + property;
				command = object + " = '" + value + "'";
			}
		
		if (!flag) eval (command); //esegue la stringa come fosse un comando JavaScript
		else if (flag == "getCommand" ) return command; // ritorna la stringa di comando
		else if (flag == "getValue") return eval(object); // ritorna il valore della proprietà selezionata
	}

	this.getName = function() //ritorna il nome del livello gestito
	{
		return this.layerName;
	}
		
	this.enable = function()	
	{
		this.enabled = true;
	}
	
	this.disable = function()	
	{
		this.enabled = false;
	}		
}
//***** fine della classe baseLayer **********************************************************************

//***** inizio della classe multiLayer **********************************************************************
function multiLayer() //visualizza un solo livello tra quelli passati come argomento
{
	this.layers = null;
	this.active = null;
	var locked = true;
	
/*****************************************************************************************************/

	this.setLayers = function () //accetta un elenco di oggetti baseLayer
	{
		locked = false;
		this.layers = new Array();
		for (i= 0; i < this.setLayers.arguments.length; i++)
			this.layers[i] = this.setLayers.arguments[i]
	}

/*****************************************************************************************************/
	
	this.showLayer = function (name) //visualizza il layer selezionato e nasconde gli altri
	{
		if (locked)	return;
		this.active = name
				
		for (i=0; i < this.layers.length; i++)
			if (this.layers[i].getName() == name)
			{
				this.layers[i].show()
			}
			else
			{
				this.layers[i].hide()
			}
	}

/*****************************************************************************************************/
	
	this.hideLayer = function (name) //nasconde il layer selezionato
	{
		if (locked)	return;
		this.active = null;
				
		for (i=0; i < this.layers.length; i++)
			if (this.layers[i].getName() == name)
			{
				this.layers[i].hide()
			}
	}

/*****************************************************************************************************/	

	this.swapLayer = function (name) //scambia lo stato di visualizzazione del layer selezionato e nasconde gli altri
	{
		if (locked)	return;
		this.active = name
		
		for (i=0; i < this.layers.length; i++)
			if (this.layers[i].getName() == name)
			{
				this.layers[i].swap()
			}
			else
			{
				this.layers[i].hide()
			}
	}

/*****************************************************************************************************/	

	this.showActive = function() //ripristina il layer attivo
	{
		this.showLayer(this.active)
	}
	
	this.lock = function()
	{
		locked = true;
	}
	
	this.unlock = function()
	{
		locked = false;
	}
}
//***** fine della classe multiLayer **********************************************************************



//***** inizio della classe WindowUtil **********************************************************************

function windowUtl()
{
	var win = null;
	
	this.apriFinestra = function (url, x, y, attributi)
	{
		/*
		apre una nuova finestra delle dimensioni specificate
		argomenti:
		url		: indirizzo della pagina da aprire
		x  		: larghezza finestra
		y  		: altezza finestra
		attributi	: stringa con attributi particolari della finestra (en scrollbars, titlebar, resizable)
		
		il metodo WINDOW.OPEN genera una nuova istanza della finestra
		del browser.
		1° argomento: url della pagina da visualizzare nella nuova finestra
		2° argomento: titolo della finestra
		3° argomento: stringa contenente le proprietà della nuova finestra
		
		le proprietà WINDOW.SCREEN.WIDTH E .HEIGHT ritornano la risoluzione utilizzata in pixel
		*/
		var screenX = window.screen.width;
		var screenY = window.screen.height;
		
		//imposta le dimensioni delle finestra se queste non vengono passate alla funzione
		if (!x) x = 400;
		if (!y) y = 300;
		
		//imposta gli attributi di default alla finestra se questi non vengono passati alla funzione
		if (!attributi) attributi = "dependent=0, resizable=0";
		
		//centraggio della nuova finestra
		xPos = (screenX - x) / 2;
		yPos = ((screenY - y ) / 2) - 100;
		if ( yPos < 10 ) yPos = 10;
		
		//istanza della finestra
		if (!win || win.closed) 
		{
			win = window.open(url, "", "height=" + y + ", width=" + x + ", left=" + xPos + ", top=" + yPos + ", " + attributi);
		}
		else
		{
			win.close();
			win = null;
			win = window.open(url, "", "height=" + y + ", width=" + x + ", left=" + xPos + ", top=" + yPos+"," + attributi);
		}
	}
}