/*
  Dynamically generates a nested UL navigation list from
  an XML file. Adds CSS class names to the LI elements.

  leafes get the menu_leaf_class
  open nodes get the menu_open_class
  closed nodes get the menu_closed_class
  the current node gets the menu_active_class 
*/



//Created By:    sreichert
//Date:          9/4/2007
init = function(){

  //get the path of the page. Set the location of nav.xml depending on the level of the page.
  var path = this.location.pathname;
  var subDir = path.split("/");
  if (path == "/epilepsy-community/advocates.aspx")
  {
    document.getElementById('SubtierMaster_QuickPollContent_VoteImage').title = "submit";
    document.getElementById('SubtierMaster_QuickPollContent_ShowResultsImage').title = "View results";

    document.getElementById('SubtierMaster_subtierContent_rptFeaturedAdvocatesTop3_ctl03_thumbnailImage').title = "Epilepsy advocate-Lydia S";
    document.getElementById('SubtierMaster_subtierContent_rptFeaturedAdvocatesTop3_ctl02_thumbnailImage').title = "Epilepsy advocate-Victor A";
    document.getElementById('SubtierMaster_subtierContent_rptFeaturedAdvocatesTop3_ctl01_thumbnailImage').title = "Epilepsy advocate-Alan C";
    document.getElementById('SubtierMaster_subtierContent_rptFeaturedAdvocatesBot3_ctl02_thumbnailImage').title = "Epilepsy advocate- Kevin E";
    document.getElementById('SubtierMaster_subtierContent_rptFeaturedAdvocatesBot3_ctl01_thumbnailImage').title = "Epilepsy advocate-Lakeisha P";

    document.getElementById('SubtierMaster_subtierContent_rptAdvocatesAZ_ctl02_advocateAZImage').title = "Epilepsy advocates biography-Alan c";
    document.getElementById('SubtierMaster_subtierContent_rptAdvocatesAZ_ctl44_advocateAZImage').title = "Epilepsy advocates biography-Kevin E";
    document.getElementById('SubtierMaster_subtierContent_rptAdvocatesAZ_ctl48_advocateAZImage').title = "Epilepsy advocates biography-Lakeisha P";
    document.getElementById('SubtierMaster_subtierContent_rptAdvocatesAZ_ctl56_advocateAZImage').title = "Epilepsy advocates biography-Lydia S";
    document.getElementById('SubtierMaster_subtierContent_rptAdvocatesAZ_ctl90_advocateAZImage').title = "Epilepsy advocates biography-Victor A";
  }
  
  if (path == "/epilepsy-community/events-calendar.aspx")
  {
    document.getElementById('SubtierMaster_QuickPollContent_VoteImage').title = "submit";
    document.getElementById('SubtierMaster_QuickPollContent_ShowResultsImage').title = "View results";
  }
  switch (subDir[1]){
    //don't call menu_mainfunction for pages in utilities or tools folder  
     case "utilities":
     case "tools":
        return;
     break;
     default:
     break;
  }
  
    //if the page is third tier, split will return 4 parts 
  if (subDir.length == 4){
      menu_main('../../includes/xml/nav.xml', 'menu');
  }
  else{
      menu_main('../includes/xml/nav.xml', 'menu');
  }
};
window.onload = init;

//config
var menu_active_class = "menu_bar_item active";
var menu_leaf_class = "leaf";
var menu_open_class = "open";
var menu_closed_class = "closed";

//the default page that is displayed if URL ends in /
var menu_default_page = "index.html";

//state
var menu_current; // XML menu node of the current location
var menu_totop;   // path to top folder from current location

// 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);
}
//global url remove ui_source
var global_url = location.pathname;
var remove = /\/ui_source\//;
global_url = global_url.replace(remove,"");  

//append a vertical bar to the navigation
var append = false;

// 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 url = location.href;
     if (url.lastIndexOf("/") == (url.length-1)) {
       url = url+menu_default_page;
     }
     if (url.lastIndexOf("?") >= 0) {
       url = url.substring(0, url.lastIndexOf("?"));
     }
     if (url.lastIndexOf("#") >= 0) {
       url = url.substring(0, url.lastIndexOf("#"));
     }
     menu_current = menu_getCurrentMenu(xml, url);
     menu_totop = menu_getPathToTop(menu_current);
     
     var main = document.getElementById(menu_id);
     if (!main) {
       alert("No element with id '"+ menu_id +"' found");
       return;
     }
     var execute = null;
     var test = global_url;
     //alert("global_url is "+global_url);
     var test2 = test.slice(0,-5);   
     //alert("test2 is "+test2);     
     temp = test2.split("/");
     if(temp.length == 3){
       if(temp[1] == temp[2]){
         execute = 1;
       }
       else{
         execute = 2;
       }
     }
     else if(temp.length == 4){
       execute = 3;
     }
     switch(execute){
       case 1:
       //alert("1");
         var idname = temp[1];
         //alert(idname);
         //alert("temp[0]:"+temp[0]+ ",temp[1]:"+temp[1]+",temp[2]:"+temp[2]);
         var nav2 = document.getElementById(idname);
          //alert("nav2 is "+nav2);
         nav2.className = "menu_bar_item1 active";
         var getText = nav2.firstChild.firstChild.nodeValue;
         nav2.removeChild(nav2.firstChild);
         var mySpan = document.createElement("span");
         var t = document.createTextNode(getText);
         mySpan.appendChild(t);
         nav2.appendChild(mySpan);
   
         
         var root = document.createElement("div");
         root.className = "second_menu";
         var secondmenu = xml.getElementsByTagName("secondmenu");  
         menu_traverse3(xml, root, secondmenu, execute);  
         main.appendChild(root);
 
       break;
       case 2:
       //alert("2");
         var idname = temp[1];
         try{
         var nav2 = document.getElementById(getOldName(idname));
         nav2.className = "menu_bar_item1 active";
         var getText = nav2.firstChild.firstChild.nodeValue;
         nav2.removeChild(nav2.firstChild);

         var tell = document.createElement("a");
         var url_pathname = location.pathname;
         var arrPathname = url_pathname.split("/");
         arrPathname[1] = getOldName(arrPathname[1]);
         tell.setAttribute("href", "/"+arrPathname[1]+"/"+arrPathname[1]+".aspx");
         var t2 = document.createTextNode(getText);         
         tell.appendChild(t2);
         nav2.appendChild(tell);
         
         var root = document.createElement("div");
         root.className = "second_menu";
         var secondmenu = xml.getElementsByTagName("secondmenu");  
         menu_traverse3(xml, root, secondmenu, execute);  
         main.appendChild(root);
         }
         catch(exception){}
     
       break;
       case 3:
       //alert("3");
         var idname = temp[1];
         var nav2 = document.getElementById(getOldName(idname));
         nav2.className = "menu_bar_item1 active";
         var getText = nav2.firstChild.firstChild.nodeValue;
         nav2.removeChild(nav2.firstChild);
         
         var tell = document.createElement("a");
         var url_pathname = location.pathname;
         var arrPathname = url_pathname.split("/");
         arrPathname[1] = getOldName(arrPathname[1]);
         tell.setAttribute("href", "/"+arrPathname[1]+"/"+arrPathname[1]+".aspx");
         var t2 = document.createTextNode(getText);         
         tell.appendChild(t2);
         nav2.appendChild(tell);
         
         var root = document.createElement("div");
         root.className = "second_menu";
         var secondmenu = xml.getElementsByTagName("secondmenu");  
         menu_traverse3(xml, root, secondmenu, execute);  
         main.appendChild(root);
         
         append = false;
         var root = document.createElement("div");
         root.className = "third_menu";
         var thirdmenu = xml.getElementsByTagName("thirdmenu");  
         menu_traverse4(xml, root, thirdmenu, execute);
         main.appendChild(root);
       break;
       default:
       break;
     }
}

function getOldName(newName){
    switch(newName.toLowerCase()){
        case "living-with-epilepsy":
            return "living";
        break;
        case "about-epilepsy":
            return "about"
        break;
        case "epilepsy-community":
            return "events";
        break;
        case "epilepsy-support":
            return "community";
        break;
        case "awareness":
            return "topics_stories";
        default:
        return newName;
        break;    
    }
}

function menu_traverse2(element, root, menu, execute) {
      var oUL = document.createElement("ul");
      oUL.className = "menu_bar_nav";
      var num = 0;
      for (var i=0; i<menu.length; i++) {
        var child = menu[i];
        if (child.nodeType != 1){ continue; }
        var li = document.createElement("li");
        var style_of_list = null;
      
        if(i == 0){
          style_of_list = "menu_bar_item1 ";
        }
        else{      
          style_of_list = "menu_bar_item ";
        }      
        //global_url 
        var url = child.getAttribute("url");
        if (!url){ url="#"; } // we are desperate now
        //if(url != global_url){
        if(test[1] != test2[1]){
          var num = num+1;
          var a = document.createElement("a");
          switch (execute) {
            case 1:
              a.setAttribute("href", "../"+url);
            break;
            case 2:
              a.setAttribute("href", "../../"+url);
            break;
            case 3:
              a.setAttribute("href", "../../"+url);
            break;
            default:
            break;
          }
          var width = child.getAttribute("width");
          a.setAttribute("onmouseover", "dropdownmenu(this, event, menu"+(num)+", '"+width+"' )");
          a.setAttribute("onmouseout", "delayhidemenu()");
          var text = document.createTextNode(child.getAttribute("title"));
          a.appendChild(text);
          li.appendChild(a);
          style_of_list = style_of_list+"nonactive";
          li.className = style_of_list;
        }
        else{
          var num = num+1;
          var text = document.createTextNode(child.getAttribute("title"));
          li.appendChild(text);
          style_of_list = style_of_list+"active";
          li.className = style_of_list;
        }
        oUL.appendChild(li);  
      }
      root.appendChild(oUL);
      var oBR = document.createElement("div");
      oBR.className = "clear";
      root.appendChild(oBR);  
}

function menu_traverse3(element, root, menu, execute) {

      var oUL = document.createElement("ul");
      oUL.className = "menu_bar_nav";
      var num = 0;
      for (var i=0; i<menu.length; i++) {
        var child = menu[i];
        if (child.nodeType != 1) continue;
        test = global_url.split("/");
        test[1] = getOldName(test[1]);
        test[2] = getOldName(test[2]);
        test2 = child.getAttribute("url").split("/");
        //alert("global_url is "+global_url);
        //alert("url is "+child.getAttribute('url'));
        //alert("test is "+test);
        //alert("test2 is "+test2);
        //alert("test[1] is "+test[1]+" test2[1] is "+test2[1]);
        if (test[1] != test2[1]){ continue; }
        if(append){
          var li = document.createElement("li");
          li.className = "menu_bar_item blue";
          var oText = document.createTextNode("|");
          li.appendChild(oText);
          oUL.appendChild(li);
        }
        var li = document.createElement("li");
        var style_of_list = null;
        if(append == false){
          style_of_list = "menu_bar_item1 ";
        }
        else{      
          style_of_list = "menu_bar_item ";
        }       
        var url = child.getAttribute("url");
        if (!url){ url="#"; } // we are desperate now        
        //if(url != global_url){
        if(test[2] != test2[2]){
        //active
          var num = num+1;
          var a = document.createElement("a");
          switch (execute) {
            case 1:
              a.setAttribute("href", ".."+url);
            break;
            case 2:
              a.setAttribute("href", ".."+url);
            break;
            case 3:
              a.setAttribute("href", "../.."+url);
            break;
            default:;
          }
          var text = document.createTextNode(child.getAttribute("title"));
          a.appendChild(text);
          li.appendChild(a);
          li.className = style_of_list;
        }
        else{
          //not active
          var temp_url = location.pathname;
          //alert(temp_url);
          var a_temp_url = temp_url.split('/');
          var test;
           if(a_temp_url.length == 4){
             var a_temp_2  = a_temp_url[3].split('.');
             //alert(a_temp_url[2]);
             //alert(a_temp_2[0]);
             test = (a_temp_url[2] == a_temp_2[0]);
           }
           
          if(test){
          
            var num = num+1;
          
            var mySpan = document.createElement("span");
            var text = document.createTextNode(child.getAttribute("title"));
            mySpan.appendChild(text);
          
            li.appendChild(mySpan);
            style_of_list = style_of_list+"active";
            li.className = style_of_list;
          }
          else{
            var num = num+1;
            var myAnchor = document.createElement("a");
            //this needs to be tighten up.
            myAnchor.setAttribute("href", "epilepsy-videos.aspx");
            myAnchor.className = "black";
            var text = document.createTextNode(child.getAttribute("title"));
            myAnchor.appendChild(text);
            li.appendChild(myAnchor);
            style_of_list = style_of_list+"active";
            li.className = style_of_list;
          }
        }
        oUL.appendChild(li);
        append = true;
      }
      
      root.appendChild(oUL);
      var oBR = document.createElement("div");
      oBR.className = "clear";
      root.appendChild(oBR);  
}

function menu_traverse4(element, root, menu, execute) {
      var oUL = document.createElement("ul");
      oUL.className = "menu_bar_nav";
      var num = 0;
      for (var i=0; i<menu.length; i++) {
        var child = menu[i];
        if (child.nodeType != 1){ continue; }
        test = global_url.split("/");
        test[2] = getOldName(test[2]);
        test2 = child.getAttribute("url").split("/");
        if (test[2] != test2[2]){ continue; }
        if(append){
          var li = document.createElement("li");
          li.className = "menu_bar_item blue";
          var oText = document.createTextNode("|");
          li.appendChild(oText);
          oUL.appendChild(li);
        }
        var li = document.createElement("li");
        var style_of_list = null;
        if(append == false){
          style_of_list = "menu_bar_item1 ";
        }
        else{      
          style_of_list = "menu_bar_item ";
        }       
        var url = child.getAttribute("url");
        if (!url){ url="#"; } // we are desperate now
        //if(url != global_url){
        if(test[3] != test2[3]){
          var num = num+1;
          var a = document.createElement("a");
          switch (execute) {
            case 1:
              a.setAttribute("href", ".."+url);
            break;
            case 2:
              a.setAttribute("href", "../.."+url);
            break;
            case 3:
              a.setAttribute("href", "../.."+url);
            break;
            default:
            break;
          }
          var text = document.createTextNode(child.getAttribute("title"));
          a.appendChild(text);
          li.appendChild(a);
          li.className = style_of_list;
        }
        else{
          var num = num+1;
          var mySpan = document.createElement("span");
          var text = document.createTextNode(child.getAttribute("title"));
          mySpan.appendChild(text);
          
          li.appendChild(mySpan);
          style_of_list = style_of_list+"active";
          li.className = style_of_list;
        }
        oUL.appendChild(li);
        append = true;
      }
      
      root.appendChild(oUL);
      var oBR = document.createElement("div");
      oBR.className = "clear";
      root.appendChild(oBR);  
}


/* Walks down the subtree and on the way back
   sets properties.
   element : the parent XML node
   root    : the DOM node of the enclosing UL
   returns bit set
           1: set = element is a node, unset = element is a leaf
           2: set = element contains the active node

*/
function menu_traverse(element, root) {
  var props = 0;
  var ihavechildren = false;
  var icontainactive = false;
  for (var i=0; i<element.childNodes.length; i++) {
    var child = element.childNodes[i];
    if (child.nodeType != 1){ continue; }
    if (child.nodeName != "menu"){ continue; }
    ihavechildren = true;
    // create DOM
    var li = document.createElement("li");
    li.className = "";
    var a = document.createElement("a");
    var url = child.getAttribute("url");
    if (!url) {
      var submenus = child.getElementsByTagName("menu");
      for (var j=0; j < submenus.length; j++) {
        url = submenus[j].getAttribute("url");
        if (url) break;
      }
    }
    if (!url){ url="#";} // we are desperate now
    var iamactive = (child == menu_current);
    if (iamactive) {
      li.className = menu_active_class;
      icontainactive = true;
    }  
    a.setAttribute("href", menu_totop + url);
    var text = document.createTextNode(child.getAttribute("title"));
    a.appendChild(text);
    li.appendChild(a);
    root.appendChild(li);

    // recurse
    var ul = document.createElement("ul");
    var subprops = menu_traverse(child, ul); // aggregate bits
    
    if (subprops & 1) {
      li.className += " "+ (iamactive || (subprops & 2) ? menu_open_class : menu_closed_class);
      li.appendChild(ul);
    } else {
      li.className += " "+menu_leaf_class;
    }
    props |= subprops;
  }
  if (ihavechildren) props |= 1;
  if (icontainactive) props |= 2;
  return props;
}

function menu_getPathToTop(menu) {
  var path = "";
  if (menu == null) return path;
  var url = menu.getAttribute("url");
  var a = url.split(/[\/]/);
  if (a.length == 1){
   return path;
  }
  var len = a.length -1;
  for (var i=0; i < len; i++) {
    path += "../";
  }
  return path;
}

// determines the current location in the nav tree.
// its the longest URL that matches the location.
// xml : the XML root node of the navigation XML
// loc : the current URL location
function menu_getCurrentMenu(xml, loc) {
  var current = null;
  var maxlen = 0;
  var menus = xml.getElementsByTagName("menu");
  var menus_length = menus.length;
  for (var i=0; i < menus_length; i++) {
    var menu = menus[i];
    var url = menu.getAttribute("url");
    
    if (!url){
     continue;
    }
    if (url.length < maxlen){
     continue;    
    }
    if (!menu_isSameUrl(loc, url)){
     continue;
    }
    current = menu;
    maxlen = url.length;
  }
  return current;
}

//matches two URIs when href is the last part of url
//.. and . are correctly resolved
function menu_isSameUrl(url, href) {
  var a = url.split(/[?\/]/i);
  var b = href.split(/[?\/]/i);
  var i = a.length - 1;
  var j = b.length - 1;
  while ((i >= 0) && (j >= 0)) {
    if (b[j] == "..") { j-=2; continue; }
    if (a[i] == "..") { i-=2; continue; }
    if ((b[j] == ".") || (b[j] == "")) { j--; continue; }
    if ((a[i] == ".") || (a[i] == "")) { i--; continue; }
    if (! (a[i] == b[j])) return false;
    i--;
    j--;
  }
  return true;
}