/*
 * Generic utility functions
 */
function Is() {
   agent = navigator.userAgent.toLowerCase();
   this.major = parseInt(navigator.appVersion);
   this.minor = parseFloat(navigator.appVersion);
   this.ns =((agent.indexOf('mozilla') != - 1) &&((agent.indexOf('spoofer') == - 1) &&(agent.indexOf('compatible') == - 1)));
   this.ns4 =(this.ns &&(this.major == 4));
   this.ns6 =(this.ns &&(this.major >= 5));
   this.ie =(agent.indexOf("msie") != - 1);
   this.ie3 =(this.ie &&(this.major < 4));
   this.ie4 =(this.ie &&(this.major == 4) &&(agent.indexOf("msie 5.0") == - 1));   this.ie5 =(this.ie &&(this.major == 4) &&(agent.indexOf("msie 5.0") != - 1));   this.ie55 =(this.ie &&(this.major == 4) &&(agent.indexOf("msie 5.5") != - 1));
   this.ie6 =(this.ie &&(agent.indexOf("msie 6.0") != - 1));
}
var is = new Is();

/*
 * Return true if the specified property is undefined
 */
function isUndefined(property) {
   return( typeof property == 'undefined');
}

/*
 * Return true if the specified property is defined
 */
function isDefined(property) {
   return( typeof property != 'undefined');
}

/*
 * Return true if the specified property is a function
 */
function isFunction(property) {
   return( typeof property == 'function');
}

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");

/*
 * Normalizes a string by removing any superfluous whitespace
 */
function normalizeString(s) {
   s = s.replace(whtSpMult, " ");
   s = s.replace(whtSpEnds, "");
   return s;
}

// Trim whitespace from left and right sides of s.
function trim(s) {
    return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

/*
 * Generic DOM functions
 */	
function findParentTag(item, tagName, stopTag) {
   if(stopTag == null) {
      stopTag = "HTML";
   }
   while(item != null && item.tagName != tagName && item.tagName != stopTag) {
      item = item.parentNode;
   }
   return item;
}

/*
 * Inserts a new child after a specified DOM node
 */
function insertAfter(newChild, refChild) {
   var parent = refChild.parentNode;
   if(parent.lastChild == refChild) {
      return parent.appendChild(newChild);
   }
   else {
      return parent.insertBefore(newChild, refChild.nextSibling);
   }
}

/*
 * Removes from the DOM of a table any empty nodes which may be the result of HTML parsing
 */
function removeTableEmptyNodes(t) {
   var row = t.firstChild;
   while(row) {
      var nextRow = row.nextSibling;
      if(!row.tagName) {
         t.removeChild(row);
      }
      else {
         var column = row.firstChild;
         do
         {
            var nextColumn = column.nextSibling;
            if(!column.tagName) {
               row.removeChild(column);
            }
            column = nextColumn;
         }
         while(column);
      }
      row = nextRow;
   }
}

/*
 * Retrieves recursively the text value of a node and its children
 */
function getTextValue(el) {
   
   if (el==null) return "";
   
   var s = "";
   var node = el.firstChild;
   while(node) {
      if(node.nodeType == document.TEXT_NODE || node.nodeType == document.CDATA_SECTION_NODE) {
         s += node.nodeValue;
      }
      else {
         if(node.nodeType == document.ELEMENT_NODE) {
            if(node.tagName == "BR") {
               s += " ";
            }
            else if(node.tagName == "INPUT") {
               s += node.value;
            }
         }
         else {
            s += getTextValue(node);
         }
      }
      node = node.nextSibling;
   }
   return normalizeString(s);
}

/*
 * Returns the absolute horizontal position of an element
 */
function getElementX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}

/*
 * Returns the absolute vertical position of an element
 */
function getElementY(obj)
{
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}
/*
 * Toggles the visibility of an element
 */
function toggleElementVisibility(el) {
	if (el!=null) el.style.visibility = el.style.visibility=='visible'?'hidden':'visible';
}
/*
 * Shows an element
 */
function showElement(el) {
	if (el!=null) el.style.visibility = 'visible';
}

/*
 * Hides an element
 */
function hideElement(el) {
	if (el!=null) el.style.visibility = 'hidden';
}

/*
 * Returns whether an element is visible
 */
function isElementVisible(el) {
	return el.style.visibility=='visible';
}

/*
 * Moves an element to the specified coordinates
 */
function moveElement(el, x, y) {
	el.style.left = x+"px";
	el.style.top = y+"px";
}

/* 
 * Returns the document's body
 */
function getDocumentBody() {
	return document.getElementsByTagName("BODY").item(0);
}

/*
 * Event handling
 */
function addEvent(el, evname, func) {
   if(el.attachEvent) {
      // IE
      el.attachEvent("on" + evname, func);
   }
   else if(el.addEventListener) {
      el.addEventListener(evname, func, true);
   }
   else {
      el["on" + evname] = func;
   }
}


/*
 * Removes an event from an element
 */
function removeEvent(el, evname, func) {
	if(isDefined(el.detachEvent)) {
		el.detachEvent("on"+evname, func);
	} else if(el.removeEventListener) {
		el.removeEventListener(evname, func, true);
	} else {
		el["on"+evname] = null;
	}
}

/*
 * Cancels an event so it doesn't propagate to other elements
 */
function cancelEvent(e) {
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	} else {
		e.cancelBubble = true;
		e.returnValue = false;
	}
}

function triggerMouseEvent(name, elementId) {
	var ev;
	if(document.createEvent) {
		ev = document.createEvent("MouseEvents");
		ev.initEvent(name, true, true);
		document.getElementById(elementId).dispatchEvent(ev);
	} else {
		ev = {};
		ev.type = name;
		ev.bubbles = true;
		ev.cancelable = true;
		document.getElementById(elementId).fireEvent("on"+name);
	}
}

/* 
 * Retrieves the element which caused the event
 */
function getEventElement(e) {
	return (e.target || e.srcElement);
}

/*
 * Memory Management for IE
 */
function addDestructor(object, destructor) {
	if(is.ie) {
		var win = window.document.defaultView || window.document.parentWindow;
		var o = object;
		object._onunload = function() {
			eval("o."+destructor+"()");
			removeEvent(win, "unload", o._onunload);
			o._onunload = null;
		};      
		addEvent(win, "unload", object._onunload);
	}
}

/*
 *
 */
function Event() {
   this.events = new Array();
   this.ieSet = false;
}

Event.prototype.addOnLoad = function(f) {
   this.events.push(f);
   if(isDefined(window.addEventListener)) {
      window.addEventListener('load', f, false);
   }
   else if(!this.ieSet) {
      if(isDefined(document.onreadystatechange)) {
         document.onreadystatechange = this.onLoad;
      }
   }
   this.ieSet = true;
};
Event.prototype.onLoad = function() {
   var m = /mac/i.test(navigator.platform);
   if(!isUndefined(document.readyState)) {
 
      if(m ? document.readyState != 'interactive' : document.readyState != 'complete') {
         return;
      }
   }
   for(var i = 0, f;(f =(i < this.events.length) ? this.events[i] : null); i++) {
      f();
   }
   return;
};
var eventManager = new Event();

function getDomDocumentPrefix() {
	if (getDomDocumentPrefix.prefix) {
		return getDomDocumentPrefix.prefix;
	}
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".DomDocument");
			return getDomDocumentPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	throw new Error("Could not find an installed XML parser");
}

function getXmlHttpPrefix() {
	if (getXmlHttpPrefix.prefix)
		return getXmlHttpPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".XmlHttp");
			return getXmlHttpPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

function XmlHttp() {}

XmlHttp.create = function () {
	try {
		if (window.XMLHttpRequest) {
			var req = new XMLHttpRequest();
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (req.readyState == null) {
				req.readyState = 1;
				req.addEventListener("load", function () {
					req.readyState = 4;
					if (typeof req.onreadystatechange == "function")
						req.onreadystatechange();
				}, false);
			}
			
			return req;
		}
		if (window.ActiveXObject) {
			return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
		}
	}
	catch (ex) {}
	// fell through
	throw new Error("Your browser does not support XmlHttp objects");
};

// XmlDocument factory
function XmlDocument() {}

XmlDocument.create = function () {
	try {
		// DOM2
		if (document.implementation && document.implementation.createDocument) {
			var doc = document.implementation.createDocument("", "", null);
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (doc.readyState == null) {
				doc.readyState = 1;
				doc.addEventListener("load", function () {
					doc.readyState = 4;
					if (typeof doc.onreadystatechange == "function")
						doc.onreadystatechange();
				}, false);
			}
			
			return doc;
		}
		if (window.ActiveXObject)
			return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlDocument objects");
};

// Create the loadXML method and xml getter for Mozilla
if (window.DOMParser &&
	window.XMLSerializer &&
	window.Node && Node.prototype && Node.prototype.__defineGetter__) {

	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	//XMLDocument.prototype.loadXML = 
	Document.prototype.loadXML = function (s) {
		
		// parse the string to a new doc	
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
		
		// remove all initial children
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);
			
		// insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			this.appendChild(this.importNode(doc2.childNodes[i], true));
		}
	};
	
	
	/*
	 * xml getter
	 *
	 * This serializes the DOM tree to an XML String
	 *
	 * Usage: var sXml = oNode.xml
	 *
	 */
	Document.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
}

function XMLLoadSync(method, url) {
	var xmlHttp = XmlHttp.create();
	xmlHttp.open(method, url, false);
	xmlHttp.send(null);
	return xmlHttp.responseXML;
}

function XMLLoadAsync(method, url, f) {
	var xmlHttp = XmlHttp.create();
	xmlHttp.open(method, url, true);
	xmlHttp.onreadystatechange = function () {
		if (xmlHttp.readyState == 4)
			f(xmlHttp.responseXML);
	}
	xmlHttp.send(null);
}

/*
 * Cookie handling
 */
function getCookie(name) {
   if(document.cookie.length > 0) {
	   //alert(document.cookie);
      var begin = document.cookie.indexOf(name + "=");
      if(begin >= 0) {
         begin += name.length + 1;
         var end = document.cookie.indexOf(";", begin);
         if(end < 0) end = document.cookie.length;
         return unescape(document.cookie.substring(begin, end));
      }
   }
   return null;
}

function delCookie(name) {
   if(getCookie(name)) {
      document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
}
function setCookie(name, value, expire) {
   var expireDate = new Date();
   path="/";
   expireDate.setTime(expireDate.getTime() +(expire * 24 * 3600 * 1000));
   document.cookie = name + "=" + escape(value) +((expire == null) ? "" : "; expires=" +
   expireDate.toGMTString()) + "; path=" + path ;
}

/*
*
* funzioni per gestire le funzioni da eseguire su onload/onunload
*
*/

// array to hold all onLoad functions
onLoadFunctions = new Array();
// array to hold all onUnload functions
onUnloadFunctions = new Array();
// array to hold all onUnload functions
onResizeFunctions = new Array();

// this runs on each page
function _initOnLoadFunctions() {
   // loop through all the items in the onLoad array
   // and execute any functions
   for(var i = 0; i < window.onLoadFunctions.length; i++) {
      if( typeof window.onLoadFunctions[i] == "function") window.onLoadFunctions[i]();
   }
}

function addOnLoad(func) {
   window.onLoadFunctions[window.onLoadFunctions.length] = func;
}

// this runs on each page
function _initOnResizeFunctions() {
   // loop through all the items in the onLoad array
   // and execute any functions
   for(var i = 0; i < window.onResizeFunctions.length; i++) {
      if( typeof window.onResizeFunctions[i] == "function") window.onResizeFunctions[i]();
   }
}

function addOnResize(func) {
   window.onResizeFunctions[window.onResizeFunctions.length] = func;
}

// this runs on each page

function _initOnUnloadFunctions() {
   // loop through all the items in the onUnload array
   // and execute any functions
   for(var i = 0; i < window.onUnloadFunctions.length; i++) {
      if( typeof window.onUnloadFunctions[i] == "function") window.onUnloadFunctions[i]();
   }
}

function addOnUnload(func) {
   window.onUnloadFunctions[window.onUnloadFunctions.length] = func;
}

function getApplicationContext() {
        var s = document.location.pathname.split("/");
        if(s.length<2) {
                return "";
        } else {
                return "/"+s[1];
        }
}

window.applicationContext = getApplicationContext();
/*
 * Initialization
 */
// Necessary for IE
if(document.ELEMENT_NODE == null) {
   document.ELEMENT_NODE = 1;
   document.TEXT_NODE = 3;
   document.CDATA_SECTION_NODE = 4;
}

// funzioni per verificare se un evento si verifica direttamento su un elemento
function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}

function checkMouseEnter (element, evt) {
  if (element.contains && evt.fromElement) {
    return !element.contains(evt.fromElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function showTransient(id) {
	var tr= document.getElementById(id);
	showElement(tr);
}
