// Add a delay to main navigation menu.
//
// This effect prevents submenus from showing up too fast up when the user
// momentarily hovers the mouse pointer over top menu items. A similar effect
// keeps submenus visible for a short time on exit.
var Menu = {
  timeout: 100,

  active: null,
  items: [],
  timeoutId: null,

  // Set up main navigation menu delay.
  setup: function() {
    var that = this;

    this.items = $$("#menu > li");
    if (this.items.length === 0) {
      alert("CSS selector failed to match menu items");
      return;
    }

    this.active = null;

    this.items.each(function(element, index) {
      element.observe("mouseover", function(event) {
        that.show(element);
      });

      element.observe("mouseout", function(event) {
        that.hide(element);
      });
    });
  },

  // Show menu item.
  show: function(element) {
    var that = this;

    this.active = element;

    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }

    this.timeoutId = setTimeout(function() {
      if (that.active === element) {
        that.hideExcept(element);
        element.addClassName("hover");
      }
    },
    this.timeout);
  },

  // Hide menu item.
  hide: function(element) {
    var that = this;

    this.active = null;

    if (element.hasClassName("hover")) {
      setTimeout(function() {
        if (that.active !== element) {
          element.removeClassName("hover");
        }
      },
      this.timeout);
    }
  },

  // Hide menu items except one.
  hideExcept: function(element) {
    this.items.each(function(item) {
      if (item !== element) {
        item.removeClassName("hover");
      }
    });
  }
};

document.observe("dom:loaded", function() {
  Menu.setup();
});
