/*******************************
 * sitenav.js
 * This script was created for our-saviour.org to manage nested navagation
 * 
 * By Steven Partlow <steve@spartlow.com>
 *
 * This script expects a two-level links in the SITENAV DIV. Such as:
 *
 * <div id="sitenav">
 * <ul>
 *  <li><a href="...">Section1</a><ul>
 *    <li><a href="...">Sub1.1</a>
 *    <li><a href="...">Sub1.2</a>
 *   </ul></li>
 *  <li><a href="...">Section2</a><ul>
 *    <li><a href="...">Sub2.1</a>
 *    <li><a href="...">Sub2.2</a>
 *   </ul></li>
 * </ul>
 * </div>
 *
 *******************************/

//var log;

/*
 * Sets up mouse over listeners for each link on the top-level LI in the sitenav
 */
function SetupSitenav() {
  //log = document.body.lastChild;
  //log.data = log.data+"  setup: ";
  var navdiv = document.getElementById('sitenav');
  var navul = GetFirstChildByNodeName(navdiv,"UL");
  var topli = GetFirstChildByNodeName(navul,"LI");

  /* loop over all child elements of the list */
  while (topli!=null){
    /* add mouseover to the first A element */
    var thelink = GetFirstChildByNodeName(topli,"A");
    thelink.onmouseover=CreateShowChildren(topli);
    topli = GetNextSiblingByNodeName(topli,"LI");
  }
}
/*
 * Returns the ShowChildren function which hides all other secondary lists but
 * shows the one under the moused-over section
 */
function CreateShowChildren(obj) {

  return function() {
    HideAll();
    var child = GetFirstChildByNodeName(obj,"UL");
    while (child!=null){
      child.style.visibility = 'visible';
      child = child.nextSibling;
    }
  }
}
/*
 * Hides all secondary sections
 */
function HideAll() {
  var navdiv = document.getElementById('sitenav');
  var navul = GetFirstChildByNodeName(navdiv,"UL");
  var topli = GetFirstChildByNodeName(navul,"LI");

  /* loop over all child elements of the list */
  while (topli!=null){
    var child = GetFirstChildByNodeName(topli,"UL");
    while (child!=null){
      child.style.visibility = 'hidden';
      child = GetNextSiblingByNodeName(child,"UL");
    }
    topli = GetNextSiblingByNodeName(topli,"LI");
  }
}
/*
 * Finds first child of a given node name (tag type)
 */
function GetFirstChildByNodeName(x,t) {
  x = x.firstChild;
  if (x!=null && x.nodeName!=t) {
    x = GetNextSiblingByNodeName(x,t);
  }
  return x;
}
/*
 * Finds next sibling with a given node name
 */
function GetNextSiblingByNodeName(y,t) {
  y = y.nextSibling;
  while(y!=null && y.nodeName!=t) {
    y = y.nextSibling;
  }
  return y;
}
