//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|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 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 = op6 || op7;
	
	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 gestoreScadenze **********************************************************************
function gestoreScadenze() //crea un elenco di scadenze ordinate per data
{
	var items = new Array();
	var indexMemo = new Array();
	var boldWord = null;
	var colPreAlert = "#3366FF";
	var colAlert = "#FF0000";
	var blockquoteClass = "";
	var alertDelta = 15;
	
	this.setAlertDelta = function(giorni)
	{
		if (giorni) alertDelta = giorni;
	}
	
	this.setBoldWords = function(expr)
	{
		boldWord = expr;
	}
	
	this.setPreAlertColor = function(color)
	{
		if (color) colPreAlert = color;
	}
	
	this.setAlertColor = function(color)
	{
		if (color) colAlert = color;
	}
	
	this.setBlockquoteClass = function(classe)
	{
		blockquoteClass = classe;
	}
	
	this.addItem = function(data, testo) //richiede una scadenza formattata in AAAA-MM-GG dove se AAAA è impostato a 0000, viene considerato l'anno attuale
	{
		var scadenzaFormattata = null;
		
		data = data.replace("0000", new Date().getYear());  //sostituisce 0000 con l'anno attuale
		if (boldWord) testo = testo.replace( boldWord, "<b>$1</b>"); //imposta le parole in grassetto
		
		var anno = data.substr(0,4)
		var	mese = data.substr(5,2)
		var giorno = data.substr(8,2)
				
		oggi = new Date();	//crea la data di oggi (clientSide)
		scadenza = new Date(anno, mese-1 , giorno); //crea la data di scadenza
		giorni = Math.ceil((scadenza - oggi) / (1000*60*60*24)); //calcola i giorni facendo la differenza tra le date che sono espresse in millisecondi
		
		//formatta la scadenza in GG-MM-AAAA
		scadenzaFormattata = (new String(scadenza.getDate()).length == 2 ? (scadenza.getDate()) : "0" + (scadenza.getDate())) + ".";
		scadenzaFormattata += (new String(scadenza.getMonth()+1).length == 2 ? (scadenza.getMonth()+1) : "0" + (scadenza.getMonth()+1)) + "." ;
		scadenzaFormattata += scadenza.getYear() ;
		
		ordinamentoScadenze = data ;
		
		if (giorni >= 0 && giorni <= alertDelta) //crea l'array di date in scadenza
		{
			var style = "";

			//imposta il colore della data a seconda del numero di giorni dalla scadenza
			if (giorni == 2) style = "style = 'color:" +  colPreAlert + "'";  
			if (giorni < 2) style = "style = 'color:" +  colAlert + "'";
			
			//aggiunge l'item in scadenza all'array associativo (il primo commento serve per creare in indice di ordinamento per l'array)
			//items[items.length] = "<!--" + (new String(giorni).length == 2 ? giorni : "0" + giorni) + "--><b " + style + ">Scadenza: " + scadenzaFormattata + "</b>: (" + ( giorni == 0 ? "Oggi" : (giorni == 1 ? "Domani" : giorni + " giorni") ) + ") <blockquote>" + testo + "</blockquote>";
			if (!items[ordinamentoScadenze])
			{
				indexMemo[indexMemo.length] = ordinamentoScadenze;
				items[ordinamentoScadenze] = "<b " + style + ">" + scadenzaFormattata + "</b>: (" + ( giorni == 0 ? "Oggi" : (giorni == 1 ? "Domani" : giorni + " giorni") ) + ") <blockquote class='" + blockquoteClass + "'>" + testo + "</blockquote>";
			}
			else
			{
				items[ordinamentoScadenze] += "<blockquote class='" + blockquoteClass + "'>" + testo + "</blockquote>";
			}
			
			
		}	
	}
	
	this.printHTML = function()
	{
		var html = "";
		indexMemo.sort() //riordina l'array di elementi in scadenza
		
		//genera l'html formattato da scrivere nel browser 
		if (indexMemo.length > 0)
		{
			for (i=0; i < indexMemo.length; i++)
				html += "<p>" + items[indexMemo[i]] + "</p>\n";
		}
		else html = "<blockquote class='" + blockquoteClass + "'>" + "Nessuna scadenza da segnalare" + "</blockquote>";
			
		//scrive l'html nel browser
		document.write(html);
	}
}
//***** fine della classe gestoreScadenze **********************************************************************

//***** 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 contextualMenu **********************************************************************
function dirData(url, flags)
{
	this.url = url;
	this.flags = ( flags ? flags : new Array() );
}

function contextualMenu(title) //v2.0
{
	var menuTitle = title;
	var section = new Array();
	var pages = new Array();
	var counter = 0;
	var url = new String(document.location).replace(/\\/g, "/");
		
	this.addSection = function(url, flags) //String url, Array flags
	{
		section[counter] = new dirData(url, flags);
		counter ++;
	}
	
	this.defineNewFlag = function(flag, folder, linkText, linkAttributes)
	{
		if (flag.length > 1)
		{
			alert("I flags devono essere di un solo carattere: " + flag + " non definito" );
			return;
		}
		
		pages[flag] = '<a href="@@' + folder + '" ' + linkAttributes + '>' + linkText + '</a>';
	}
	
	this.summon = function()
	{
		//ricerca della sezione corrente
		var currentSection = -1;
		for (q=0; q < counter; q++)
			if (url.indexOf(section[q].url) != -1) currentSection = q;
			
		//se non ci sono flag definiti per questa sezione o se non è definita la sezione esce senza fare nulla
		if (currentSection == -1) return;
		if (section[currentSection].flags.length == 0 ) return;	
		
		var list = "";
		//definizione lista html 
		//		@link@		link alla sezione
		//		@rep		inizio area ripetuta
		//		rep@		fine area ripetuta
		list =  "<ul>";
		list += "  @rep"; //inizio area ripetuta
		list += "  <li>";
		list += "		@link@"; //@link@ viene sostituito dal link effettivo
		list += "  </li>";
		list += "  rep@"; // fine area ripetuta
		list += "</ul>";
		
		
		var repeatArea = list.substring (list.indexOf("@rep") + 4, list.indexOf("rep@"));
		var rows = "";

		//creazione righe tabella
		for (q=0; q < section[currentSection].flags.length; q++)
			rows += repeatArea.replace("@link@", pages[section[currentSection].flags[q]].replace("@@", section[currentSection].url ));
		
		//sostituisce nella tabella l'area ripetuta con le righe della tabella generate
		list = list.replace(/@rep[\w\W]*rep@/gi, rows);
		
		if (rows == "") document.write("&nbsp;");
		else document.write(list);
	}
}
//***** fine della classe contextualMenu **********************************************************************

//***** 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);
		}
	}
}