/* Portions copyright 2005 Wrox Press */

/*jslint white: true, onevar: true, browser: true, undef: true,
    nomen: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true,
    immed: true, indent: 2 */
/*members childNodes, className, getElementById, href, id, indexOf, 
    length, location, nodeName, nodeType, onclick, parentNode, replace, 
    tagName, toLowerCase
*/

// Toggle collapse state
function toggleExpansion(element) {
	switch (element.nodeName.toLowerCase()) {
  case "li":
  case "ul":
  case "ol":
  case "span":
    // Fall through in each case
    break;
  default:
    //alert(element.nodeName);
    throw "requires list item";
  }
  
  if (element.className.indexOf("expand") >= 0) {
    element.className = element.className.replace("expand", "collapse");
  }
  else {
    element.className = element.className.replace("collapse", "expand");
  }
}

function tocInitialize(rootNode) {
  var sClassCurrent = " current", node, urlCurrent = document.location.href, urlTarget, n, i;
  rootNode = rootNode || document.getElementById("toc_root");
  function onclick() {
    toggleExpansion(this.parentNode);
  }
  
  for (i = 0; i < rootNode.childNodes.length; i++) {
    node = rootNode.childNodes[i];
    if (node.nodeType === 1) {
      node.className = node.className.replace("init", "collapse");
      if (node.tagName === "SPAN") {
        node.onclick = onclick;
      }
      tocInitialize(node);
      
      // Highlight current subtree
      if (node.tagName === "A" && node.className.indexOf("item") !== -1) {
        urlTarget = node.href;
        if ((urlCurrent.indexOf(urlTarget) !== -1) && (urlCurrent.indexOf(urlTarget) + urlTarget.length === urlCurrent.length)) {
          node.parentNode.className += sClassCurrent;
          // Spin up the parent array
          for (n = node; n.id !== "toc_root"; n = n.parentNode) {
            if (n.tagName === "LI") {
              n.className = n.className.replace("collapse", "expand");
            }
          }
        }
      }
    }
  }
}

window.addEventListener("load", function () { tocInitialize(); }, true);
