
// Funzione che chiude la finestra corrente:
function closeWindow(){
	if (this['Dialog'] !== undefined)
		Dialog.closeInfo();
	else
		window.close();
}

function includeJS(jsPath){
	  var script = document.createElement('script');
	  script.setAttribute('type', 'text/javascript');
	  script.setAttribute('src', jsPath);
	  document.getElementsByTagName('head')[0].appendChild(script);
}

function includeCSS(cssPath){
	var css = document.createElement('link');
	css.type = 'text/css';
	css.rel = 'stylesheet';
	css.href = cssPath;
	css.media = 'screen';
	document.getElementsByTagName("head")[0].appendChild(css);
}

if(this['BrowserDetect'] != undefined)
	BrowserDetect.init();

function isFirefox(){
  if (BrowserDetect.browser === "Firefox")
	return true;
	else return false;
}

function getBrowserName(){
  return BrowserDetect.browser;
}

function getBrowserVersion(){
	  return BrowserDetect.version;
	}

function uncheckRadioButton(obj){
   if (!isFirefox())
   		uncheckRadioButtonIE(obj);
   	else
   		uncheckRadioButtonFF(obj);
}


// Funzione che permette di deselezionare una opzione di un elemento radiobutton 
// (in modo da poter avere anche l'opzione "nessuna selezione")
function uncheckRadioButtonIE(obj) {	
	var checked = obj.checked;

	if (checked) {
		obj.checked = false;
	}
	else {
		obj.checked = true;
	}
}

var radioStatus = new Object();
function uncheckRadioButtonFF(obj) {
	if (radioStatus[obj.name] === null) {
		radioStatus[obj.name] = obj.value;
	}
	else {
		if (radioStatus[obj.name] == obj.value) {
			obj.checked = false;
			radioStatus[obj.name] = null;
		}
		else {
			radioStatus[obj.name] = obj.value;
		}
	}
		
}

// Funzione che controlla che il contenuto del campo "obj"
// non ecceda "max_length" (nell'eventualità, i caratteri in più vengono tagliati)
function checkMaxLength(obj, max_length){
  if(obj.value.length > max_length)
  {      
    obj.value = obj.value.substring(0, max_length);
  }
}


// Funzione che controlla che il textfield identificato da 'textFieldId' non sia vuoto
function checkTextField(textFieldId) {
	
	var tf = xGetElementById(textFieldId);
	var text = 'Inserire almeno una lettera';
	
	if ((tf.value === null) || (tf.value === "")){
		if (this['Dialog'] !== undefined){
			openErrorDialog(text);
		}
		else{
			alert(text);
		}
		return false;
  	}
  	else{ 
  		return true;
  	}

}

// Funzione che assegna al'elemento "targetId" 
// il valore selezionato nella select "selectId"
function assignSelectedInList(selectId, targetId) {
	
	var selectElement = xGetElementById(selectId); 
	var targetElement = xGetElementById(targetId); 
	
	var index = selectElement.selectedIndex;
	if (index == -1){
		alert("Selezionare un elemento della lista\n");
        return false;
	}
	else{
		var row = selectElement[index];
		targetElement.value = row.value;
		return true;
	}
	
}

// Parte copiata da ici.js
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function FF_ViewData(objName, theProp) {
 var obj = MM_findObj(objName);
  if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
   if(eval("obj."+theProp) == 'block')
    eval("obj."+theProp+"= 'none'");
   else
    eval("obj."+theProp+"= 'block'");
  }
}

function checkDataValida(giorno,mese) {
	switch ( mese ) {
		case 2:
   			if ( (anno % 4)  == 0 ) {
				if ( giorno <= 29 )  {return true;}
				else {return false;}
			}
			else {
				if ( giorno <= 28 ) { return true; }
				else { return false; }
			}
			break;
		case 4:
			if ( giorno <= 30 ) { return true; }
			else { return false; }
			break;
		case 6:
			if ( giorno <= 30 ) { return true; }
			else { return false; }
			break;
		case 9:
			if ( giorno <= 30 ) { return true; }
			else { return false; }
			break;
		case 11:
			if ( giorno <= 30 ) { return true; }
			else { return false; }
			break;
		default:
			return true;
			break;
	}
}

function openMessaggioWindow(messaggio_jsp, id, resp_id){
 {
    win = window.open(messaggio_jsp+"?_msgid="+id+"&_respId="+resp_id, "Messaggio", "width=550,height=620,screenX=300,screenY=200,resizable=yes");
    if(!win || win.closed)
     {win = window.open(messaggio_jsp+"?_msgid="+id+"&_respId="+resp_id, "Messaggio", "width=550,height=620,screenX=300,screenY=200,resizable=yes");}
    else
     {win.focus();}


 }


}

function openScriviMessaggioWindow(scriviMessaggio_jsp)
 {
    win = window.open(scriviMessaggio_jsp, "ScriviMessaggio", "width=550,height=620,screenX=300,screenY=200,resizable=yes");
    if(!win || win.closed)
     {win = window.open(scriviMessaggio_jsp, "ScriviMessaggio", "width=550,height=620,screenX=300,screenY=200,resizable=yes");}
    else
     {win.focus();}
 }

function openBlob(blobServlet, tipo, hash)
 {
  var iWidth = (window.innerWidth) ? window.innerWidth
	: document.body.offsetWidth;
  var iHeight = (window.innerHeight) ? window.innerHeight
	: document.body.offsetHeight+164;

  win = window.open(blobServlet+"?_tipo="+tipo+"&_codice="+hash, "", "width="+iWidth+",height="+iHeight+",resizable=yes,scrollbars=yes");
    if(!win || win.closed)
     {win =  window.open(blobServlet+"?_tipo="+tipo+"&_codice="+hash, "", "width="+iWidth+",height="+iHeight+",resizable=yes,scrollbars=yes");}
  else
     {win.focus();}
 }

/**
 * La funzione apre una nuova finestra.
 * I parametri da indicare sono i seguenti:
 * - jsp 		url nuova finestra
 * - width 		larghezza
 * - height 	altezza
 * - winName 	nome nuova finestra
 * - returnWin  se settato a true, il metodo ritorna come variabile la finestra creata
 */ 
function openJspInNewWindow(jsp, width, height, winName, returnWin) {

	if (width == undefined)
		width = window.xClientWidth()*0.8;
	if (height == undefined)
		height = window.xClientHeight()*0.8;
	if (winName == undefined)
		winName = randomString(6);
		
	var openOptions = {
		name		: winName,
		width		: width,
		height		: height,
		location	: jsp
	};
	var win = _newWindow(openOptions);
	win.load(openOptions.location);
	
	if (returnWin !== undefined && returnWin === true){
		return win;
	}

}

/*
 * 
 */
function openJspInModalWindow(jsp, width, height) {
	
	if (width == undefined)
		width = window.xClientWidth()*0.8;
	if (height == undefined)
		height = window.xClientHeight()*0.8;
	
	if (this['Dialog'] !== undefined){
		Dialog.info({url: jsp, options: {method: 'get'}}, {className: "alphacube", width:width, height:height, closable: true});
	}
	else{
		var openOptions = {
				width		: width,
				height		: height,
				location	: jsp
			};
			window.showModalDialog(openOptions.location, "", "dialogWidth:"+openOptions.width+"px;dialogHeight:"+openOptions.height+"px;resizable:yes;status:no");
	}
		
}



function openJspInModalWindowStandard(jsp, width, height) {
	
	if (width == undefined)
		width = window.xClientWidth()*0.8;
	if (height == undefined)
		height = window.xClientHeight()*0.8;
	
	
	var openOptions = {
			width		: width,
			height		: height,
			location	: jsp
	    };
	
	window.showModalDialog(openOptions.location, "", "dialogWidth:"+openOptions.width+"px;dialogHeight:"+openOptions.height+"px;resizable:yes;status:no");
}



/* Apre un oggetto WINDOW (vuota)**/
function openNewWindow(width, height, winName) {
	var openOptions = {
		name		: winName,
		width		: width,
		height		: height
	};
	var win = _newWindow(openOptions);
	win.load('');
}

/* Ritorna un oggetto WINDOW **/
function _newWindow(options) {
	
    this.options = Object.extend({
		name		: 'newWindow',
		width		: 800,
		height		: 600,
		left		: 50,
		top			: 50,
		location	: '',
		menubar		: 0,
		resizable	: 1,
		scrollbars	: 1,
		statusbar	: 1,
		toolbar		: 0
      }, options || {});

    
	/** EXTEND funzione introdotto dalla libreria prototype
	per dettagli vedere http://www.prototypejs.org/api/element/extend **/
	var win = new xWindow(this.options.name, this.options.width, this.options.height, 
						  this.options.left, this.options.top, this.options.location,
						  this.options.menubar, this.options.resizable, this.options.scrollbars, 
						  this.options.scrollbars, this.options.toolbar);
	return win;
}

function submitFormNewWindow(formID) {
	submitFormNewWindow(formID, '_newWin');
}

function submitFormNewWindow(formID, winName) {
	submitFormNewWindow(formID, winName, '1000', '750')
}

function submitFormNewWindow(formID, winName, width, height) {	
	var theForm = xGetElementById(formID);
	var jsp = theForm.action;
	openNewWindow(width, height, winName);
	theForm.target = winName;
	theForm.submit();
}


function openInSportelloSize(jsp)
 {
 	var w = 800;
 	var h = 600;
 	
    if (window.screen) {
 		w = (window.screen.availWidth)* 8 / 10;
 		h = (window.screen.availHeight)* 8 / 10;
   	}
 	
    win = window.open(jsp, '', "width="+w+",height="+h+",screenX=50,screenY=50,resizable=yes,scrollbars=yes");
    if(!win || win.closed)
     {win = window.open(jsp, '', "width="+w+",height="+h+",screenX=50,screenY=50,resizable=yes,scrollbars=yes");}
    else
     {win.focus();}
     
 }

function openInFullScreen(jsp)
 {
    if (window.screen) {
	    win = window.open(jsp, '', "width="+(window.screen.availWidth-5)+",height="+(window.screen.availHeight-5)+",resizable=yes,scrollbars=yes");
	    if(!win || win.closed)
	     {win = window.open(jsp, '', "width="+(window.screen.availWidth-5)+",height="+(window.screen.availHeight-5)+",resizable=yes,scrollbars=yes");}
	    else
	     {win.focus();}
   	}
   else{
	    win = window.open(jsp, '', "fullscreen=yes,resizable=yes,scrollbars=yes");
	    if(!win || win.closed)
	     win = window.open(jsp, '', "fullscreen=yes,resizable=yes,scrollbars=yes");
	    else
	     {win.focus();}
   }
 }

// Funzioni utilizzate per controllo del contenuto in un TextField in cui si desidera avere solo valori numerici
// -------------------------------------------------------------------------------------------------------------

// 1) da richiamare "onkeypress", impedisce che nel field vengano scritti caratteri diversi dai numerici (NOTA: non impedisce il COPIA/INCOLLA)
function isNumericKey(e){
  var k = document.all ? e.keyCode : e.which;
  return ((k > 47 && k < 58) || k == 8 || k == 0);
}

// 2) da richiamare "onChange", controlla che nel campo non siano stati inseriti caratteri diversi dai numerici, e in tal caso li cancella
function extractNumeric(str){
  return str.replace(/\D/g,"");
}

// -------------------------------------------------------------------------------------------------------------
// Fine funzioni utilizzate per controllo del contenuto in un TextField in cui si desidera avere solo valori numerici


// Funzioni utilizzate per controllo della data:
// ---------------------------------------------

function MonLen(Yr, Mo, Dy) { 
	
  var Dol, K, DiM, NsI

  DiM = LengthOfMonth(
		  +Yr.options[Yr.selectedIndex].text,
		  Mo.selectedIndex+1);
  
  Dol = Dy.options.length;
  
  if ((NsI = Dy.selectedIndex) >= DiM){ 
	  NsI = DiM-1;
  }
  
  // rimozione giorni (es. passaggio da dicembre a giugno o febbraio)
  for (K=Dol; K >DiM ; K--){ 
	  Dy.options[K-1] = null;
  }
  
  // aggiunta giorni (es. passaggio da giugno o febbraio a dicembre)
  for (K=Dol+1 ; K<=DiM ; K++){ 
	  Dy.options[K-1] = new Option(K);
	  Dy.options[K-1].value = K;
  }
  
  Dy.selectedIndex = NsI;

}

function Lz(x) { return (x<0||x>=10?"":"0") + x /* local */ }

function DropReadYMD(Yr, Mo, Dy) {
  // formatta la data come stringa in un campo
  var Y = + Yr.options[Yr.selectedIndex].text
  var M = Mo.selectedIndex // 0..11
  var D = Dy.selectedIndex + 1
  return  Lz(D) + '/' + Lz(M+1) + '/' + Y }

function InitYMD(Yr, Mo, Dy, SetObj) {
	
	Yr.options[0] = new Option(SetObj.getFullYear());
	Yr.options[0].value = SetObj.getFullYear();
	Mo.options[0] = new Option(Mon3[SetObj.getMonth()])
	Mo.options[0].value = SetObj.getMonth()+1
	Dy.options[0] = new Option(SetObj.getDate())
	Dy.options[0].value = SetObj.getDate();
	
    // MonLen(Yr, Mo, Dy) 
}

// Initialiser 2: setta la data alla data passata come SetObj (se c'è), 
// oppure alla prima data disponibile (indici = 0):
function InitYMDselector(Yr, Mo, Dy, Anni, Base, SetObj) {
  var J
  if (!Base) Base = new Date().getFullYear()
  for (J=0; J<Anni; J++) {
  	Yr.options[J] = new Option(Base+J)
  	Yr.options[J].value = J + Base
  }
  for (J=0;  J<12 ; J++){
     Mo.options[J] = new Option(Mon3[J])
     Mo.options[J].value = J+1
  }
  for (J=0;  J<31 ; J++) {
  	Dy.options[J] = new Option(J+1)
  	Dy.options[J].value = J + 1
  }
  if (SetObj) with (SetObj) {
		    Yr.selectedIndex = getFullYear()-Base
		    Mo.selectedIndex = getMonth()
		    Dy.selectedIndex = getDate()-1 
    }
  else
  Yr.selectedIndex = Mo.selectedIndex = Dy.selectedIndex = 0

  MonLen(Yr, Mo, Dy) 
  }

function GlobalNames() {
  Mon3 = ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu",
          "Lug", "Ago", "Set", "Ott", "Nov", "Dic"]
  Day3 = ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'] }

function LengthOfMonth(Y, M) { // M=1..12 // OK in NS4? Mac?
  with (new Date(Y,M,1,12)) { setDate(0) ; return getDate() } }

// ---------------------------------------------
// Fine funzioni utilizzate per controllo della data


// Funzione che gestisce l'attributo "readonly" dell'elemento/degli elementi 
// passati come parametro
// array può essere:
// - 1 elemento
// - 1 ID di un elemento
// - 1 array di ID
// - 1 array di ELEMENTI
function setReadonly(array, bool){
	
	var el;
	if (isArray(array)){ /*** ARRAY ***/
		for(var i=array.length-1; i>=0; i--) {					
			if(typeof(array[i]) === 'string'){ //ID
				el = xGetElementById(array[i]);
				if (el){ 
					el.readOnly = bool;
					// el.focus();
				}
			}
			else{ // ELEMENT
				el = array[i];

				if (el.type && el.type === 'DateLoader'){ // elemento DateLoader
					setReadonlyDateLoader(el, bool);
				}
				else if(el.type && el.type === 'ComboLoader'){ // elemento ComboLoader
					setReadonlyComboLoader(el, bool);
				}
				else{
					el.readOnly = bool;
				}
			}
		}
	}
	else { /*** 1 ELEMENT ***/
		
		if(typeof(array) === 'string'){ //ID
			
			el = xGetElementById(array);
			if (el){ 
				el.readOnly = bool;
			}
		}
		else{ // ELEMENT
			
			el = array;
			if (el.type && el.type === 'DateLoader'){ // elemento DateLoader
				setReadonlyDateLoader(el, bool);
			}
			else if(el.type && el.type === 'ComboLoader'){ // elemento ComboLoader
				setReadonlyComboLoader(el, bool);
			}
			else{
				el.readOnly = bool;
			}
		}
	}

}
	
function setReadonlyDateLoader(dateLoader, bool){
	
	var dateLoaderId = dateLoader.id;
	
	var ggField = $('gg_'+dateLoaderId);
	var mmField = $('mm_'+dateLoaderId);
	var aaaaField = $('aaaa_'+dateLoaderId);
	
	var ggVal = ggField.value;
	var mmVal = mmField.value;
	var aaaaVal = aaaaField.value;

	clearCombo(ggField);	
	clearCombo(mmField);	
	clearCombo(aaaaField);	
	
	var data = new Date();
	data.setFullYear(aaaaVal,mmVal-1,ggVal);
	
	if (bool){
         InitYMD(aaaaField, mmField, ggField, data);
	}
	else{
		var baseYear = dateLoader.annoIniziale;
		var spanYear = dateLoader.annoFinale-baseYear+1;
		InitYMDselector(aaaaField, mmField, ggField, spanYear, baseYear, data);
	}
	
 	dateLoader.readonly = bool;

	// SETVALUE SUL CAMPO HIDDEN ASSOCIATO (vedi DateLoader.java)	
 	$("__#hidden#__"+dateLoaderId).value = (bool?"readonly":"");

}

function setReadonlyComboLoader(comboLoader, bool){
	
	var selectId = comboLoader.selectId;
	var theCombo = $(selectId);
	
	var val = ' ';
	var text = ' ';
	
	if (theCombo.selectedIndex !== -1){
		val = theCombo.value;
		text = theCombo.options[theCombo.selectedIndex].text;
	}
	
	clearCombo(theCombo);	
	 	
	if (bool){
	  	theCombo.options[0] = new Option(text);
	  	theCombo.options[0].value = val;
	}
	else{
		var comboValues = comboLoader.values;
		var comboElements = comboLoader.elements;
		for (var j=0; j<comboValues.length; j++){
		  	theCombo.options[j] = new Option(comboElements[j]);
		  	theCombo.options[j].value = comboValues[j];
		}

		// ripristino valore
		theCombo.value = val;
 	}

 	comboLoader.readonly = bool;
	
	// SETVALUE SUL CAMPO HIDDEN ASSOCIATO (vedi ComboLoader.java)	
 	$("__#hidden#__"+selectId).value = (bool?"readonly":"");
}

function clearCombo(theCombo){
    while (theCombo.childNodes.length > 0) {
      theCombo.removeChild(theCombo.firstChild);
    }
}

// Funzione che setta il valore 'val' ad ognuno dell'elemento/degli elementi il cui 
// id viene passato come parametro in "arrayOfId" (1 elemento o array)
function setValue(array, val){
	
	var element;
	if (isArray(array)){ /*** ARRAY ***/
		for(var i=array.length-1; i>=0; i--) {					
			if(typeof(array[i]) === 'string'){ //ID
				element = xGetElementById(array[i]);
				if (element){ 
					if (element.type && (element.type.indexOf('select') === 0)){
						setValueSelect(element, val);
					}
					else if(element.type === 'ComboLoader'){
						setValueComboLoader(element, val);
					}
					else if(element.type === 'DateLoader'){
						setValueDateLoader(element, val);
					}
					else{
						element.value = val;
						if (element.innerHTML !== undefined){
							try{
								element.innerHTML = val;
							}catch(error){}
						}
					}
				}
			}
			else{ // ELEMENT
				element = array[i];
				if (element.type && (element.type.indexOf('select') === 0)){
					setValueSelect(element, val);
				}
				else if(element.type === 'ComboLoader'){
					setValueComboLoader(element, val);
				}
				else if(element.type === 'DateLoader'){
					setValueDateLoader(element, val);
				}
				else{
					element.value = val;
					if (element.innerHTML !== undefined){
						try{
							element.innerHTML = val;
						}catch(error){}
					}
				}
			}
		}
	}
	else { /*** 1 ELEMENT ***/		
		if(typeof(array) === 'string'){ //ID
			element = xGetElementById(array);
			if (element){ 
				if (element.type && (element.type.indexOf('select') === 0)){
					setValueSelect(element, val);
				}
				else if(element.type === 'ComboLoader'){
					setValueComboLoader(element, val);
				}
				else if(element.type === 'DateLoader'){
					setValueDateLoader(element, val);
				}
				else{				
					element.value = val;
					if (element.innerHTML !== undefined){
						try{
							element.innerHTML = val;
						}catch(error){}
					}
				}
			}
		}
		else{ // ELEMENT
			element = array;
			if (element.type && (element.type.indexOf('select') === 0)){
				setValueSelect(element, val);
			}
			else if(element.type === 'ComboLoader'){
				setValueComboLoader(element, val);
			}
			else if(element.type === 'DateLoader'){
				setValueDateLoader(element, val);
			}
			else{				
				element.value = val;			
				if (element.innerHTML !== undefined){
					try{
						element.innerHTML = val;
					}catch(error){}
				}
			}
		}
	}
	
}


function setValueDateLoader(dateLoader, date){
	
	var orig_ro = dateLoader.readonly;
	setReadonlyDateLoader(dateLoader, false);
		
	var dateLoaderId = dateLoader.id;
	
	var ggField = $('gg_'+dateLoaderId);
	var mmField = $('mm_'+dateLoaderId);
	var aaaaField = $('aaaa_'+dateLoaderId);
	
	/*
	 * NOTA: uso parseInt (xx, 10) come workaround del seguente bug:
	 * http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256C85006A6604
	 */
	setValueSelect(ggField, parseInt(date.giorno, 10));
	setValueSelect(mmField, parseInt(date.mese, 10));
	setValueSelect(aaaaField, parseInt(date.anno, 10));
	
	/*
	 * Se il DateLoader è gestito dal RadioButton 
	 * ed il RadioButton non è "checked",
	 * deve anche forzare un click sul RadioButton
	 * purchè la data non sia tutta a zero (trucco per dire che non voglio la data)
	 */
	if(date.anno>0){
		try {
			if (dateLoader.dateSetter_Id !== undefined) {
				if (!($(dateLoader.dateSetter_Id).checked)) {
					$(dateLoader.dateSetter_Id).checked = true;
				}
			}
		} catch (e) {}
	}
	try {
		if (dateLoader.hideOrShowFunction_Name !== undefined) {
			window[dateLoader.hideOrShowFunction_Name]();
		}
	} catch (e) {}
	
	setReadonlyDateLoader(dateLoader, orig_ro);
	
}

function setValueComboLoader(comboLoader, val){
	
	var orig_ro = comboLoader.readonly;
	setReadonlyComboLoader(comboLoader, false);
		
	var comboLoaderId = comboLoader.selectId;
	var theCombo = $(comboLoaderId);
	setValueSelect(theCombo, val);
	
	setReadonlyComboLoader(comboLoader, orig_ro);
	
}

function setValueSelect(select, val){
  var found = false;
  var i;
  for (i = 0; i < select.options.length; i++) {
    if (select.options[i].value == val) {
      select.options[i].selected = true;
      found = true;
    }
    else {
      select.options[i].selected = false;
    }
  }

  if (found) return;

  for (i = 0; i < select.options.length; i++) {
    select.options[i].selected = (select.options[i].text == val);
  }
}





// Funzione che abilita (o disabilita) ognuno dell'elemento/degli elementi il cui 
// id viene passato come parametro in "arrayOfId" (1 elemento o array)
function setEnabled(arrayOfId, bool){
	var arrayOfElements = xGetElementById(arrayOfId);
	if (isArray(arrayOfElements)){ /*** ARRAY ***/
		for(var i=arrayOfId.length-1; i>=0; i--) {
			var el = xGetElementById(arrayOfId[i]);
			if (el){
				el.disabled = (!bool);
			}
		}
	}
	else {	
		if (arrayOfElements){ /*** 1 ELEMENT ***/			
			
			var el = arrayOfElements;
			
			if (el.type && el.type === 'DateLoader'){ // elemento DateLoader
				setEnabledDateLoader(el, bool);
			}
			else if(el.type && el.type === 'ComboLoader'){ // elemento ComboLoader
				setEnabledComboLoader(el, bool);
			}
			else{
				el.disabled = (!bool);
			}

			
			
		}
	}
}

function setEnabledComboLoader(comboLoader, bool){
	var comboLoaderId = comboLoader.selectId;
	var theCombo = $(comboLoaderId);
	theCombo.disabled = (!bool);
}

function setEnabledDateLoader(dateLoader, bool){
	var dateLoaderId = dateLoader.id;
	
	var ggField = $('gg_'+dateLoaderId);
	var mmField = $('mm_'+dateLoaderId);
	var aaaaField = $('aaaa_'+dateLoaderId);
	
	ggField.disabled = (!bool);
	mmField.disabled = (!bool);
	aaaaField.disabled = (!bool);
}

// Funzione che aggiunge il listener "eventName" con associata la funzione "funct" 
// all'elemento/agli elementi passati come parametro in "arrayOfElements" (1 elemento oppure array)
function addEvent(arrayOfElements, eventName, funct){
	var ieEvent;
	var mozEvent;
	if (eventName.substring(0,2) == "on"){
		ieEvent = eventName;
		mozEvent = eventName.substring(2);
	}
	else {
		mozEvent = eventName;
		ieEvent = "on"+eventName;
	}
	
	if (isArray(arrayOfElements)){ /*** ARRAY ***/
		for(var i=0; i<arrayOfElements.length; i++) {
			var el = arrayOfElements[i];
			if(el.addEventListener) {/*** MOZILLA ***/
				el.addEventListener(mozEvent, funct, false);
			}
			if(el.attachEvent) { /*** IE ***/
				el.attachEvent(ieEvent, funct, false);
			}
		}
	}
	else{ /*** 1 ELEMENT ***/
		try{
			if (arrayOfElements.id){
				var el = arrayOfElements;
				if(el.addEventListener) {/*** MOZILLA ***/
					el.addEventListener(mozEvent, funct, false);
				}
				if(el.attachEvent) { /*** IE ***/
					el.attachEvent(ieEvent, funct, false);
				}
			}
		}catch (e){}
	}
	
}

// la Funzione cancella l'esecuzione della funzione "funct" in corrispondenza dell'evento "eventName"
// dall'elemento/agli elementi passati come parametro in "arrayOfElements" (1 elemento oppure array)
function removeEvent(arrayOfElements, eventName, funct){
	var ieEvent;
	var mozEvent;
	if (eventName.substring(0,2) == "on"){
		ieEvent = eventName;
		mozEvent = eventName.substring(2);
	}
	else {
		mozEvent = eventName;
		ieEvent = "on"+eventName;
	}
	
	if (isArray(arrayOfElements)){ /*** ARRAY ***/
		for(var i=0; i<arrayOfElements.length; i++) {
			var el = arrayOfElements[i];
			if(el.removeEventListener) {/*** MOZILLA ***/
				el.removeEventListener(mozEvent, funct, false);
			}
			if(el.detachEvent) { /*** IE ***/
				el.detachEvent(ieEvent, funct, false);
			}
		}
	}
	else{ /*** 1 ELEMENT ***/
		try{
			if (arrayOfElements.id){
				var el = arrayOfElements;
				if(el.removeEventListener) {/*** MOZILLA ***/
					el.removeEventListener(mozEvent, funct, false);
				}
				if(el.detachEvent) { /*** IE ***/
					el.detachEvent(ieEvent, funct, false);
				}
			}
		}catch (e){}
	}
	
}


// Funzione che esegue la chiamata esplicita al listener "eventName" 
// all'elemento/agli elementi passati come parametro in "arrayOfElements" (1 elemento oppure array)
function fireEvent(arrayOfElements, eventName){
	
	// EVENT "onchange" (NOTA: UNICO IMPLEMENTATO FINO AD ORA!!!!!)
	if (eventName === "onchange" || eventName === "change"){
		if (isArray(arrayOfElements)){ /*** ARRAY ***/
			for(var i=0; i<arrayOfElements.length; i++) {
				var el = arrayOfElements[i];
				if (el.fireEvent){ /*** IE ***/
					el.fireEvent("onchange");
				}		
				else if (el.dispatchEvent){ /*** MOZILLA ***/
					var evt = window.document.createEvent("HTMLEvents");
					evt.initEvent("change",true,true);
					el.dispatchEvent(evt);
				}	
				if (el.onchange){ /*** evento onchange "normale" ***/
					el.onchange;
				}
			}
		}
		else{ /*** 1 ELEMENT ***/
			try{
				if (arrayOfElements.id){
					var el = arrayOfElements;
					if (el.fireEvent){ /*** IE ***/
						el.fireEvent("onchange");
					}		
					else if (el.dispatchEvent){ /*** MOZILLA ***/
						var evt = window.document.createEvent("HTMLEvents");
						evt.initEvent("change",true,true);
						el.dispatchEvent(evt);
					}	
					if (el.onchange){ /*** evento onchange "normale" ***/
						el.onchange;
					}
				}
			}catch (e){}
		}
	}
	
	// TODO: eventuali altri EVENTS
	else if (eventName === "onclick" || eventName === "click"){
		if (isArray(arrayOfElements)){ /*** ARRAY ***/
			for(var i=0; i<arrayOfElements.length; i++) {
				var el = arrayOfElements[i];
				if (el.fireEvent){ /*** IE ***/
					el.fireEvent("onclick");
				}		
				else if (el.dispatchEvent){ /*** MOZILLA ***/
					var evt = window.document.createEvent("HTMLEvents");
					evt.initEvent("click",true,true);
					el.dispatchEvent(evt);
				}	
				if (el.onclick){ /*** evento onclick "normale" ***/
					el.onclick;
				}
			}
		}
		else{ /*** 1 ELEMENT ***/
			try{
				if (arrayOfElements.id){
					var el = arrayOfElements;
					if (el.fireEvent){ /*** IE ***/
						el.fireEvent("onclick");
					}		
					else if (el.dispatchEvent){ /*** MOZILLA ***/
						var evt = window.document.createEvent("HTMLEvents");
						evt.initEvent("click",true,true);
						el.dispatchEvent(evt);
					}	
					if (el.onclick){ /*** evento onclick "normale" ***/
						el.onclick;
					}
				}
			}catch (e){}
		}
	}
	
}


// Funzioni per gestione IMPORTI 
// -----------------------------

// 1) http://javascript.internet.com/forms/auto-currency.html

function showKeyPress(evt)
{
alert("onkeypress handler: \n"
      + "keyCode property: " + evt.keyCode + "\n"
      + "which property: " + evt.which + "\n"
      + "charCode property: " + evt.charCode + "\n"
      + "Character Key Pressed: "
      + String.fromCharCode(evt.charCode) + "\n"
     );
}


// Funzione da richiamare sull'evento "onkeypress" nel campo che si vuole controllare
// Accetta la digitazione dei soli caratteri specificati in "strCheck" 
function currencyFormat(fld, e) {

	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789-,';
	var aux = aux2 = '';
	var whichCode = '';
	
	if (!isFirefox())
		whichCode = e.keyCode;
	else
		whichCode = (e.which !== undefined) ? e.which : e.keyCode;
	
	if (whichCode == 8) return true;  // Delete
	if (whichCode == 9 || whichCode == 0) return true;  // Tab
	if (whichCode == 13) return true;  // Enter
	if (whichCode == 35) return true;  // End
	if (whichCode >= 37 && whichCode <= 40) return true;  // Arrows
	
	key = String.fromCharCode(whichCode);  // Get key value from key code

	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	if (key == '-'){
		if (fld.value.indexOf('-') != -1) return false;
	}
	if (key == ','){
		if (fld.value.indexOf(',') != -1) return false;
	}
	
	iPeriodPos =fld.value.indexOf(',');
	
	if (iPeriodPos<0)
		{
		if ((fld.value.length > ((fld.maxLength-1)-3)) && (key != ',')) {
			return false;
		}
	}
	return true;
}


// Funzione da richiamare all'uscita dal campo che si vuole controllare
// "Normalizza" il valore del campo interpretandolo come un numerico e formattandolo di conseguenza
// - separatore migliaia = "."
// - separatore decimali = ","
function commaFormatted(fld)
{
	
 	var actual = fld.value; 
 	var amount = fld.value;
    var migliaiaSep = '.';
    var decimalSep = ',';
	
	// rimozione eventuale segno '-' in posizione errata:
	if (amount.indexOf('-') != -1){
	    var m = amount.split('-',2);
	    if (m[0].length > 0)
		amount = m[0]+m[1];
	}

	// rimozione eventuali 0 in testa:
	var k=0;
	while ((amount.substring(k,k+1) == '0') && 
			(amount.substring(k+1,k+2) != decimalSep))
	   amount = amount.substring(k+1);
	    	
    var a = amount.split(',',2);   
    var d = (a[1]) ? a[1]+"00" : "000";    
    var parteDec = parseInt(lTrimZero(d));   
   
    	
	var tmp = a[0].split('.',7);
    var i = parseInt(tmp[0]+tmp[1]+tmp[2]+tmp[3]+tmp[4]+tmp[5]+tmp[6]);

    if(isNaN(i)) { 
	    fld.value = ''; 
    }else{
	    var minus = '';

	    if(i < 0 | amount.substring(0,1) == '-') { minus = '-'; }

	    i = Math.abs(i);

	    var n = new String(i);	    
	    var a = [];
	    while(n.length > 3)
	    {
	        var nn = n.substr(n.length-3);
	        a.unshift(nn);
	        n = n.substr(0,n.length-3);
	    }

	    if(n.length > 0) { a.unshift(n); }	    
	    n = a.join(migliaiaSep);	    
	    
	    if (parteDec != 0){
	    	amount = n + ',' + d.substr(0,2);
	    } else {
	    	amount = n + ',00';
	    }
		amount = minus + amount;
  	    fld.value = amount;
	}
}

// formatta un valore in 1.234,56
function valueCommaFormatted(value) {
 	var actual = value; 
 	var amount = value;
    var migliaiaSep = '.';
    var decimalSep = ',';
	
	// rimozione eventuale segno '-' in posizione errata:
	if (amount.indexOf('-') != -1){
	    var m = amount.split('-',2);
	    if (m[0].length > 0)
		amount = m[0]+m[1];
	}


	// rimozione eventuali 0 in testa:
	var k=0;
	while ((amount.substring(k,k+1) == '0') && 
			(amount.substring(k+1,k+2) != decimalSep))
	   amount = amount.substring(k+1);

	
	    
    var a = amount.split(',',2)
    var d = (a[1]) ? a[1]+"00" : "000";
	
	var tmp = a[0].split('.',7);
    var i = parseInt(tmp[0]+tmp[1]+tmp[2]+tmp[3]+tmp[4]+tmp[5]+tmp[6]);
	
    //var i = parseInt(a[0]);
    if(isNaN(i)) { 
	    return ''; 
    } else {
	    var minus = '';
	    if(i < 0 | amount.substring(0,1) == '-') { minus = '-'; }
	    i = Math.abs(i);
	    var n = new String(i);
	    var a = [];
	    while(n.length > 3)
	    {
	        var nn = n.substr(n.length-3);
	        a.unshift(nn);
	        n = n.substr(0,n.length-3);
	    }
	    if(n.length > 0) { a.unshift(n); }
	    n = a.join(migliaiaSep);
	    
	    if (parteDec != 0){
	    	amount = n + ',' + parteDec.substr(0,2);
	    } else {
	    	amount = n + ',00';
	    }
		amount = minus + amount;
		return amount;
	}
}


// -----------------------------
// Fine funzioni per gestione IMPORTI

// Fine funzioni per gestione PERCENTUALI
// --------------------------------------
function percentFormat(fld, e) {

// SEPARATORE DECIMALI:
var decSep = ',';
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789,';
var aux = aux2 = '';

if (!isFirefox())
	whichCode = e.keyCode;
else
	whichCode = (window.event) ? e.which : e.keyCode;
	
if (whichCode == 8) return true;  // Delete
if (whichCode == 9 || whichCode == 0) return true;  // Tab
if (whichCode == 13) return true;  // Enter
if (whichCode == 35) return true;  // End
if (whichCode >= 37 && whichCode <= 40) return true;  // Arrows
key = String.fromCharCode(whichCode);  // Get key value from key code
if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
if (key == ','){
	if (fld.value.indexOf(',') != -1) return false;
}

iPeriodPos =fld.value.indexOf(',');
if (iPeriodPos<0)
	{
	if ((fld.value.length > ((fld.maxLength-1)-3)) && (key != ',')) {
		return false;
	}
}

}

// formatta un importo numerico con 
// una sola cifra decimale
function doubleCommaFormatted(field) {
	var amount = field.value;
	var decimalSep = ',';
	
	//eventuale trasformazione ',' in '.'
	if (amount.indexOf(',') > -1) {
	amount = amount.substring(0,amount.indexOf(',')) + '.' + 
			amount.substring(amount.indexOf(',') + 1, amount.length);
	}
	amount = Math.round(parseFloat(amount) * 10) + '';
	field.value = amount.substring(0, amount.length - 1) + ',' + 
		amount.substring(amount.length - 1, amount.length);
}

function percentCommaFormatted(fld){
	
	// 1) FORMATTAZIONE
    percentCommaFormattedNoMax(fld);
    
	// 2) CONTROLLO < 100
	if (parseFloat(fld.value) > 100){
		openErrorDialog("Percentuale superiore al 100%");
		fld.value = '0,0';
	}
    
}

function percentCommaFormattedNoMax(fld){
 
 	var amount = fld.value;
    var decimalSep = ',';
	
	// rimozione eventuali 0 in testa:
	var k=0;
	while ((amount.substring(k,k+1) == '0') && 
			(amount.substring(k+1,k+2) != decimalSep))
	   amount = amount.substring(k+1);
	    
    var a = amount.split(',',2)
    var d = (a[1]) ? a[1]+"00" : "000";
	
	var tmp = a[0].split('.',7);
    var i = parseInt(tmp[0]+tmp[1]+tmp[2]+tmp[3]+tmp[4]+tmp[5]+tmp[6]);
	
    if(isNaN(i) ) {     	
	    fld.value = '0,0'; 	    
    }else{
	    var n = new String(i);
	    amount = n + ',' + d.substr(0,2);
		fld.value = amount;
    }
    
}

// --------------------------------------
// Fine funzioni per gestione PERCENTUALI



//////////////////////////////////////////////////////////////
// FUNZIONI HIDE/SHOW DIV ////////////////////////////////////

// mantiene lo spazio "allocato" per la div anche quando la div è non visibile
function setVisible(arrayOfDivId, bool){

	var arrayOfElements = xGetElementById(arrayOfDivId);

	if (isArray(arrayOfElements)){ /*** ARRAY ***/
		for(var i=arrayOfDivId.length-1; i>=0; i--) {
		  var myDiv = xGetElementById(arrayOfDivId[i]);
		  if (bool){ // DO SHOW
		  	myDiv.style.visibility = "visible";
		  }
		  else{ // DO HIDE
		  	myDiv.style.visibility = "hidden";
		  }
		}
	}
	else {
		if (arrayOfElements){ /*** 1 ELEMENT ***/
		  var myDiv = xGetElementById(arrayOfDivId);
		  if (bool){ // DO SHOW
		  	myDiv.style.visibility = "visible";
		  }
		  else{ // DO HIDE
		  	myDiv.style.visibility = "hidden";
		  }
		}
	}
}


// cancella lo spazio "allocato" per la div quando la div è non visibile
function displayDiv(arrayOfDivId, bool){	
	
	var arrayOfElements = xGetElementById(arrayOfDivId);
	if (isArray(arrayOfElements)){ /*** ARRAY ***/
		for(var i=arrayOfDivId.length-1; i>=0; i--) {
		  var myDiv = xGetElementById(arrayOfDivId[i]);
		  if (bool){ // DO SHOW
			myDiv.style.display = 'block';
		  }
		  else{ // DO HIDE
		  	myDiv.style.display = 'none';
		  }
		}
	}
	else {
		if (arrayOfElements){ /*** 1 ELEMENT ***/
		  var myDiv = xGetElementById(arrayOfDivId);
		  if (bool){ // DO SHOW
			myDiv.style.display = 'block';
		  }
		  else{ // DO HIDE
		  	myDiv.style.display = 'none';
		  }
		}
	}

}	

// Chiude o apre la div, a seconda del suo stato attuale.
function hideOrDisplayDiv(divId){	
	displayDiv(divId, xGetElementById(divId).style.display === 'none');	
}

//////////////////////////////////////////////////////////////

// FUNZIONE CHE CATTURA L'EVENTO "Enter" E NE ANNULLA L'EFFETTO
// (SE AGGIUNTA COME document.onkeypress, SERVE PER DISABILITARE LA SUBMIT IN CASO DI EVENTO ENTER)
function handleEnter(theEvent) {
	
	if(!theEvent){ // IE: handleEnter è richiamata senza parametri, ma l'evento è reperibile da browser
		theEvent = event;
	}
	
    var keyCode = theEvent.keyCode ? theEvent.keyCode : theEvent.which ? theEvent.which : theEvent.charCode;
	if (keyCode === 13) {
		return false;
	} 
}      

/////// startsWith, endsWith //////////////////////////////////////////

String.prototype.startsWith = function(str){
	return (this.match("^"+str)==str);
}

String.prototype.endsWith = function(str){
	return (this.match(str+"$")==str);
}


/////// FUNZIONI TRIM //////////////////////////////////////////

function lTrim(sString){
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}
	return sString;
}


function rTrim(sString){
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}


function lTrimZero(sString){
	while (sString.substring(0,1) == '0'){
		sString = sString.substring(1, sString.length);
	}
	return sString;
}


function rTrimZero(sString){
	while (sString.substring(sString.length-1, sString.length) == '0'){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function trim(sString){
	return (lTrim(rTrim(sString)));
}

//////////////////////////////////////////////////////////////

function isArray(obj) {
	
	if (obj && typeof(obj) !== 'string' && obj.length && !obj.type){
		return true;
	}
	else{
		return false;
	}
	
}


/////// FUNZIONI CHE RILEVANO LA POSIZIONE ASSOLUTA DI UN OGGETTO IN UNA PAGINA //
function findX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
		}
	}
	return curleft;
}


function findY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curtop += obj.offsetTop
		}
	}
	return curtop;
}
//////////////////////////////////////////////////////////////////////////////////

// aggiunge alla url una coppia di valori parametro-valore
// se il parametro "parName" è già presente nella URL, viene aggiornato col nuovo valore
function addParameter (url, parName, parValue){
		
	if (url.indexOf('?') == -1){
		return url + "?"+parName+"="+parValue;
	}
	else{
		var param_idx = url.indexOf(parName+'=');
		if (param_idx == -1){
			return url + "&"+parName+"="+parValue;
		}
		else{ // parametro già presente -> aggiornamento valore
			
			var eq_idx = url.indexOf('=', param_idx);
			var and_idx = url.indexOf('&', eq_idx);

			var fineUrl;		
			if (and_idx == -1){
				fineUrl = '';
			}
			else{
				fineUrl = url.substring(and_idx);
			}
			
			return url.substring(0, eq_idx+1) + parValue + fineUrl;
			
		}
		
	}
}
// endPad sul valore "val", a cui vengono aggiunti una serie di 
// "paddingChar" in coda, fino a raggiungere la "desiredLength"
// return: valore
function endPad (val, paddingChar, desiredLength){

	var finalVal = val;
	for (i=0; i<(desiredLength - val.length); i++){
		finalVal =  finalVal + paddingChar ;
	}
	return finalVal;
}
// endPad sul textfield identificato da "textFieldId"
// return: void (il pad viene fatto direttamente sull'elemento)
function endPadText (textFieldId, paddingChar){
	var tf = xGetElementById(textFieldId);
	var initialVal = tf.value;
	if (tf.maxLength){
		tf.value = endPad(initialVal, paddingChar, tf.maxLength);
	}
	
}

// headPad sul valore "val", a cui vengono aggiunti una serie di 
// "paddingChar" in testa, fino a raggiungere la "desiredLength"
// return: valore
function headPad (val, paddingChar, desiredLength){

	var finalVal = val;
	for (i=0; i<(desiredLength - val.length); i++){
		finalVal = paddingChar + finalVal;
	}
	return finalVal;
}

// headPad sul textfield identificato da "textFieldId"
// return: void (il pad viene fatto direttamente sull'elemento)
function headPadText (textFieldId, paddingChar){
	var tf = xGetElementById(textFieldId);
	var initialVal = tf.value;
	if (tf.maxLength){
		tf.value = headPad(initialVal, paddingChar, tf.maxLength);
	}
	
}
//-------------------------------------------------------------------
// isBlank(value)
//   Returns true if value only contains spaces
//-------------------------------------------------------------------
function isBlank(val){
	if(val==null){return true;}
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
		}
	return true;
	}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
function isDigit(num) {
	if (num.length>1){return false;}
	var string="1234567890";
	if (string.indexOf(num)!=-1){return true;}
	return false;
	}


// isInteger(value)
//   Returns true if value contains all digits
//-------------------------------------------------------------------
function isInteger(val){
	if (isBlank(val)){return false;}
	for(var i=0;i<val.length;i++){
		if(!isDigit(val.charAt(i))){return false;}
		}
	return true;
}

// ritorna "true" se val è una sequenza di zeri, "false" altrimenti
function isSequenceOfZero(val){

	for (k=0; k<val.length; k++){
		if (val[k] !== '0'){
			return false;
		}
	}
	
	return true;
}

// la funzione da' il nome alla finestra principale della applicazione
// viene richiamata esclusivamente da CommonMenu.jsp
// Dare un nome preciso alla finestra principale torna utile per mantenere
// un riferimento quando piu' finestre si aprono vicendevolmente
// (vedi Sanzioni)
function nameMainWindow() {
	window.name = 'SportelloIciMain';
}
// la funzione ritorna il window handler alla finestra
//principale della applicazione
function getMainWindow() {
	return window.open('', 'SportelloIciMain');
}

function nameTmpWindow(){
	window.name = 'myNameTmpWindow';
}

function getTmpWindow() {
	return window.open('', 'myNameTmpWindow');
}

function getWindowByName(winName) {
	return window.open('', winName);
}


// Chiamata Ajax senza callback
// Viene chiamata la URL specificata con i parametri specificati
// parameters è una stringa del tipo "name1=value1&name2=value2&..."
function ajaxCall(url, parameters){
	var xmlHttp = CreateXmlHttpObject();
	if (xmlHttp==null){
		alert ("Browser does not support HTTP Request");
		return;
	}
	else{
		xmlHttp.open("POST", url, true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

		xmlHttp.send(parameters);
	}
}

function CreateXmlHttpObject(){
	var objXMLHttp=null;
	if (window.XMLHttpRequest){
		objXMLHttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject){
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
}

/////////////////////////////////////////////////////////////
// FUNZIONI PER GESTIRE L'ANOMALIA DI IE SUI <button>
	
// aggiunge a tutti i <button> un listener che, richiamato sull'onclick,
// modificherà il nome
// ESEGUITA SOLO SU IE
function transformButtonsForIE() {
	if(!isFirefox()) {
		var allButtons = xGetElementsByTagName("button");
		if(allButtons) {
			for(i = 0; i < allButtons.length; i++) {
				var myButton = allButtons[i];
				
				if(!myButton.id){myButton.id=myButton.name};
				
				 addEvent(myButton, 'onmousedown', modificaBottoni);
			}
		}
	}
}

// Funzione richiamata sull'evento "onclick" dei bottoni a cui
// è stato applicato il listener (vedi transformButtonsForIE)
function modificaBottoni(e) {
		
// 1) estrazione dell'elemento che ha scaturito l'evento
	var targ;
	if (!e) var e = window.event;
	if (e.target){
		targ = e.target;
	}
	else if (e.srcElement){
		targ = e.srcElement;
	}
	if (targ.nodeType == 3){ // defeat Safari bug
		targ = targ.parentNode;
	}
	
	
	// 2) riporta i nomi dei bottoni alla condizione originale 
	//    (toglie eventuale "NO_" aggiunto nella fase 4 in una precedente chiamata)
	var allButtons = xGetElementsByTagName("button");
	for(i = 0; i < allButtons.length; i++) {
	var myButton = allButtons[i];
		if(myButton.name.indexOf('#NO#_')==0){
			myButton.name = myButton.name.substring(5);
		}
	}
	
	// 3) toglie l'eventuale "NO_" dal nome dell'elemento che ha scaturito l'evento
	if(targ.name.indexOf('#NO#_')==0){
		targ.name=targ.name.substring(5);
	}
	
	// 4) aggiunge "NO_" a tutti i bottoni TRANNE A QUELLO CHE HA SCATURITO L'EVENTO
	for(i = 0; i < allButtons.length; i++) {
		var myButton = allButtons[i];
		if(myButton.name!=targ.name){
			myButton.name = '#NO#_'+myButton.name;
		}
	}			
	
}


function replaceButtonText(buttonId, text)
{
  if (document.getElementById)
  {
    var button=document.getElementById(buttonId);
    if (button)
    {
      if (button.childNodes[0])
      {
        button.childNodes[0].nodeValue=text;
      }
      else if (button.value)
      {
        button.value=text;
      }
      else //if (button.innerHTML)
      {
        button.innerHTML=text;
      }
    }
  }
}


//Garantisce il campo in maiuscolo  (tipico per codice fiscale)
function toUppercase(obj) {
	if(obj){
		obj.value = obj.value.toUpperCase();
	}
}


function randomString(length) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
    
    if (!length) {
        length = Math.floor(Math.random() * chars.length);
    }
    
    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

//////////////////////////////////////////////////////////////


function openWaitDialog(testo) { 
    Dialog.info(testo, {
    	showEffect:Element.show, 
    	hideEffect: Element.hide, 
    	zIndex: 2000,width:250, height:60, 
    	showProgress: true,
    	className: "alphacube",
    	title: "<a class=\"alphacube_info\" >Attendere</a>"
    });    
} 

function closeDialog(){
	Dialog.closeInfo();
}


function calcolaTimeout(testo){
	var timedefault = 2;
	var charLen = 15;		
	return timedefault + Math.floor(testo.length/charLen);
}
function calcolaDimensioni(testo){
	var heightdefault = 60;
	var heightdelta = 30;	
	if(testo.length > 84){
	return heightdefault + ( Math.ceil((testo.length - 84)/42) * heightdelta );
	}
	else return heightdefault ;
}

var timeout; 
function openInfoDialog(testo) { 
    Dialog.info(testo, {
    	showEffect:Element.show, 
    	hideEffect: Element.hide, 
    	zIndex: 2000,width:250, height:calcolaDimensioni(testo), 
    	showProgress: true,
    	className: "alphacube",
    	title: "<a class=\"alphacube_info\" >INFO</a>"
    });
    
    timeout=calcolaTimeout(testo);   
    setTimeout(infoTimeout, 1000); 
} 

function openErrorDialog(testo) { 	
    Dialog.info(testo, {
    	showEffect:Element.show, 
    	hideEffect: Element.hide, 
    	zIndex: 2000,width:250, height:calcolaDimensioni(testo), 
    	showProgress: true,
    	className: "alphacube",   
    	title: "<a class=\"alphacube_error\" >ERRORE</a>"
    });
    
    timeout=calcolaTimeout(testo);    
    setTimeout(infoTimeout, 1000); 
} 

function infoTimeout() { 
    timeout--; 
    if (timeout >0) {         
        setTimeout(infoTimeout, 1000) 
    } else 
        Dialog.closeInfo()
}  

function openConfirmDialog(testo,nomeBottone,idForm,formAction) { 	
	Dialog.confirm(testo, {
        className:"alphacube",
        width:300,          
        okLabel:"Sì",
        cancelLabel:"No",
        onCancel:function(win) { }, 
        onOk:function(win) {
        	$(idForm).action=formAction+'?'+nomeBottone;
            $(idForm).submit();
        }  
    });
} 

function confermaEliminazione(nomeBottone,idForm,formAction) { 
	openConfirmDialog("Procedere con l'eliminazione?",nomeBottone,idForm,formAction) ;
} 



function confermaEliminazioneAjax(ajaxAction){	
		Ext.MessageBox.show({
	        title:'CONFERMA',
	        msg: 'Sicuro di voler eliminare',
	        buttons: Ext.MessageBox.OKCANCEL,
	        fn: ajaxAction,                   
	        icon: Ext.MessageBox.QUESTION
	    });	
}



function setMultiModal(){
	Window.keepMultiModalWindow = true;
}


function transferToOpener(arrayOfIds, arrayOfValues) { 
	
	for(i = 0; i < arrayOfIds.length; i++) {
		if (arrayOfValues[i]){
			var unId = arrayOfIds[i];
			var unVal = arrayOfValues[i];
			var openerEl = window.opener.xGetElementById(unId);
			if (openerEl){
				openerEl.value = unVal;
			}
			else{
				openerEl = window.xGetElementById(unId);
				if (openerEl)
					openerEl.value = unVal;
			}
		}
		else
			break;
	}
	
	closeWindow();

}

function scrollToElement(theElement){
  var selectedPosX = 0;
  var selectedPosY = 0;
              
  while(theElement != null){
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }
            		      
 window.scrollTo(selectedPosX,selectedPosY);
}

