if(typeof(isIE) == 'undefined') isIE = (navigator.userAgent.toLowerCase().indexOf("msie") != -1) ;
if(typeof(isMoz) == 'undefined')  isMoz = !isIE;

//Possible prefixes ActiveX strings for DOM DOcument
var ARR_ACTIVEX = ["MSXML4.DOMDocument", "MSXML3.DOMDocument", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XmlDom"];

//When the proper prefix is found, store it here
var STR_ACTIVEX = "";

//-----------------------------------------------------------------
// IE Initialization
//-----------------------------------------------------------------

//if this is IE, determine which string to use
if (isIE) {
    //define found flag
    var bFound = false;
    
    //iterate through strings to determine which one to use (NCZ, 1/30/02)
    for (var i=0; i < ARR_ACTIVEX.length && !bFound; i++) {
    
        //set up try...catch block for trial and error of strings (NCZ, 1/30/02)
        try {
        
            //try to create the object, it will cause an error if it doesn't work (NCZ, 1/30/02)
            var objXML = new ActiveXObject(ARR_ACTIVEX[i]);
            
            //if it gets to this point, the string worked, so save it and return
            //the DOM Document (NCZ, 1/30/02)
            STR_ACTIVEX = ARR_ACTIVEX[i];
            bFound = true                
        
        } catch (objException) { 
        } //End: try
    } //End: for

    //if we didn't find the string, send an error (NCZ, 1/30/02)
    if (!bFound)
       throw "No DOM DOcument found on your computer."

} //End: if

//-----------------------------------------------------------------
// Mozilla Initialization
//-----------------------------------------------------------------
if (isMoz) {
    
    //add the loadXML() method to the Document class
    Document.prototype.loadXML = function(strXML) {
    
        //change the readystate
        changeReadyState(this, 1);

        //create a DOMParser
        var objDOMParser = new DOMParser();
        
        //create new document from string
        var objDoc = objDOMParser.parseFromString(strXML, "text/xml");
        
        //make sure to remove all nodes from the document
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);
            
        //add the nodes from the new document
        for (var i=0; i < objDoc.childNodes.length; i++) {
            
            //import the node
            var objImportedNode = this.importNode(objDoc.childNodes[i], true);
            
            //append the child to the current document
            this.appendChild(objImportedNode);
        
        } //End: for
        
        //we can't fire the onload event, so we fake it
        handleOnLoad(this);
        
    } //End: function
    

	Document.prototype.transformNodeToObject = function(stylesheet, outputObject){
		var xsltProcessor = new XSLTProcessor();
		xsltProcessor.importStylesheet(stylesheet);	
		var fragment = xsltProcessor.transformToFragment(this, document);
		var out = document.implementation.createDocument("", "root", null);	
		for(i=0 ; i<fragment.childNodes.length ; i++) {
			out.documentElement.appendChild (out.importNode(fragment.childNodes[i],true))
		}	
		outputObject.loadXML(out.xml);
	}
	
	Document.prototype.transformNode = function(stylesheet){		
        var out = document.implementation.createDocument("", "", null);	
        this.transformNodeToObject(stylesheet, out);
        return out.xml;
    }
	
	Element.prototype.transformNodeToObject = function(stylesheet, outputObject){
        var oDoc = document.implementation.createDocument("", "", null);
		oDoc.loadXML(this.xml);		
		oDoc.transformNodeToObject(stylesheet,outputObject);
    }
	
	Element.prototype.transformNode = function(stylesheet){
        var oDoc = document.implementation.createDocument("", "", null);
		oDoc.loadXML(this.xml);
		return oDoc.xml;
    }
	
	Node.prototype.__defineGetter__("text", _Node_getText);
	Node.prototype.__defineSetter__("text", _Node_setText);	
	
    //add the getter for the .xml attribute
    Node.prototype.__defineGetter__("xml", _Node_getXML);
    
    //add the readystate attribute for a Document
    Document.prototype.readyState = "0";
    
    //save a reference to the original load() method
    Document.prototype.__load__ = Document.prototype.load;

    //create our own load() method
    Document.prototype.load = _Document_load;
    
    //add the onreadystatechange attribute
    Document.prototype.onreadystatechange = null;
    
    //add the parseError attribute
    Document.prototype.parseError = 0;
// ---- / XPATH -------------------------------------------------------  
    
	XMLDocument.prototype.selectNodes = function(sExpr, contextNode){
        var oResult = this.evaluate(sExpr,
                    (contextNode?contextNode:this),
                    this.createNSResolver(this.documentElement),
                    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var nodeList = [];
		for(i=0; i< oResult.snapshotLength; i++) {
			nodeList[nodeList.length] = oResult.snapshotItem(i);
		}
        return nodeList;		
    } 
	
	Element.prototype.selectNodes = function(sExpr) {
		return this.ownerDocument.selectNodes(sExpr,this);
	}
	
	XMLDocument.prototype.selectSingleNode = function(sExpr, contextNode){
		var nodeList = this.selectNodes(sExpr, contextNode);
		if (nodeList.length>0) return nodeList[0];
	}
	
	Element.prototype.selectSingleNode = function(sExpr) {
		return this.ownerDocument.selectSingleNode(sExpr,this);
	}
// ----  XPATH / -------------------------------------------------------	
} //End: if


function isDefined (o) {
	return (typeof(o) != 'undefined');
}

function jsXML() {}

jsXML.getRequest = function(){
	var req = null;
	try	{
	req=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e){
		try	{req=new ActiveXObject("Microsoft.XMLHTTP");}
		catch(oc){req=null;}
	}
	if(!req && isDefined(XMLHttpRequest)){
		try	{req=new XMLHttpRequest();}
		catch(oc){this._raiseError(oc);	}
	}
	return req;
}

jsXML.sendSync = function(url,body){
	var req = this.getRequest();
	req.open("POST", url, false);
	req.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");	
	req.send(body);
	return req.responseText;
}

var jsXMLrequests = new Object();
jsXMLrequests.inner = new Array();
jsXMLrequests.add = function (request,action,onfault,onwait,url) {
	var r = new jsXMLrequest(request,action,onfault,onwait,url);
	r.index =  this.inner.length ;
	this.inner[this.inner.length] = r;
}


jsXMLrequests.process = function () {
	for (i = 0 ; i < this.inner.length; i ++) {
		var rq = this.inner[i];
		if (!rq.received){
			if (rq.get_readyState() == 4) {
				if (rq.get_status() == 200) {
					rq.received = true;
					if(rq.action!=null) rq.action(rq.get_responseText(),rq);
				}
				else {
					rq.received = true;
					if(rq.onfault!=null) rq.onfault(rq.get_statusText());
				}
			}
			else {
				if(rq.onwait!=null) rq.onwait(rq.get_readyState());
			}
		}
	}
}

function jsXMLrequest (request,action,onfault,onwait,url) {
	this.request = request ;
	this.action = action || null;
	this.onfault = onfault || null;
	this.onwait = onwait || null;
	this.url = url || '';
	this.received = false;
	this.index = 0;
}

jsXMLrequest.prototype.get_responseText = function () { return this.request.responseText}
jsXMLrequest.prototype.get_readyState = function () { return this.request.readyState}
jsXMLrequest.prototype.get_statusText = function () { return this.request.statusText}
jsXMLrequest.prototype.get_status = function () { return this.request.status}
jsXMLrequest.prototype.get_readyState = function () { return this.request.readyState}

//setHeaderCallback è un callback aggiuntivo che permette 
//di intervenire per aggiungere headers
jsXML.sendAsync = function (method,url,body,action,onfault,onwait,setHeaderCallback) {
	var req = this.getRequest();	
	jsXMLrequests.add(req , action, onfault, onwait , url);	
	req.onreadystatechange = this.Process;
	req.open(method, url, true);
	if (method=="POST")	req.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");	
	if(typeof setHeaderCallback == "function") setHeaderCallback(req);
	req.send(body);
}

jsXML.sendAsyncGet = function (url,body,action,onfault,onwait) {
	this.sendAsync("GET",url,body,action,onfault,onwait);
}

jsXML.sendAsyncPost = function (url,body,action,onfault,onwait) {
	this.sendAsync("POST",url,body,action,onfault,onwait);
}

jsXML.Process = function (){
	jsXMLrequests.process();
}
/*
jsXML.parseXMLDocument
carica il documento direttamente da una stringa XML 
*/
jsXML.parseXMLDocument = function (xmlText) //as XMLDocument
{
	var doc = jsXML.createDOMDocument('','root');
	doc.loadXML (xmlText);
	return doc;
} // end parseXMLDocument

/*
jsXML.openDOMDocument
carica il documento in modo sincrono
*/
jsXML.openDOMDocument = function (url) //as XMLDocument
{
	var doc = this.createDOMDocument ("","root");
	doc.async = false;
	doc.load(url);
	return doc;
}//end openDOMDocument

jsXML.newDOMDocument = function(){
	return jsXML.createDOMDocument("","root");
}
jsXML.createDOMDocument = function(strNamespaceURI, strRootTagName) {

    //variable for the created DOM Document
    var objDOM = null;
    
    //determine if this is a standards-compliant browser like Mozilla
    if (isMoz) {
    
        //create the DOM Document the standards way
        objDOM = document.implementation.createDocument(strNamespaceURI, strRootTagName, null);    
    
        //add the event listener for the load event
        objDOM.addEventListener("load", _Document_onload, false);
        
    } else if (isIE) {
    
        //create the DOM Document the IE way
        objDOM = new ActiveXObject(STR_ACTIVEX);

        //if there is a root tag name, we need to preload the DOM
        if (strRootTagName) {
       
            //If there is both a namespace and root tag name, then
            //create an artifical namespace reference and load the XML.  
            if (strNamespaceURI) {
                objDOM.loadXML("<a0:" + strRootTagName + " xmlns:a0=\"" + strNamespaceURI + "\" />");
            } else {
                objDOM.loadXML("<" + strRootTagName + "/>");        
            }
        
        }
    }    
    //return the object
    return objDOM;
}

function _Node_getText() {
	var s = "";
	for(var i=0;i<this.childNodes.length;i++){
		if(this.childNodes[i].nodeType == 3) s += this.childNodes[i].nodeValue; //#text
		else if(this.childNodes[i].nodeType == 4) {
			// s += this.childNodes[i].firstChild.nodeValue; //CDATA
			 s += this.childNodes[i].nodeValue;
			 }
	}
	return s;
}

function _Node_setText(value) {
	this.appendChild(this.ownerDocument.createTextNode(value));
}

function _Node_getXML() {
    
    //create a new XMLSerializer
    var objXMLSerializer = new XMLSerializer;
    
    //get the XML string
    var strXML = objXMLSerializer.serializeToString(this);
    
    //return the XML string
    return strXML;
}



function _Document_load(strURL) {

    //set the parseError to 0
    this.parseError = 0;

    //change the readyState
    changeReadyState(this, 1);
    
    //watch for errors
    try {
        //call the original load method
        this.__load__(strURL);
        
    } catch (objException) {
    
        //set the parseError attribute
        this.parseError = -9999999;
        
        //change the readystate
        changeReadyState(this, 4);

    } // End: try...catch
}


function _Document_onload() {

    //handle the onload event
    handleOnLoad(this);
}


function handleOnLoad(objDOMDocument) {
    //check for a parsing error
    if (!objDOMDocument.documentElement || objDOMDocument.documentElement.tagName == "parsererror")
        objDOMDocument.parseError = -9999999;

    //change the readyState
    changeReadyState(objDOMDocument, 4);
}


function changeReadyState(objDOMDocument, iReadyState) {

    //change the readyState
    objDOMDocument.readyState = iReadyState;
    
    //if there is an onreadystatechange event handler, run it
    if (objDOMDocument.onreadystatechange != null && typeof objDOMDocument.onreadystatechange == "function")
        objDOMDocument.onreadystatechange();
}

