var Menu = Class.create({

  initialize: function(e) {
    this.element = $(e);

    this.active = this.element.down('.active')
    this.cols = this.element.select('.col');
    this.subs = this.cols.collect((function(col) {return this.submenu(col)}).bind(this));

    this.cols.each((function(col) {
      Event.observe(col, 'mouseover', this.trigger.bind(this));
      Event.observe(col, 'mouseout', this.tryHide.bind(this));
    }).bind(this));
    this.subs.each((function(sub) {
      Event.observe(sub, 'mouseover', this.trigger.bind(this));
      Event.observe(sub, 'mouseout', this.tryHide.bind(this));
    }).bind(this));

    if(this.active) this.trigger(this.active);
  },

  submenu: function(col) {
    type = col.down('a').className.replace('active', '').strip();
    return $$('div.'+type).first();
  },

  folder: function(submenu) {
    var type = submenu.className.replace('active', '').replace('visible', '').strip();
    return $$('#main-menu a.'+type).first().up('.col');
  },

  trigger: function(element) {
    // Hover checking since we are switching menus
    if(this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }

    // Determine the submenu triggered
    if(element['element']) {
      element = element.element();
      if(!(this.cols.include(element) || this.subs.include(element))) {
        if(element.up('#main-menu')) {
          element = element.up('.col');
        } else {
          element = element.up('#submenu');
        }
      }
    }

    if(!element) return;

    var sub = this.submenu(element)
    if(sub) element = sub;

    // Cancel early if already visible
    if(element.hasClassName('visible')) return;

    // Hide everything that was visible
    this.closeAll();

    // Make hovered element visible
    element.addClassName('visible');
    this.folder(element).addClassName('active');
  },

  tryHide: function() {
    this.timer = setTimeout(this.hide.bind(this), 2000);
  },

  hide: function() {
    if(this.active && this.submenu(this.active).hasClassName('visible')) return;
    this.closeAll();
    if(this.active) this.trigger(this.active);
  },

  closeAll: function() {
    this.cols.each(function(e) {e.removeClassName('active')});
    this.subs.each(function(e) {e.removeClassName('visible')});
  }

});

$(document).observe('dom:loaded', function() {
  var menu = $('main-menu');
  if(menu) new Menu(menu);
});

