document.observe("dom:loaded", function() 
{
  $$('#menu > li > a').each(function(menu_link)
  {
    menu_link.observe("click", respondToClick);
  });
})

function respondToClick(event) {
  menu_link = event.element();
  menu_link.up().select("ul").each(function(menuOfClickedCategory) {
    conditionallyCloseSubMenus(menuOfClickedCategory);
  })
  Event.stop(event); // don't refresh the page
}

function conditionallyCloseSubMenus(clickedMenu) {
  $$('#menu > li ul').each(function(subMenu) {
    if(!containsCurrentPage(subMenu)) { // never hide the category that contains the current page
      if(subMenu == clickedMenu) {
        subMenu.toggle(); // hide or show the clicked one
      }
      else {
        subMenu.hide(); // hide the rest
      }   
    }
  });
}

function containsCurrentPage(subMenu) {
  return subMenu.hasClassName('contains_current_page');
}

