// #######################################################################################################
//
//      ADEIS_xmlForMenus.js
//      ====================
//
//      Dernière modification le 23/01/2004.
//
//
// #######################################################################################################

///////////////////////////////////////////////////////////////////////////////
// DEBUT xmlextra.js        ///////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

// used to find the Automation server name
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");
}

//////////////////////////
// Start the Real stuff //
//////////////////////////


// XmlHttp factory
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
	 *
	 */
	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	/*
	XMLDocument.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
	*/
	Document.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
}

///////////////////////////////////////////////////////////////////////////////
// FIN xmlextra.js          ///////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// DEBUT xmlMenu.js        ////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
function removeEmptyChilds(parentNode) {
	//alert("removeEmptyChilds");
	var childNode;
	
	if(parentNode.hasChildNodes()) {
		childNode = parentNode.firstChild;
		while(childNode) {
			//alert(parentNode.nodeName+"/"+childNode.nodeName+"="+childNode.nodeType);
//			if(childNode.nodeName=="#text" || ( childNode.nodeName=="text" && childNode.nodeValue==null ) ) {
			if(childNode.nodeName=="#text") {
				//alert(childNode.nodeName);
				parentNode.removeChild(childNode);
				//alert("ok remove");
				childNode = parentNode.firstChild;
			} else {
				if(childNode.hasChildNodes()) {
					removeEmptyChilds(childNode);
					//alert("fin remove");
					//alert(parentNode.nodeName);
				}
				childNode = childNode.nextSibling;
			}
		}
	}
}
function xmlMenu(urlVueXml, oVueXml) {
    
    this.url = "";
    this.restrictToCategory = "";
    //this.racine = "";
    this.position = "";
    this.unid = "";
    this.libelle = "";
    this.profondeur = "";
    this.defaultTarget = "";
    this.baseUrl = "";
    this.vueXml = null;
    this.xmlStr = "";
    this.xmlDoc = null;
    this.menuRoot = null;
    this.menuLoaded = false;
    
    this.getOptionValue = function(name) {
        if(this.url!="") {
            var index = this.url.indexOf(name);
            if(index!=-1) {
                var nDeb = this.url.indexOf("=", index) + 1;
                var nFin = this.url.indexOf("&", index+1);
                if(nFin==-1) { nFin = this.url.length; }
                return(unescape(this.url.substring(nDeb, nFin)));
            }
        }
        return("");
    }
    
    this.load = function(urlVueXml, vue) {
        if(urlVueXml!="") {
            this.url = urlVueXml;
            this.baseUrl = unescape(this.url.substring(0, this.url.toLowerCase().indexOf(".nsf/")+5))+"0/";
            this.restrictToCategory = this.getOptionValue("&restricttocategory");
            //this.racine = this.getOptionValue("&racine").toUpperCase();
            this.position = this.getOptionValue("&position");
            this.unid = this.getOptionValue("&unid").toUpperCase();
            this.libelle = this.getOptionValue("&libelle");  
            this.profondeur = this.getOptionValue("&profondeur");
            this.defaultTarget = this.getOptionValue("&target");
            if(vue!=null) {
                this.vueXml = vue;
            } else {
                this.vueXml = new xmlView(urlVueXml);
            }
            this.create();
        }
    }   // load    
   
    this.create = function() {
        var str = "";
        var keyName="", keyValue="";
        var curCols=null, precCols=null;
        var nbSousMenusOuverts=0, nivPrec=0, nivCur=0, nivExclu=0;
        var debut=0, nivMini=0, nivMax=999;
        if(this.unid!="") {
            keyName = "url";
            keyValue = this.unid;
        } else {
            if(this.position!="") {
                keyName = "position";
                keyValue = this.position; 
            } else {
                if(this.libelle!="") {
                    keyName = "libelle";
                    keyValue = this.libelle;
                }
            }
        }
        if(keyName!="" && keyValue!="" && this.profondeur!="") {
            var deb, niv1, niv2, prof;
            debut = 9999;
            deb = this.vueXml.getEntryPosByUNID(keyValue);

//            deb = this.vueXml.getEntryPosByKey(keyName, keyValue);

            if(deb!=-1 && (deb+1)<this.vueXml.nbEntries) {
                niv1 = parseInt(this.vueXml.getEntry(deb)["niveau"]);
                niv2 = parseInt(this.vueXml.getEntry(deb+1)["niveau"]);
                prof = parseInt(this.profondeur);
                if(niv2>niv1 && prof>0) {
                    debut = deb+1;
                    nivMini = niv2;
                    nivMax = nivMini + prof - 1;
                }
            }
        }

        str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<menu>"
        for(var i=debut; i<this.vueXml.nbEntries; i++) {
            curCols = this.vueXml.getEntry(i);
            nivCur = parseInt(curCols["niveau"]);
            if(nivExclu==0 || nivCur <= nivExclu) {
                nivExclu = 0;
                if(i!=debut && curCols["exclure"]=="1") {
                    nivExclu = nivCur;
                } else {
                    if(nivCur>=nivMini) {
                        if(nivCur<=nivMax) {
                            if(precCols==null) {
                                str += "<ligne"
                            } else
                            {
                                if(nivCur==nivPrec) {
                                    str += this.getItemAttributes(precCols);
                                    str += "></ligne>\n"
                                    str += "<ligne"
                                } else {
                                    if(nivCur>nivPrec) {
                                        /*str += " libelle=\""+escape(precCols["libelle"])+"\""
                                        if(typeof(precCols["icone"])!="undefined") {
                                            str += " icone=\""+escape(precCols["icone"])+"\""
                                        } else {
                                            str += " icone=\"\""
                                        }
                                        if(typeof(precCols["bulle"])!="undefined") {
                                            str += " bulle=\""+escape(precCols["bulle"])+"\">"
                                        } else {
                                            str += " bulle=\"\">"
                                        }*/
                                        str += this.getItemAttributes(precCols)+">"; 
                                        str += "<ligne"
                                        nbSousMenusOuverts++
                                    } else {
                                        str += this.getItemAttributes(precCols);                       
                                        str += "></ligne>\n"
                                        for(var j=0; j<nivPrec-nivCur; j++) {
                                            str += "</ligne>\n";
                                            nbSousMenusOuverts--
                                        }
                                        str += "<ligne"
                                    }
                                }
                            }
                            precCols = curCols;
                            nivPrec = nivCur;
                        }
                    } else {
                        break;
                    }
                }
            }
        }
        if(precCols!=null) {
            str += this.getItemAttributes(precCols);      
            str += "></ligne>\n"
            for(var j=0; j<nbSousMenusOuverts; j++) {
                str += "</ligne>\n";
            }
        }
        str += "</menu>"
        this.xmlStr = str;
        this.xmlDoc = XmlDocument.create();
        this.xmlDoc.loadXML(str);
        this.menuRoot = this.getMenuRoot();
        this.menuLoaded = this.menuRoot!=null ? true : false;
        //document.write(str);
        //alert(str);
        //alert(this.menuLoaded);
    }   // create   
    
    this.getItemAttributes = function(cols) {
        var str = "";

        if(typeof(cols["libelle"])!="undefined") {
            str += " libelle=\""+escape(cols["libelle"])+"\""
        } else {
            str += " libelle=\".\""
        }
        if(typeof(cols["url"])!="undefined" & cols["url"]!="") {
            str += " url=\""+escape(this.baseUrl+cols["url"]+"?OpenDocument")+"\"";
        } else {
            str += " url=\"#\""
        }
        if(typeof(cols["cible"])!="undefined" && this.defaultTarget=="") {
            str += " cible=\""+escape(cols["cible"])+"\""
        } else {
            str += " cible=\""+this.defaultTarget+"\""
        }
        if(typeof(cols["icone"])!="undefined") {
            str += " icone=\""+escape(cols["icone"])+"\""
        } else {
            str += " icone=\"\""
        }
        if(typeof(cols["bulle"])!="undefined") {
            str += " bulle=\""+escape(cols["bulle"])+"\""
        } else {
            str += " bulle=\"\""
        }        
        return(str);    
    }   // getItemAttributes
    
    this.getMenuRoot = function() {
        if(this.xmlDoc.hasChildNodes) {
            var cs = this.xmlDoc.childNodes;
            for(var i=0;i<cs.length;i++) {
                if(cs[i].nodeType==1 && cs[i].nodeName=="menu" && cs[i].hasChildNodes) {
                    return(cs[i]);
                }
            }
        }
        return(null);
    }   // getMenuRoot

    this.toString = function () {
        return this.xmlStr;
    }
       
    if(arguments.length>0) {
        arguments.length==2 ? this.load(urlVueXml, oVueXml) : this.load(urlVueXml, null);
    }
  
}

function xmlView(urlVueXml) {
    
    this.urlVue = urlVueXml;
    this.entries = null;
    this.nbEntries = 0;
  
    this.loadView = function() {
        var vueXml;
        
        //var xmlHttp = XmlHttp.create();
        //var async   = false;
        //xmlHttp.open("GET", this.urlVue, async);
        //xmlHttp.send(null);
        //vueXml = xmlHttp.responseXML;
        //alert(xmlHttp.responseText);
        
        vueXml = XmlDocument.create();
        vueXml.async = false;
        vueXml.load(this.urlVue);
                
        this.entries = null;
        this.nbEntries = 0;
        if(vueXml.hasChildNodes) {
            var cs = vueXml.childNodes;
            for(var i=0;i<cs.length;i++) {
                if(cs[i].nodeName=="viewentries") {
                	if (!window.ActiveXObject) removeEmptyChilds(cs[i]);
                    this.entries = cs[i].childNodes;
                    this.nbEntries = this.entries.length;
                }
            }
        }
        //alert(this.nbEntries);
        //for(var i=0; i<this.nbEntries; i++) {
        //	alert(i+"="+this.entries[i].childNodes[0].childNodes[0].nodeName+"="+this.entries[i].childNodes[0].childNodes[0].nodeValue);
    	//}
    }   // loadView
    
    this.getEntry = function(rowNumber) {
        if(rowNumber<this.nbEntries) {
            var cs = this.entries[rowNumber].childNodes;
            var cols = new Array(cs.length);
            var valeur;
            var niveau;
            for(var i=0;i<cs.length;i++) {
                if(cs[i].childNodes[0].hasChildNodes) {
                    valeur = cs[i].childNodes[0].childNodes[0].nodeValue;
                } else {
                    valeur = cs[i].childNodes[0].nodeValue;
                }
                //#######################################
                
                if (cs[i].getAttribute("name") == "niveau"){
                	niveau = valeur;
                }
                
                if (cs[i].getAttribute("name") == "url"){
                	 
                	if(valeur==null){
            		
                		valeur = this.getURLContenu(rowNumber, niveau);
                		//alert(cs[i].getAttribute("name")+" "+i+" = "+valeur);
                		}
                	
                }
                
                // ######################################
                cols[cs[i].getAttribute("name")] = ( valeur==null ? "" : valeur );
            }
            return(cols);
        } else {
            return(null);
        }
    }   // getEntry
    
    this.getEntryPosByKey = function(keyName, keyValue) {
        var cs, valeur;

        for(var i=0;i<this.nbEntries;i++) {
            cs = this.entries[i].childNodes;
            for(var j=0;j<cs.length;j++) {
                if(cs[j].getAttribute("name")==keyName) {
                    if(cs[j].childNodes[0].hasChildNodes) {
                        valeur = cs[j].childNodes[0].childNodes[0].nodeValue;
                    } else {
                        valeur = cs[j].childNodes[0].nodeValue;
                    }
                    if(escape(valeur)==escape(keyValue)) { return(i); }
                }
            }
        }
        return(-1);
   }   // getEntryPosByKey
   
   
   // ##########################"
   
      this.getEntryPosByUNID = function(keyValue) {
        var cs, valeur;
        for(var i=0;i<this.nbEntries;i++) {
/*            cs = this.entries[i].childNodes;
            for(var j=0;j<cs.length;j++) {
                if(cs[j].getAttribute("name")==keyName) {
                    if(cs[j].childNodes[0].hasChildNodes) {
                        valeur = cs[j].childNodes[0].childNodes[0].nodeValue;
                    } else {
                        valeur = cs[j].childNodes[0].nodeValue;
                    }
                    if(escape(valeur)==escape(keyValue)) { return(i); }
                }
*/
//					alert(this.entries[i].getAttribute("unid"));
		//alert(this.entries[i].toString());
                if (escape(this.entries[i].getAttribute("unid"))==escape(keyValue)) 
                {return(i);}
                
            }
    
        return(-1);
   }   // getEntryPosByUNID
 
   
   // ##############################
   
   
   this.getURLContenu= function(rowNumber, niveau){
   	
   	rowNumber++;
   	niveau++;
   	
   	if(rowNumber<this.nbEntries) {
      	var cs = this.entries[rowNumber].childNodes;
         var cols = new Array(cs.length);
         var valeur;
         var niveauS;
         
         for(var i=0;i<cs.length;i++) {
         	if(cs[i].childNodes[0].hasChildNodes) {
            	valeur = cs[i].childNodes[0].childNodes[0].nodeValue;
            } else {
            	valeur = cs[i].childNodes[0].nodeValue;
            }
                
            if (cs[i].getAttribute("name") == "niveau"){
	           	niveauS = valeur;
            }
                
            if (cs[i].getAttribute("name") == "url"){
                	//alert(cs[i].getAttribute("name")+" "+i+" test = "+valeur);
                	// cas où il y a null dans url à traiter
              	if(valeur==null || valeur==""){
               	valeur = this.getURLContenu(rowNumber, niveau);
               	//alert(cs[i].getAttribute("name")+" "+i+" = "+valeur);
               	return valeur;
            	}else{
            		if (niveau == niveauS) return valeur;
            	}
            } 	
         }
   	}
   
   	return null;	
   }	// getURLContenu
   
   
   
   
   this.loadView();
}

///////////////////////////////////////////////////////////////////////////////
// FIN xmlMenu.js        //////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
