var blinding = false;

// stores our timer id for the menu disappearing
var timers = new Hash();

// go through each one and add the relevant styles and events
Event.observe(window, 'load', applyFunkyJSToSubmenus);

// on resize, make sure they stay where they're supposed to be
Event.observe(window, 'resize', repositionSubmenus);
Event.observe(window, 'load', function() { window.setTimeout(repositionSubmenus, 200); }); // and position them now

function showMenu(item) {
  // reset the "hide" timer
  
  if (blinding === true) { // if we're blinding we only want to clear our own timer on mouseover
    
    if (timers.get(item.identify())) // if the timer exists
      window.clearTimeout(timers.unset(item.identify())); // removes the id from the hash and tells the window to clear it :)
    
  } else { // not blinding, we need to clear them all and hide them all
    timers.values().each(function(timer) { window.clearTimeout(timer); }); // clear all the timeouts
    timers = new Hash(); // easiest way to clear the timers I think!
    
    $$('.submenu').select(function(menu) {
      return menu.identify() != item.identify();
    }).invoke('hide'); // and hide them all except this one
    
  }
  
  // show the menu
  if (item.style.display == 'none') {
    if (blinding === true) Effect.BlindDown(item, { duration: 0.4 }); // blinding doesn't work very well for some reason
    else item.show();
  }
}

function hideMenu(item) {
  if (item.style.display != 'none')
    timers.set(item.identify(), window.setTimeout(function() {
      if (blinding === true) Effect.BlindUp(item, { duration: 0.4 }); // blinding doesn't work very well for some reason
      else item.hide();
    }, 250));
}

function repositionSubmenus() {
  $$('.submenu').each(function(item) {
    var parentPos = item.up().cumulativeOffset(); // the containing <li>
    
    item.setStyle({
      left: parentPos.left + 1 + 'px',
      top: (parentPos.top + item.up().offsetHeight + 1) + 'px'
    });
  });
}

function applyFunkyJSToSubmenus() {
  $$('.submenu').each(function(item) {
    var pn = item.up(); // the containing <li>
    
    // fix ie6 spacing problems
    item.cleanWhitespace();
    item.descendants().invoke("cleanWhitespace");
    
    item.hide();
    item.setOpacity(0.8);
    
    // make it show the submenu on mouseover
    pn.observe('mouseover', function() { showMenu(item); });
    pn.observe('mouseout', function() { hideMenu(item); });
  });
}
