// main function
// navfile : the URL to the navigation XML
// menu_id : id of the element into which to insert the navigation
function menu_main(navfile, menu_id) {
  var xml = menu_loadXml(navfile);
  if (!xml) return;
  menu_create(xml, menu_id);
}

// navfile : the URL to the navigation XML
function menu_loadXml(navfile) {
    var xmlHttp = false;
    // Mozilla, Opera, Safari, IE7
    if (typeof XMLHttpRequest != 'undefined') {
        xmlHttp = new XMLHttpRequest();
    }

    if (!xmlHttp) {
        // before IE 6
        try {
            xmlHttp  = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                xmlHttp  = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                xmlHttp  = false;
            }
        }
    }
    
    if (!xmlHttp) {
      alert("Sorry, your browser does not support AJAX!");
      return false;
    }

    xmlHttp.open("GET", navfile, false);
    xmlHttp.send(null);
    if ((xmlHttp.status>=200) && (xmlHttp.status < 400)) {
      return xmlHttp.responseXML.getElementsByTagName("navigation")[0];
    } else {
      alert("AJAX error: "+ xmlHttp.status +" "+ xmlHttp.statusText);
      return false;
    }
}

// xml : the XML root node of the navigation XML
// menu_id : id of the element into which to insert the navigation
function menu_create(xml, menu_id) {
     
     var main = document.getElementById(menu_id);
     if (!main) {
       alert("No element with id '"+ menu_id +"' found");
       return;
     }
  
     var root = document.createElement("ul");
     build_menu(xml, root);
     main.appendChild(root);
           
}

function build_menu(navigationXml, root) {

    //loop through menu items
    for (var i=0; i<navigationXml.childNodes.length; i++) {
        var menuItem = navigationXml.childNodes[i];
        
        if (menuItem.nodeType != 1) continue;
        if (menuItem.nodeName != "menu") continue;  
        
        var li = document.createElement("li");
        li.className = "";
        
        var a = document.createElement("a");
        var url = menuItem.getAttribute("url");
        
        a.setAttribute("href", url);
        
        var text = document.createTextNode(menuItem.getAttribute("title"));
        a.appendChild(text);
        
        li.appendChild(a);
        root.appendChild(li);

    }    
}
