var currentMenu;
var currentMenuCell;
var previousCSSClass;
//
// Type 1: onClick
// Type 2: onMouseOver
//
var menuType = 2;

var timerID = 0;
var menuDelay = 500;

currentMenu = "";
currentMenuCell = null;
document.onclick = menuOnMouseClick;

function menuOnMouseClick(event) {
  if (currentMenu != "") {
    hideMenu(event, currentMenu);
  }
}

function findPosX(obj) {
  var curleft = obj.offsetLeft;
  while (obj.offsetParent) {
    obj = obj.offsetParent;
    curleft += obj.offsetLeft;
  }
  return curleft + "px";
}

function findPosY(obj) {
  var curtop = 0;
  curtop += (obj.offsetTop + obj.offsetHeight);
  while (obj.offsetParent) {
    obj = obj.offsetParent;
    curtop += obj.offsetTop;
  }
  return curtop + "px";
}

function showMenu(event, menuName) {
  var menuCell, menuDiv;

  if (!event.stopPropagation) {
    event.stopPropagation = new Function('this.cancelBubble = true;')
  }
  if (menuType == 1) {
    if (event.type == "mouseover" && currentMenu == "") {
      return;
    }
  }
  else if (menuType == 2) {
    if (event.type == "click") {
      event.stopPropagation();
      return;
    }
    if (timerID) {
      clearTimeout(timerID);
      timerID = 0;
    }
  }
  if (currentMenu != "") {
    hideMenu(event, currentMenu);
  }
  if (menuName != "") {
    menuDiv = document.getElementById(menuName);
    if (!menuDiv) {
      event.stopPropagation();
      return;
    }
    menuCell = document.getElementById(menuName+"Cell");
    previousCSSClass = menuCell.className;
    menuCell.className = previousCSSClass + "Selected";
    menuDiv.style.top = findPosY(menuCell);
    menuDiv.style.left = findPosX(menuCell);
    menuDiv.style.visibility = "visible";
    currentMenu = menuName;
    currentMenuCell = menuCell;
  }
  event.stopPropagation();
}

function hideMenu(event, menuName) {
  var menuDiv;

  if ((menuType == 2) && (timerID)) {
    clearTimeout(timerID);
    timerID = 0;
  }
  if (menuName != "") {
    menuDiv = document.getElementById(menuName);
    if (menuDiv) {
      menuDiv.style.visibility = "hidden";
    }
    if (currentMenuCell) {
      currentMenuCell.className = previousCSSClass;
    }
  }
  currentMenu = "";
  currentMenuCell = null;
}

function doNotHideMenu(event) {
  if (!event.stopPropagation) {
    event.stopPropagation = new Function('this.cancelBubble = true')
  }
  event.stopPropagation();
}

function delayedHideMenu(event, menuName) {
  if (menuType == 2) {
    timerID = setTimeout("hideMenu(0, '" + menuName + "')", menuDelay);
  }
}

function goMenuLink(event) {
  var theItem;

  theItem = event.target;
  for(var x=0;x <theItem.childNodes.length;x++){
    if(theItem.childNodes[x]){
      if (theItem.childNodes[x].nodeName == "A") {
        window.location.href = theItem.childNodes[x].href;
      }
    }
  }
  hideMenu(event, currentMenu);
}
