/**
 * Functions and variables for handling the CJAS site menu.
 *
 * All global names start with "cjas" to avoid potential naming conflicts with
 * JavaScript in any site component we might use.
 */

// The link element that will be highlighted by default.
var cjasDefaultHighlight =
  (cjasSiteSection == null) ? null : document.getElementById(cjasSiteSection);

// The link element that currently has focus.
var cjasHover = null;

// The link element that the mouse is currently hovering over.
var cjasFocus = null;

// Array of all menu items, including the border images.
var cjasMenu = new Array;

/**
 * The initialization procedure.  Should be called once, before anything else
 * menu-related happens.
 */
function cjasInit() {
  // Initialize the cjasMenu variable.
  var nodes = document.getElementById("cjasMenu").childNodes;
  var numItems = 0;
  for (var i = 0; i < nodes.length; i++) {
    var cur = nodes.item(i);

    // Ignore text elements.
    if (cur.nodeName == "#text") continue;

    // Assume we have an <li>.  Get its first child that is not a text element.
    cjasMenu[numItems] = cur.firstChild;
    while (cjasMenu[numItems].nodeName == "#text")
      cjasMenu[numItems] = cjasMenu[numItems].nextSibling;

    numItems++;
  }

  // Set up the initial highlight.
  cjasRefreshMenu();

  // Set up the unload handler.
  var oldHandler = window.onunload;
  window.onunload = function() {
    cjasBlurFocus();
    if (oldHandler != null) eval(oldHandler);
  }
}

/**
 * Highlights the menu item corresponding to the given link element.
 */
function cjasMenuHighlight(element) {
  var elementIdx;
  for (var i = 0; i < cjasMenu.length; i++) {
    var baseClass = cjasMenu[i].className.split(" ")[0];
    cjasMenu[i].className = baseClass;
    if (cjasMenu[i] == element) elementIdx = i;
  }

  if (element != null) {
    element.className += " cjasLinkActive";
    cjasMenu[elementIdx-1].className += " cjasLinkInactiveR";
    cjasMenu[elementIdx+1].className += " cjasLinkInactiveL";
  }
}

/**
 * Refreshes the menu highlight.
 */
function cjasRefreshMenu() {
  if (cjasHover != null)
    cjasMenuHighlight(cjasHover);
  else if (cjasFocus != null)
    cjasMenuHighlight(cjasFocus);
  else
    cjasMenuHighlight(cjasDefaultHighlight);
}

/**
 * If a menu element has focus, transfers it to the given element.
 */
function cjasBlurFocus() {
  if (cjasFocus != null) cjasFocus.blur();
}

cjasInit();


