function addListener(element, event, listener, bubble)
{
	if(element.addEventListener) {
		if(typeof(bubble) == "undefined") bubble = false;
		element.addEventListener(event, listener, bubble);
	} else if(this.attachEvent) {
		element.attachEvent("on" + event, listener);
	}
}

/*addListener(this, "load", function() { clear_wait(); });
addListener(window, "load", function() { clear_wait(); });*/

function clear_wait() 
{
	var wait_obj = document.getElementById('wait_obj');
	
	if (wait_obj.style.display.toLowerCase() == 'none')
		return;
	
	try { wait_obj.filters[0].Apply(); } catch(e) {}
	wait_obj.style.backgroundColor = '';
	try { wait_obj.filters[0].Play(); } catch(e) {}
	
	var duration = 0;
	try { duration = wait_obj.filters[0].Duration; } catch(e) {}
	
	setTimeout(function() { document.getElementById('wait_obj').style.display = 'none'; }, 
			(duration * 1000) + 50);
	
	return;
}

function setCookie(name, value, days)
{
	var expires = '';
	if (days) { var date = new Date(); date.setTime(date.getTime()+(days*86400000/*24*60*60*1000*/)); expires = '; expires='+date.toGMTString(); }
	document.cookie = name+'='+escape(value)+expires+'; path=/';
}

function getCookie(name)
{
	var ca = document.cookie.split(';'); 
	var nameEQ = name + "=";
	for(var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
		if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length, c.length));
	}
	return null;
}
function eraseCookie(name) { setCookie(name, '', -1); }

// ----------
window.getDialogReturn = function() { return window.returnValue; };
window.setDialogReturn = function(value) { window.returnValue = value; return window.returnValue; };
window.getDialogArguments = function() { return window.dialogArguments; };
window.setDialogArguments = function(value) { window.dialogArguments = value; return window.dialogArguments; };

if (!window.showModalDialog)
{
	window.getDialogReturn = function() { return getCookie('dialogReturn'); };
	window.setDialogReturn = function(value) { setCookie('dialogReturn', value); return getCookie('dialogReturn'); };
	window.getDialogArguments = function() { return getCookie('dialogArguments'); };
	window.setDialogArguments = function(value) { return setCookie('dialogArguments', value); return getCookie('dialogArguments'); };
	
	window.showModalDialog = function(sURL, vArguments, sFeatures)
	{
		if (sFeatures == null || sFeatures.match(/\s+/gi))
			sFeatures = '';
		else
		{
			var sFeaturesArray = sFeatures.replace(';', ',').split(',');
			var rFeatures = '';
			for (var key in sFeaturesArray)
				if (!sFeaturesArray[key].match(/(dependent|modal|dialog)=.*/ig))
					rFeatures += sFeaturesArray[key] + ',';

			if (rFeatures.length <= 0) rFeatures += ',';
			
			sFeatures = rFeatures;
		}
		
		sFeatures = sFeatures.replace('dialogHeight', 'height').replace('dialogWidth', 'width') + 'modal=1';
		//alert("calling: window.open('"+sURL+"', 'win', '"+sFeatures+"', "+vArguments+");");
		var val = '';
		try 
		{
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect UniversalBrowserWrite"); 
			var vWin = window.open(sURL, 'win', sFeatures, vArguments);
			netscape.security.PrivilegeManager.revertPrivilege("UniversalXPConnect UniversalBrowserWrite"); 
		} catch (ex) {
			alert(ex); //'Non sono stati impostati i permessi per la finestra dialog.');
			return null;
		}
		val = window.getDialogReturn();
		window.setDialogReturn('');
		return val;
	};
}

// recupera la versione stampabile di un form
function getPrintable(elementName)
{
	if (!document.getElementById(elementName))
		return "";
	var form = document.getElementById(elementName).cloneNode(true);
	for (i=0; i<form.all.length; i++)
	{
		switch (form.all[i].tagName.toUpperCase()) 
		{
			case "SELECT": 
				form.all[i].insertAdjacentHTML("afterEnd", "<b>" + form.all[i][document.getElementById(form.all[i].id).selectedIndex].innerText + "</b>");
				form.all[i].style.display="none";
				break;
			case "TEXTAREA": 
				form.all[i].insertAdjacentHTML("afterEnd", "<b>" + form.all[i].innerText.replace("\r\n","<br>") + "</b>");
				form.all[i].style.display="none";
				break;
			case "INPUT": 
				if (form.all[i].type=="text")
				{
					form.all[i].style.display="none";
					form.all[i].insertAdjacentHTML("afterEnd", "<b>" + form.all[i].value + "</b>");
				}
				else 
				{
					if (form.all[i].type=="radio")
					{
						if (document.getElementById(form.all[i].id).checked==true)
						{
							if (form.all[i].value=="true")
								form.all[i].insertAdjacentHTML("afterEnd", "<b>SI</b>");
							else
								form.all[i].insertAdjacentHTML("afterEnd", "<b>NO</b>");
						}
					}
				}
				form.all[i].style.display="none";
				break;
			case "IMG":	
				form.all[i].style.display="none";
				break;
			case "LABEL":	
				form.all[i].style.display="none";
				break;
		}
		
	}
	return form.innerHTML;
}
// stampa il video relativamente alle tabs specificate (separate da ";". "-" per una interruzione di pagina)
var wPrintPreview = null;
function PrintTabs(tabsToPrint)
{
	if (tabsToPrint=="")
		return;
	var tabs = tabsToPrint.split(";");
	wPrintPreview = window.open("about:blank", "AnteprimaStampa", "toolbar=0, status=0, location=0, menubar=0, resizable=1, top=0, left=0, width=" + screen.availWidth-5 + ", height=" + screen.availHeight-20 + ", scrollbars=1");
	wPrintPreview.document.title="Anteprima di stampa";
	wPrintPreview.document.createStyleSheet(Application_commonroot + "css/PrintFormPage.css");
	var text = "";
	for (j=0; j<tabs.length; j++)
	{
		if (tabs[j]=="-") // - indica una interruzione di pagina
			text += "<div style=\"page-break-before: always\"></div>";
		else
			text += getPrintable(tabs[j]);
	}
	text+='<style type="text/css" media="print">.hiddenOnPrint {display: none; } .hiddenOnPrint2 {display: none; }</style>';
	text+='<br/><div align="right" width="100%" class="hiddenOnPrint">' +
	'	<img border="0" id="Conferma" name="Conferma" style="cursor:hand" src="' + Application_commonroot + 'icons/conferma.jpg" onclick="javascript:window.print(); window.close()" alt="Conferma">' +
	'	&nbsp;&nbsp;' +
	'	<img border="0" id="Annulla" name="Annulla" style="cursor:hand" onclick="window.close()" src="' + Application_commonroot + 'icons/annulla.jpg" alt="Annulla">' +
	'</div>';
	wPrintPreview.document.body.innerHTML=text;
}




// Funzione per gestire i messaggi di avviso
function MessageBox(Text, MessageMode)
{
	if (MessageMode=="alert")
	{
		alert(Text);
	}
	else
	{
		if (confirm(Text)) 
		{ 
			document.getElementById("__IgnoreWarnings").value = 'true'; 
			document.getElementById("__Save").click(); 
		} 
		else
			document.getElementById("__IgnoreWarnings").value = 'false';
	}
}


function Navigate(dir)
{
	var codes = document.getElementById("__Navigation").value;
	var OID = document.getElementById("__ObjectCode").value;
	
	if (codes == null || codes == '' || codes == 'undefined') return;
	
	if (OID == null || OID == '' || OID == 'undefined') return;
	
	
	var codeArray = codes.split(';');
	
	for (i = 0; i < codeArray.length; i++)
	{
		if (codeArray[i].toLowerCase() != OID.toLowerCase())
			continue;

		var xdir = dir.toLowerCase();
		if (xdir == 'next') j = i+1;
		else if (xdir == 'previous') j = i-1;
		else if (xdir == 'first') j = 0;
		else j = codeArray.length-1;
		
		if (i != j && (	(j < codeArray.length && (xdir == 'next' || xdir == 'last')) ||
						(j >= 0 && (xdir == 'previous' || xdir == 'first')) ))
		{
			document.getElementById('__ObjectCode').value = codeArray[j];
			
			var navRe = /Navigating/i;
			var navPos = document.forms.item(0).action.search(navRe);
			if (navPos == -1)
			{
				var piPos = document.forms.item(0).action.indexOf('?');
				
				if (piPos == -1) {
					document.forms.item(0).action += "?";
				} else {
					if (document.forms.item(0).action.substr(piPos).length > 0)
						document.forms.item(0).action += "&";
				}
				document.forms.item(0).action += "Navigating=true";
			}
			
			document.getElementById("__GetOne").click();
			break;
		}
	}
}

function StartPrint(id,title)
{
	var Table = document.getElementById(id);
	var vet = new Array();
	vet[0] = Table;
	var result = window.showModalDialog(Application_root + "PrintViewForm.aspx?title="+title, vet, "scroll: Auto; dialogHeight: 680px; dialogWidth: 1000px; edge: Raised; center: Yes; help: No; resizable: Yes; status: No;");
}

function PrintCalendar(id)
{
	var Table = document.getElementById(id);
	var vet = new Array();
	vet[0] = Table;
	var result = window.showModalDialog(Application_root + "PrintCalendarForm.aspx", vet, "scroll: No; dialogHeight: 680px; dialogWidth: 1000px; edge: Raised; center: Yes; help: No; resizable: Yes; status: No;");
}

function OnDeleteClick()
{
	var retValue = false;
	var OID = new String(document.getElementById("__ObjectCode").getAttribute("value"));
	if (OID!="" && OID!="undefined" && OID!="null")
	{ 
		retValue = (confirm("Confermi l'eliminazione di questo documento?"));
	} 
	else
	{
		alert("Nessun documento da eliminare");
		retValue = false;
	}
	return retValue;
}


var SearchWindowRef;
function FormSearch()
{
	
	if (SearchWindowRef != null)
		SearchWindowRef.close();
		
	SearchWindowRef = self.open(Application_root+"SearchResultForm.aspx?DataContext=", 'SearchFormBox', 
		'height=520,width=950,menubar=no,toolbar=no,location=no,directories=no,statusbar=no,resizable=yes,scrollbars=no,dependent=yes,chrome=yes');
	SearchWindowRef.WindowRef = self;
	SearchWindowRef.OnIdUpdate = OnFormClick;
	return;
}

function OnFormClick(result)
{				
	var codice = new String(result[0]);
	if (codice == null) codice = '';
	if (!codice.match(/[0-9A-Z]{6}/i)) codice = '';
	this.WindowRef.document.getElementById("__ObjectCode").value = codice;
	if (codice != '')
	{

		var navigation = new String(result[3]);
		if (navigation == null) codice = '';
		if (!navigation.match(/[0-9A-Z]{6}/i)) navigation = '';
		this.WindowRef.document.getElementById("__Navigation").value = navigation;
		this.WindowRef.document.getElementById("__GetOne").click();
	}
	

}


function OnSearchBoxFormClick(result)
{
	
		
		var codice = new String(result[0]);
		var id = this.id;
		
		if (codice == null) codice = '';
		if (!codice.match(/[0-9A-Z]{6}/i)) codice = '';
		
		if (codice != '')
		{
			this.WindowRef.document.getElementById(id + 'thisCode').value = codice;
			this.WindowRef.document.getElementById(id).value = result[1];
			this.WindowRef.document.getElementById(id + "PrevText").value = result[1];
			this.WindowRef.document.getElementById(id + "FieldValues").value = result[2];
			if (this.WindowRef.document.getElementById(id + "SubmitAfterFill"))
				this.WindowRef.document.getElementById(id + "SubmitAfterFill").click();
		}
		
		//PopupSearchWindowRef=null;
}

function FieldValidator(id, context, controlType, validatorType, validatorArgs, errorMessage)
{
	// id del controllo da validare
	this.Id = id;
	// risultato della validazione sul controllo
	this.IsValid = true;
	// il nome della tabella/classe a cui fa riferimento
	this.Context = context;
	// il tipo di validatore (ex SearchFound, Required, Range, RegExpr ecc)
	this.ValidatorType = validatorType;
	// messaggio di alert per l'utente
	this.ErrorMessage = errorMessage;
	// indica il tipo di controllo da validare
	this.ControlType = controlType;
	// indica dei parametri per il validatore (ex range di valori, esprssioni regolari ecc.)
	this.ValidatorArgs = validatorArgs;
}

function PageValidator()
{
	this.Validators = new Array();
	var oThis = this;
	// risultato della validazione sul form
	this.IsValid = true;
	// Contesto su cui opera la validazione (nome tabella/vista)
	this.ValidationContext = "";
	
	this.ContextValidators = null;
	this.setValidationContext = function (context) 
	{ 
		oThis.ValidationContext = context;
		oThis.ContextValidators = new Array(); 
		for (i=0; i<oThis.getLength(); i++)
		{
			if (oThis.Validators[i].Context == context)
				oThis.ContextValidators.push(oThis.Validators[i]);
		}
	}
	
	this.getLength = function () { return oThis.Validators.length; }
}

PageValidator.prototype.Add = function (fValidator) 
{
	this.Validators.push(fValidator);
}

// effettua la validazione nel caso di azione salva
PageValidator.prototype.ValidateOnSave = function (Context) 
{
	this.setValidationContext(Context);
	this.IsValid = true;

	for (i=0; i<this.ContextValidators.length; i++)
	{
		switch (this.ContextValidators[i].ValidatorType)
		{
			case "Required" : this.ValidateRequiredValidator(this.ContextValidators[i]);
				break;
			case "RequiredIF" : this.ValidateRequiredIFValidator(this.ContextValidators[i]);
				break;
			case "SearchFound" : this.ValidateSearchFoundValidator(this.ContextValidators[i]);
				break;
			case "eMailFormat" : this.ValidateEmailFormatValidator(this.ContextValidators[i]);
				break;
		}
		
		
		this.IsValid = this.IsValid && this.ContextValidators[i].IsValid;
		
	}
	
	return this.IsValid;
	
}

PageValidator.prototype.ValidateEmailFormatValidator = function (validator) 
{
	if (validator.ControlType=="eMailTextBox")
	{
		var objValidator = findObj(validator.Id);
		var objErr = findObj(validator.Id + "ErrorIcon");
		
		if (objErr[0])
			objErr = objErr[0];
		
		if (!objValidator || !objErr.style)
			return false;
		
		var Text = objValidator.value; //.getAttribute("value");
		var re = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
		var rx = new RegExp(re);
		var matches = rx.exec(Text);
		if ((matches != null && Text == matches[0]) || Text=="")
		{
			validator.IsValid=true;
			objErr.style.display  = "none";
		}
		else
		{
			validator.IsValid=false;
			objErr.style.display  = "inline";
		}
	}
}

PageValidator.prototype.ValidateRequiredValidator = function (validator) 
{
	if (!validator)
		return;
		
	validator.IsValid = true;

	var objValidator = null;
	var objRequiredErrorIcon = findObj(validator.Id + "RequiredErrorIcon");	
	
	if (!objRequiredErrorIcon)
		return;
	
	if (validator.ControlType=="SearchTextBox" || 
		validator.ControlType=="MaskTextBox" || 
		validator.ControlType=="BaseTextBox" || 
		validator.ControlType=="ImageBrowserTextBox" || 
		validator.ControlType=="eMailTextBox")
	{	
		objValidator = findObj(validator.Id);
		
		if (!objValidator || !objRequiredErrorIcon)
			return;
		
		validator.IsValid = objValidator.value.replace('/\s/', '') != '';
	}
	else if (validator.ControlType=="RadioYesNo")
	{
		var objYes = findObj(validator.Id + "_0");
		var objNo = findObj(validator.Id + "_1");
		
		validator.IsValid= (objYes.checked || objNo.checked);
	}
	else if (validator.ControlType=="ChooseList")
	{
		objValidator = findObj(validator.Id);
		if (!objValidator)
			return;

		var index = objValidator.selectedIndex;
		validator.IsValid = index!=0;
	}
	else if (validator.ControlType=="CheckList")
	{
		validator.IsValid = false;
		var listLength = validator.ValidatorArgs;
		for (chkI=0; chkI<listLength; chkI++)
		{
			var objChkI = findObj(validator.Id+"_"+chkI);
			if (objChkI.checked)
			{
				validator.IsValid = true;
				break;
			}
		}
			
	}
	else if (validator.ControlType=="SelectList")
	{
		objValidator = findObj(validator.Id+'_Value');
		if (!objValidator)
			return;
			
		validator.IsValid = (objValidator.value.replace(/\s/,'')!='') ? true : false;
	}
	else
	{
		// qui altri controlli
	}

	objRequiredErrorIcon.style.display  = (validator.IsValid) ? "none" : "inline";
}

PageValidator.prototype.ValidateRequiredIFValidator = function (validator) 
{
	var IFCondition = eval(validator.ValidatorArgs);

	if (IFCondition==null || IFCondition=="undefined" || IFCondition==false)
	{
		validator.IsValid=true;
		document.getElementById(validator.Id + "RequiredErrorIcon").style.display  = "none";
	}
	else
	{
		this.ValidateRequiredValidator(validator);
	}
}

PageValidator.prototype.ValidateSearchFoundValidator = function (validator) 
{
	if (validator.ControlType=="SearchTextBox")
	{

		var Text = document.getElementById(validator.Id).getAttribute("value");
		var PrevText = document.getElementById(validator.Id + "PrevText").getAttribute("value");
		var thisCode = document.getElementById(validator.Id + "thisCode").getAttribute("value");
		if (Text!="" && (thisCode=="" || Text!=PrevText))
			validator.IsValid=false;
		else
			validator.IsValid=true; 		
	}
}

function decimalRound(toRound,number)
{
	rounded = Math.round(toRound*Math.pow(10,number))/Math.pow(10,number);
	return rounded;
}

function ctrlModified(datacontext)
{
	var objCheckOnSave = document.getElementById('__ConfirmOnClose');
	if (objCheckOnSave) 
		objCheckOnSave.value = '1';
}

/* from ajax.js */

// XML DOM
function loadXmlDoc(xmlFile, cbFun)
{
	var xdoc;
	
	if ( window.ActiveXObject && /Win/.test(navigator.userAgent) )
	{
		xdoc = new ActiveXObject("Microsoft.XMLDOM");
		
		xdoc.async = false;
		xdoc.load(xmlFile);
		
		cbFun(xdoc);
		
		return true;
	}
	else if ( document.implementation && document.implementation.createDocument )
	{
		xdoc = document.implementation.createDocument("", "", null);
		xdoc.load(xmlFile);
		
		xdoc.onload = function() { cbFun(xdoc); }
	
		return true;
	}
	
	return false;
}

function getXmlHttp(handler)
{ 
	var objXmlHttp = null;
	var objName = '';
	
	if (navigator.userAgent.indexOf("MSIE")  >= 0)
		objName = (navigator.appVersion.indexOf("MSIE 5.5")>=0) ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP";

	if (objName != '')
	{
		try {
		objXmlHttp = new ActiveXObject(objName);
		objXmlHttp.onreadystatechange = handler;
		} catch(e) {
			alert(e.description);
			objXmlHttp = null;
		}
	} else {
		objXmlHttp = new XMLHttpRequest();
		objXmlHttp.onload = handler;
		objXmlHttp.onerror = handler;
	}
	
	return objXmlHttp;
}

function getAsyncData(url)
{
    var value = null;
    try
    {
        var objXmlHttp = getXmlHttp(null);
        
        var rand = ((url.match(/[?]/i)) ? '&_rand=' : '?_rand=') + Math.random();
        
        objXmlHttp.open('GET', url + rand, false);
        objXmlHttp.send(null);
        value = objXmlHttp.responseText;
    } 
    catch (e) { }
    
    return value;
}

/* utilità */

function $(id)
{
    return document.getElementById(id);
}

function fillComboBox(id, data, addempty)
{
    if (data == null || !data.match(/\S+/))
        return;
        
	var combo = document.getElementById(id);
	while (combo.options.length > 0)
	    combo.remove(combo.options[0]);
	
	if (addempty)
	{
	    var emptyopt = document.createElement('option');
	    emptyopt.text = '';
	    emptyopt.value = '';
	    try { combo.add(emptyopt, null); }
	    catch(e) { combo.add(emptyopt); }
	}
	
	for (var subdat in data.split('\x01'))
	{
	    var keyvalue = subdata.split('\x02');
    	var opt = document.createElement('option');
    	opt.value = keyvalue[0];
    	opt.text = keyvalue[1];
    	
    	try { combo.add(opt, null); }
    	catch(e) { combo.add(opt); }
    }
    
	combo.selectedIndex = 0;
	return;
}

//
// Metodi per le stringhe: trim(), trimLeft(), trimRight(), padLeft(), padRight()
//
if (String.prototype.padLeft == null)
String.prototype.padLeft = function(totalWidth, paddingChar) {
    var re = new RegExp('.{'+totalWidth+'}$');
    var pad = '';
    while (pad.length < totalWidth)
        pad += paddingChar;
    return new String(re.exec(pad + this.valueOf()));
}
if (String.prototype.padRight == null)
String.prototype.padRight = function(totalWidth, paddingChar) {
    var re = new RegExp('^.{'+totalWidth+'}');
    var pad = '';
    while (pad.length < totalWidth)
        pad += paddingChar;
    return new String(re.exec(this.valueOf() + pad));
}
if (String.prototype.trim == null)
String.prototype.trim = function()
{
    var search = '\\s';
    if (arguments.length > 0) {
        search = '['
        for (i=0; i<arguments.length; i++)
            search += arguments[i];
        search += ']';
    }
    var str = this.valueOf();
    str = eval('str.replace(/^'+search+'+|'+search+'+$/g, "");');
    return new String(str);
}
if (String.prototype.trimLeft == null)
String.prototype.trimLeft = function() {
    var search = '\\s';
    if (arguments.length > 0) {
        search = '['
        for (i=0; i<arguments.length; i++)
            search += arguments[i];
        search += ']';
    }
    var str = this.valueOf();
    str = eval('str.replace(/^'+search+'+/, "");');
    return new String(str);
}
if (String.prototype.trimRight == null)
String.prototype.trimRight = function() {
    var search = '\\s';
    if (arguments.length > 0) {
        search = '['
        for (i=0; i<arguments.length; i++)
            search += arguments[i];
        search += ']';
    }
    var str = this.valueOf();
    str = eval('str.replace(/'+search+'+$/, "");');
    return new String(str);
}