//
//  menu.js
//

var menuAnimators = $H(new Object());
var animDuration = 400;

function setupMenu () {
  $$("#menu > li.menu").each(function (menuItem) {
    setupMenuAnimator(menuItem);
    setupMenuLink(menuItem.firstDescendant());
  });
  selectCurrentItem();
}

function setupMenuAnimator (menuItem) {
  var menuId = menuItem.getAttribute("id");
  var subMenu = menuItem.immediateDescendants().last();
  
  menuAnimators[menuId] = new Animator({
    duration: animDuration,
    transition: Animator.tx.easeInOut,
    onStep: function () {
      if (this.state > 0.0)
        showSubMenuForExplorer(subMenu);
      else hideSubMenuForExplorer(subMenu);
    },
    onComplete: function () {
      if (this.state == 1.0)
        this.options.transition = Animator.tx.easeInOut;
      else this.options.transition = Animator.tx.easeInOut;
    }
  }).addSubject(
    new CSSStyleSubject(subMenu, "closed", "open"));
  hideSubMenuForExplorer(subMenu);
}

function setupMenuLink (menuLink) {
  menuLink.onclick = Prototype.K.bind(this, false);
  Event.observe(menuLink, "click", function () {
    var menuId = this.parentNode.getAttribute("id");

    if (numberOfMenusOpenExcluding(menuId) > 0) {
      closeAllMenusExcept(menuId);
      setTimeout(function () {
        menuAnimators[menuId].toggle();
      }, animDuration / 2);
    } else menuAnimators[menuId].toggle();
  }.bind(menuLink));
}

function closeAllMenusExcept (menuId) {
  menuAnimators.keys().each(function (key) {
    if (menuId != key) menuAnimators[key].seekTo(0.0);
  });
}

function numberOfMenusOpenExcluding (menuId) {
  var menusOpen = 0;
  menuAnimators.keys().each(function (key) {
    if (menuId != key && menuAnimators[key].state > 0.0)
      menusOpen = menusOpen + 1;
  });
  return menusOpen;
}

function hideSubMenuForExplorer (subMenu) {
  // if (Prototype.Browser.IE) subMenu.hide();
}

function showSubMenuForExplorer (subMenu) {
  // if (Prototype.Browser.IE) subMenu.show();
}

function selectCurrentItem () {
  var currentUrl = new String(document.location);
  $$("ul.submenu li a").each(function (link) {
    if (currentUrl.include(link.href)) {
      var menuId = link.up("li.menu").getAttribute("id");
      showSubMenuForExplorer(link.up("ul"));
      
      menuAnimators[menuId].jumpTo(1.0);
      menuAnimators[menuId].options.transition = Animator.tx.easeInOut;
    }
  });
}

Event.observe(window, "load", setupMenu);
