
var newNavigation;
var Navigation = Class.create();
Navigation.prototype = {
  
  initialize: function() {
    
    var th = this;
    
    th.menus = new Array();
    th.delayRate = 0;
    th.hide_delay = undefined;
    
    var nav_top_ul = $('sub_nav').firstDescendant();
    
    // go through top li's
    nav_top_ul.childElements().each(function(topElm){
      
      var uls = topElm.select('ul');
      var ulElm = uls[0];
      
      var classes = $w(topElm.className);
      th.menus.push(classes[0]);
      
      
      if( ulElm ) {
        
        var top_as = topElm.select('a');
        Element.observe(ulElm,'mouseout',th.hide_menu.bindAsEventListener(th,ulElm));
        Element.observe(top_as[0],'mouseover',th.show_menu.bindAsEventListener(th,ulElm));
        
        ulElm.select('li').each(function(aElm){
          //Element.observe(aElm,'mouseout',th.hide_menu.bindAsEventListener(th,ulElm));
          Element.observe(aElm,'mouseover',th.came_back.bindAsEventListener(th,ulElm));
        });
        
      } else {
        
        Element.observe(topElm,'mouseover',th.hide_top_menus.bindAsEventListener(th,topElm));
        
      }
      
    });
    
  },
  
  hide_top_menus: function(e,elm) {
    
    var menus = this.menus;
    var classes = $w(elm.className);
    
    for( var i=0; i<menus.length; i++ ) {
      var ulToClose = $$('ul.'+menus[i]);
      if( ulToClose.length > 0 ) ulToClose[0].removeClassName('show_menu');
    }
    
  },
  
  show_menu: function(e,elm) {
    
    this.hide_top_menus(e,elm); 
    elm.addClassName('show_menu');
    
  },

  hide_menu: function(e,elm) {

    var th = this;
    var over_right_menu = th.over_right_menu(e,elm);
    
    if( over_right_menu ) {
      Event.stop(e);
    } else {
      th.hide_delay = Element.removeClassName.delay(th.delayRate,elm,'show_menu');
    }
    
  },
  
  over_right_menu: function(e,elm) {
    
    var elmOver = e.relatedTarget;
    var menuClass = $w(elm.className);
    var menuElm = $$('li.'+menuClass[0])[0];
    
    var flag = elmOver ? elmOver.descendantOf(menuElm) : false;
    
    return flag;
    
  },
  
  came_back: function(e,elm) {
    
    var th = this;
    window.clearTimeout(th.hide_delay);
    
  }
  
};


function initNavigation() { newNavigation = new Navigation(); }
document.observe('dom:loaded', initNavigation);