$(document).ready(function(){
  // each dropdown has its own timeout, named after the parent li class
  var hideTimer = new Array();

  $("#mainmenu > li").hover(
    function () {
      $(".innernav").hide();
      var submenu = $(this).find("ul");

      // 1. find the position, size and margin for the parent li
      var pos = $(this).position();
      var height = $(this).height();
      var leftmargin = $(this).css("margin-left").replace('px', '');
      var topMargin = $(this).css("margin-top").replace('px', '');
      var bottomMargin = $(this).css("margin-bottom").replace('px', '');
      var x = pos.left + parseInt(leftmargin);
      var y = pos.top + height + parseInt(topMargin) + parseInt(bottomMargin);

      // 2. position the popup
      submenu.css('left', x+'px');
      submenu.css('top', y+'px');

      // 4. cancel any pending hide operations and show the menu
      var intervalKey = $(this).attr('class');
      clearInterval(hideTimer[intervalKey]);
      submenu.fadeIn(300);
    },
    function () {
      // insert a short delay before hiding
      var submenu = $(this).find("ul");
      var intervalKey = $(this).attr('class');
      hideTimer[intervalKey] = window.setTimeout(function() {
        submenu.hide();
      }, 250);
    }
  );

});

