var Menu = Class.create();

Menu.prototype =
{
  activeItem: null,
  timerHideBox: null,
  timerShowBox: null,
  delay: 375,

  initialize: function()
  {
    this.container = $('navigation');

    $$('#mega-nav li').each((function(li){
      this.addEvents(li);
      if (li.hasClassName('active'))
      {
        this.activeItem = li;
      }
    }).bind(this));

    if (this.activeItem) this.activeItem.down('.menu').show();

  },

  addEvents: function(li)
  {
    box = li.down('.menu');

    if ( ! box ) return;
    li.hover(
      (function(event) { this.itemOver(li) }).bind(this),
      (function(event) { this.itemOut(li)  }).bind(this)
    );

  },

  itemOver: function(li)
  {
    clearTimeout(this.timer);
    this.timer = null;

    var self = this;
    self.timer = setTimeout(function() { self.show( li ); self.timer = null; }, this.delay);

  },

  itemOut: function(li)
  {
    clearTimeout(this.timer);
    this.timer = null;

    var self = this;
    self.timer = setTimeout(function() { self.hide( li ); self.timer = null; }, this.delay);
  },

  show: function(li)
  {
    this.hideAll();
    li.addClassName('hover');
    if (li != this.activeItem)
    {
      if (this.activeItem) this.activeItem.down('.menu').hide();
    }
  },

  hide: function(li)
  {
    li.removeClassName('hover');
    if (this.activeItem) this.activeItem.down('.menu').show();
  },


  hideAll: function()
  {
    $$('#mega-nav li').each((function(li){
      if (! li.hasClassName('.active'))
      {
        box = li.down('.menu');
        if (box) this.hide(li);
      }
    }).bind(this));
  }

};


Event.observe(window, 'load', function(){
  new Menu;
});

