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) {
  // first off, make its 'parent' <a> thingy look hovery
	item.previous().setStyle({ 'backgroundPosition': '-184px 0px' });
	
  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!
    
    $$('.subnav').select(function(menu) {
      return menu.identify() != item.identify();
    }).each(function (it) {
			it.hide(); // hide them all except this one
			it.previous().setStyle({ 'backgroundPosition': '0px 0px' });
		});
    
  }
  
  // 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();
				item.previous().setStyle({ 'backgroundPosition': '0px 0px' });
			}
    }, 250));
}

function repositionSubmenus() {
  $$('.subnav').each(function(item) {
    var parentPos = item.up().cumulativeOffset(); // the containing <li>
    
    item.setStyle({
      left: (parentPos.left + item.up().offsetWidth) + 'px',
      top: (parentPos.top + 2) + 'px'
    });
  });
}

function applyFunkyJSToSubmenus() {
  $$('.subnav').each(function(item) {
    var pn = item.up(); // the containing <li>
    
    // fix ie6 spacing problems
    item.cleanWhitespace();
    item.descendants().each(function(item) { if (item.cleanWhitespace) item.cleanWhitespace(); });
    
    item.hide();
    
    // make it show the submenu on mouseover
    pn.observe('mouseover', function() { showMenu(item); });
    pn.observe('mouseout', function() { hideMenu(item); });
  });
}
