
/* La funzione permette di calcellare l'azione predefinita per un evento*/
function StopPreventDefault(evt)
{	
	if(evt.preventDefault) 
		evt.preventDefault();
	 else 
		evt.returnValue=false;
}

/* La funzione permette di calcellare il 'bubble' degli eventi'*/
function StopPropagation(evt)
{
	if(evt.stopPropagation) 
		evt.stopPropagation();
	 else 
	 evt.cancelBubble=true;
}

function SourceElement(evt)
{
	if (navigator.appName=='Netscape')
		return evt.target;
	else 
		return event.srcElement;
}

function getEvent(evt)
{
	if (evt==null)
		return window.event;
	else
		return evt;
}

function stopSubmitOnEnterPress(e,enterPressHandle)
{
   
    if (e.keyCode == 13)
    {   
        var srcEl=SourceElement(e);
        if (srcEl.tagName.toLowerCase()!="a" && srcEl.type.toLowerCase() != "submit" && srcEl.type.toLowerCase() != "button") 
        {
            StopPreventDefault(e);
            if (enterPressHandle!=null && enterPressHandle!="")
            {
                eval(enterPressHandle());
            }
        }
     }
}
/*
Data l'ID della ComboBox la combo verrà selezionata in base al VALUE passato.
*/
function SelectCombo(comboId,value)
{
	var el=document.getElementById(comboId);
	var i;
	for (i=0;i<el.options.length;i++)
	{
		if (el.options(i).value==value)
		{
			el.selectedIndex=i;
			break;
		}
	}
}

/*
	consente, dato l'id stringa di un combo, di ottenere il testo selezionato
*/
function getComboSelectedText(elementId){
	var el, str;
	el=document.getElementById(elementId);
	str= el.options[el.selectedIndex].text;
	return str;
}

/*
	dato il nome lato client "elementId" di una radiobuttonlist ottiene il valore selezionato
	della key (isText=true) o della label associata (isText=false)
*/
function getRadioButtonListSelected(elementId, isText){
	var el,radios,labels, str, ix;
	str="";
	el=document.getElementById(elementId);
	radios = el.getElementsByTagName("input");
	
	for (ix=0; ix < radios.length; ix++){
		if (radios[ix].checked){ 
			if (isText){
				labels = radios[ix].parentNode.getElementsByTagName("label");
				if (labels.length > 0) { str = labels[0].innerHTML;}
			} else {
				str = radios[ix].value;
			}
			break;
		}
	}
	return str;
}

/*
	dato l'id della RadioButtonList e il valore key, seleziona l'elemento correlato 
*/
function selRadioButtonList(elementId, key){
	var el,radios, ix;
	el=document.getElementById(elementId);
	radios = el.getElementsByTagName("input");
	for (ix=0; ix < radios.length; ix++){
		radios[ix].checked = (radios[ix].value==key);
	}
}


/*
Consente di checcare tutti i check box di una colonna di un datagrid
dgrId		Id del datagrid
bool		indica se checcare o no il checkbox
column		la colonna del datagrid (se è un datalist, usare sempre 0)
			indice 0-based
index		l'indice del checkbox da trovare (normalmente 0)
			indice 0-based
*/
function CheckAll(dgrID,bool,column,index)
{
	var el=document.getElementById(dgrID);
	var count=0;
	var i,t;
	for (i=1;i<el.rows.length;i++)
	{
		var check=el.rows[i].cells[column].getElementsByTagName("INPUT");
		//alert(el.rows[i].cells[column].innerHTML);
		for (t=0;t<check.length;t++)
			if (check[t].type=="checkbox")
			{
				if (index==count)
					check[t].checked=bool;
				count++;
			}
		count=0;
	}
}


/*
Consente di scorrere la geranchia dei controlli a partire da un oggetto e di trovare uno specifico tag
el		Elemento di partenza
tag		Stringa con il nome del tag
count	Quante volte deve trovarlo nella ricerca prima che sia quello valido (ad esempio il secondo parent TABLE)
		Indice 1-based
ord		Come si muove nella gerarchia
		GERARCHIA_MOVE_UP=0;
		GERARCHIA_MOVE_DOWN=1;
		GERARCHIA_MOVE_LEFT=2;
		GERARCHIA_MOVE_RIGHT=3;
inside (boolean), esegue prima un firstChild
*/
function GetElementByTag(el,tag,count,movimento,inside)
{
	var found=false;
	var i=0;
	//alert(el);
	if (inside)
	{
		el=el.firstChild;
		movimento=3;
	}
	while (!found)
	{
		if (el==null)
			return null;
		if (el.nodeName.toUpperCase()=='#TEXT')
		{
			el=el.nextSibling;
		}
		
		if (el==null)
			return null;
		
		if (el.nodeName.toUpperCase()==tag.toUpperCase())
		{
			i++;
			if (i==count) 
				found=true;
			else
				switch (movimento)
				{
					case 0:
						el=el.parentNode;
						break;
					case 1:
						el=el.firstChild;
						break;
					case 2:
						el=el.previousSibling;
						break;
					case 3:
						el=el.nextSibling;
						break;
				}
		}
		else
			switch (movimento)
			{
				case 0:
					el=el.parentNode;
					break;
				case 1:
					el=el.firstChild;
					break;
				case 2:
					el=el.previousSibling;
					break;
				case 3:
					el=el.nextSibling;
					break;
			}
	}
	
	return el;
}

/*
Abilita la gestione dei cambiamenti ai controlli nella maschera chiamante, ad esempio qualsiasi
modifica ad un controllo che sia TextBox, Combo o checkbox viene monitorato nell maschera e 
qualora ci sia stato un cambiamento al blur del controllo verrà avviata la procedura callBackFunction
callBackFunction	Riferimento alla funziona da passare PROTOTIPO: <func>(<control>)

ATTENZIONE, non monitorizza le finestre modali!! Per farlo utilizzare la loro proprietà CustomProcBeforeSend
Vedi: disableCheckControls()
*/
function enableChangeControls(callBackFunction)
{
	document.ondeactivate=function()
							{
								SalvaCampo(window.event.toElement.id);
								if (Test(window.event.srcElement.id))
								{
									callBackFunction(window.event.srcElement);
								}
							}
}

/*
Disabilita il monitoraggio dei cambiamenti dei controlli nella pagina
*/
function disableChangeControls(callBackFunction)
{
	document.ondeactivate=null;
}

/*
Crea una finestrella PopUp
text			Il test (in HTML) da viualizzare
style			Lo style dellla finestra. Lo stile può essere anche una classe basta che inizi per '.'
x, y			La posizione x e y. Se -1 centra nello schermo (in vert o orriz)
width, height	la dimensione della finestra.

return			L'oggetto PopUp
*/
function createPopUp(text, style, x, y, width, height)
{
	var popUp=window.createPopup();

	popUp.document.createStyleSheet(GetMainDir() + "StylesPortale.css");
	if (style.substring(0,1)=='.')
	{
		popUp.document.body.style.cssText = "";
		popUp.document.body.className=style.substring(1);
	}
	else
		popUp.document.body.style.cssText += ';' + style;
		
	popUp.document.body.innerHTML=text;
	
	var px,py;
	
	if (x<0) px=screen.width/2-width/2; 
	else px=x;
	
	if (y<0) py=screen.height/2-height/2; 
	else py=y;
	
	popUp.show(px,py,width,height)
	
	return popUp;
}

function find(el)
{
	return document.getElementById(el);
}

/*  CLASSE OnitDate (TESTED WITH MOZILLA and IE)
	 questa classe permette di riconoscere le date di tipo "dd/mm/yy" e in italiano come "25 gennaio 1988 10.55"
	e nonchè nel formato di javascript riconosciuto dal metodo date.parse(). L'ora viene riconosciuta anche nel fomato "15:55:33"
	 la classe OnitDate possiede la proprità .data  (di tipo Date) che contiene all'inizio la data di sistema. 
	->Il metodo parse permette di riconoscere una data in stringa instanziando la proprietà .data; se non valida .data=null
	->Il metodo isDate() è identico a quello di vbs. Non modifica la proprità .data
	->Il metodo format formatta una data utilizzando le stringhe segnaposto dd= giorno, MM=mese, yy=anno 4 cifre, hh=ore, 
	  mm=minuti ss= secondi
*/
function OnitDate(){
	this.data=new Date();
	this.isDate=OnitDate_isDate;     /*(sData) true se la stringa passata è una data*/
	this.parse=OnitDate_parse2;      /* (sData) instanzia la classe interpretando la stringa passata*/
	this.format=OnitDate_format;	 /* (fmt,abbr) Es fmt = "dd/MM/yy hh.mm.ss" oppure "day dd month yy hh:mm:ss"
										abbr indica la lunghezza dell'abbreviazione del giorno e mese in parole*/
	this.toString=OnitDate_toString; /* data formattata in gg/mm/aaaa */
}

/*effettua il riconoscimento delle date anche italiane*/
function OnitDate_parse(sDate){
	sDate=OnitDate_Replace(sDate);
	var splDate, splAnno, sOra, g,m,a,ora,mi,se, i, indice, ix;
	ora=0; mi=0; se=0; sOra="";
    if (sDate.length == 0)  return null;
	if (sDate.indexOf("/")>0){/* data tipo gg/mm/aaaa*/
		splDate = sDate.split("/"); if (splDate.length!=3) return null;
		splAnno=splDate[2].split(" ");
		if (isNaN(splDate[0])) return null; else g=parseInt(splDate[0],10);
		if (isNaN(splDate[1])) return null; else m=parseInt(splDate[1],10);
		for (i=0;i<splAnno.length;i++){
			if (isNaN(splAnno[i])) return null; 
				else {
					a=parseInt(splAnno[i],10); a=OnitDate_EspandiAnno(a);
					if (i<splAnno.length-1) sOra=splAnno[i+1]; /*contiene l'ora*/
					break;
				}	
		}
	} else { /* data in lettere */
		splDate = sDate.split(" ");
		m=-2; indice=-1; g=-1; a=-1;
		for (i=0;i<12;i++){
			ix=sDate.toLowerCase().indexOf((" "+OnitDate_translate_DM(i, true,3)).toLowerCase());
			if (ix >= 0 && ix>indice) {m=i; indice=ix};
		}
		m = m+1;
		/* ricerco giorno e anno*/
		for (i=0;i<splDate.length;i++){
			if (g<0){ /* cerco il giorno */
				if (!isNaN(splDate[i])) g=parseInt(splDate[i],10);
			} else if(a<0){ /* cerco l'anno */
				if (!isNaN(splDate[i])){ 
					a=parseInt(splDate[i],10); a=OnitDate_EspandiAnno(a);
					if (i<splDate.length-1) sOra=splDate[i+1]; /*contiene l'ora*/
				}
			}
		}
		
		if (g<0||m<0||a<0){ /* ultimo tentativo: uso il parse di js*/
			if (!isNaN(Date.parse(sDate))) 
				return new Date(sDate);
			else
				return null;
		}
	}
	/*interpretazione ora*/
	var splOra= sOra.replace(/:/g,".").split(".");
	if (splOra.length==3 || splOra.length==2){
		if (!isNaN(splOra[0])) ora=parseInt(splOra[0],10);
		if (!isNaN(splOra[1])) mi=parseInt(splOra[1],10);
		if (splOra.length==3){/*secondi*/
			if (!isNaN(splOra[2])) se=parseInt(splOra[2],10);
		}
		
	}
	if ( g>0 && g<=31 && m>0 && m<=12 && a>=0 && ora>=0 && ora <24 && mi>=0 && mi<60 && se>=0 && se<60){ 
		return new Date(a,m-1,g,ora,mi,se,0);
	} else {
		return null;
	}
}

function OnitDate_isDate(sDate){
	return (OnitDate_parse(sDate) != null);
}

/*registra solamente la data nell'oggetto */
function OnitDate_parse2(sDate){this.data = OnitDate_parse(sDate)}

function OnitDate_format(fmt,abbr){
	var strOut="";
	var strOra="";
	var g,m,a,day,month,hh,mm,ss;
	if (this.data==null) return "";
	day= OnitDate_translate_DM(this.data.getDay(),false,abbr)
	g=this.data.getDate(); g=((g<10) ? "0"+g:""+g);
	m=this.data.getMonth(); m=((m<9) ? "0"+(m+1):""+(m+1));
	month= OnitDate_translate_DM(this.data.getMonth(),true,abbr)
	a=this.data.getFullYear(); 
	/*ora*/
	hh= (this.data.getHours()<10 ? "0":"") + this.data.getHours();
	mm= (this.data.getMinutes()<10 ? "0":"") + this.data.getMinutes();
	ss= (this.data.getSeconds()<10 ? "0":"") + this.data.getSeconds();
	/*data*/
	strOut= fmt.replace(/day/g,day);
	strOut= strOut.replace(/month/g,month);		
	strOut= strOut.replace(/dd/g,g);
	strOut= strOut.replace(/MM/g,m);	
	strOut= strOut.replace(/yy/g,a);	
	strOut = strOut.replace(/hh/g,hh);
	strOut = strOut.replace(/mm/g,mm);
	strOut = strOut.replace(/ss/g,ss);
	return strOut;
}
function OnitDate_toString(){
	return this.format("dd/MM/yy hh.mm.ss",0);
}



function OnitDate_translate_DM(num, bMonth,iAbbreviazione){
	var mesi, giorni;
	var strOut="";
	mesi = new Array("Gennaio","Febraio","Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre" , "Dicembre" );
	giorni = new Array("Domenica", "Lunedi", "Martedi", "Mercoledi", "Giovedi", "Venerdi", "Sabato" ); 
	if (bMonth) strOut=mesi[num]; else strOut=giorni[num];
	if (iAbbreviazione==0) return strOut; else return (strOut.substring(0,iAbbreviazione));
}

function OnitDate_Replace(str){
	var s=str+"";
	s=s.replace(/    /g," "); 
	s=s.replace(/   /g," ");
	s=s.replace(/  /g," ");
	return s;

}

/*permette di espandere l'anno di una data da 1-2 a 4 cifre */
function OnitDate_EspandiAnno(val){
	var valore=val+"";
	var ris=valore, upB=(new Date()).getFullYear()+30;
	if (valore.length<=2 && valore.length>0 && !isNaN(valore)){
		if (upB%100 > valore) ris=(upB-upB%100)+parseInt(valore,10);
		else ris=(upB-upB%100)-100+parseInt(valore,10);
	}
	return ris;
}


/* fine OnitDate */

//********************************************************************************************************//
// Le due funzioni addProcToEvent e removeProcToEvent servono rispettivamente per aggiungere e rimuovere 
// da una lista di procedure associate ad eventi (window.onload,window.resize,..) qualche procedure !!
// E' necessario che tutti passino come  parametro "EVENTO" la stessa stringa  per lo stesso evento!
// Per il momento questi sono gli eventi utilizzati:
// - "window.onload"
// - "window.onresize"
// - "window.document.onkeydown"
// Se a qualcuno serve associare ad un altro evento una procedura scriva qui la stringa "evento" 
// passata alla funzione!
// P.S. per avere l'oggetto "event" passato come parametro alla nostra funzione, il parametro "PROCEDURA"
//      dovrà essere del tipo 'myProc(evt)', dove EVT è l'evento!!
//*******************************************************************************************************//

//
var eventProcs=new Object;
var eventProcsRegistered=new Object;
//

function addProcToEvent(evento,procedura,key)
{
	//
	if (eventProcs[evento.toString()]==null) eventProcs[evento.toString()]=new Array;
	//
	if (eventProcsRegistered[evento.toString()]==null)
	{	
		if (eval(evento)!=null)
		{
			if (eval(evento).toString!=null)
			{
				strRoutine=eval(evento).toString();
				strRoutine=strRoutine.replace('function','');
				strRoutine=strRoutine.substring(strRoutine.indexOf('{'));
				eventProcs[evento.toString()][evento.toString()] = strRoutine + ';' ;
			}
		}
		eventProcsRegistered[evento.toString()]=true;
	}
	//	
	eventProcs[evento.toString()][key] = procedura + ';';
	//
	RebuildEventHanldes(evento);
	//
}

function removeProcToEvent(evento,key)
{
	//
	if (eventProcs[evento.toString()]!=null) eventProcs[evento.toString()][key]=null;
	//
	RebuildEventHanldes(evento);
	//
}

function RebuildEventHanldes(evento)
{
	//
	var keys;
	var procs='';
	//
	for (keys in eventProcs[evento.toString()])
	{
		var pr=eventProcs[evento.toString()][keys];
		if (pr!=null && typeof(pr)=="string")
		{	
			procs=procs + eventProcs[evento.toString()][keys] ;
		}
	}
	//
	eval(evento+'=function(evt) {evt=getEvent(evt);' + procs + ';};');
	//
}
///////////////////////    MARCO 27/01/2004    ////////////////////////////
/////  traduzione delle omonime funzioni presenti in WindowUtility.vbs  ///
///////////////////////////////////////////////////////////////////////////
var first;

function GetMainDir(){
	var i,path;
	path="";
	parti = document.location.pathname.split("/");
	if (parti[0]!="" )
	     path="../";
	for (i=1;i<(parti.length - 2);i++)
		path= (path + "../");
	return path;
}

function SetFirst(){
	first=1;
}

function AreYouSure(){
	if (first==1)
		window.open("Layout/Exit.aspx","exit","status=0,menubar=0,scrollbars=0,resizable=1,width=400,height=200,fullscreen=3,center=yes");
}

//////////////////    FINE MARCO 27/01/2004      /////////////////////

function toUpper(obj)
{
	obj.value=(obj.value).toUpperCase();
}

function checkIsNumber(obj,minInteri,maxInteri,minDec,maxDec)
{
	var r;
	alert("^(+|-)?d{" + minInteri + "," + maxInteri + "}(,)?d{" + minDec + "," + maxDec + "}$");
	r = new RegExp("^(+|-)?d{" + minInteri + "," + maxInteri + "}(,)?d{" + minDec + "," + maxDec + "}$");
		
	var ret=r.test(obj.value);
	alert(obj.value + ' ' + r.test(obj.value));
	
	if (!ret)
		obj.value="";
}


/* ---------- MODULO DI GESTIONE DINAMICA DEGLI STYLES ------------------ */

/*ottiene uno stile calcolato dinamicamente*/
function getStyle(oElm, strCssRule){
	var strValue = "";

	if(document.defaultView && document.defaultView.getComputedStyle){
		/*mozilla*/
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		/*ie*/
		try{
			strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
				return p1.toUpperCase();
			});
			strValue = oElm.currentStyle[strCssRule];
		}
		catch(e){
			// Used to prevent an error in IE 5.0
		}
	}

	return strValue;
}

/*ottiene il valore corrente di uno stile convertendolo in un numero */
function getIntegerStyle(oElm, strCssRule){
	var strStyle; 
	strStyle = getStyle(oElm, strCssRule);
	strStyle = strStyle.replace(/[^0-9,\.,]+/g,"");
	return parseInt(strStyle,10);
}


    
    /*
    	ottiene la dimensione reale in pixel dell'oggetto passato.
    	come valore di ritorno si ottiene un ggetto con le properieta .width e .height
    */
    function getObjectDimension(obj){
    	var ret;
    	switch (obj.tagName)
			{
				case "FORM":
					ret=getBodyDimension();
					break;
				case "BODY":
					ret=getBodyDimension();
					break;
				default: // div, tabelle ecc..
					ret=new Object();
					ret.height=obj.offsetHeight;
					ret.width =obj.offsetWidth;
			}
		return ret;
    }
    
    
    /*
    	funzione che restituisce le dimensioni dell'area renderizzata in base al browser utilizzato
    	ritorna un oggetto con le properieta .width e .height
    */
    
    function getBodyDimension(){
    	var ret=new Object();

	    if( typeof( window.innerWidth ) == 'number' ) {
	        //Non-IE
	        ret.width = window.innerWidth;
	        ret.height = window.innerHeight;
	        //calcolo dei margini top e bottom
	        ret.height=ret.height-(getIntegerStyle(document.body,"margin-top")+getIntegerStyle(document.body,"margin-bottom"));
	    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	        //IE 6+ in 'standards compliant mode'
	        ret.width = document.documentElement.clientWidth;
	        ret.height = document.documentElement.clientHeight;
	        //calcolo dei margini top e bottom
	        ret.height=ret.height-(getIntegerStyle(document.body,"margin-top")+getIntegerStyle(document.body,"margin-bottom"));
	    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	        //IE 4 compatible
	        ret.width = document.body.clientWidth;
	        ret.height = document.body.clientHeight;
	    }   
	    return ret;
    }
    


/* ---------------------------------------------------------------------- */
