 var $getEls, $getListElts, $getAgn, $div;
  var divId, eNext;

  $(function() {
    $getEls = $('ul#menu > li');
    $getListElts = $('div#submenus > div');
    $getAgn = $getEls;

    $getEls.each(function(i) {
      $(this).mouseover(function() {
        var thisParent = this;
        $getAgn.each(function() {
          if (this.id != thisParent.id) {
            $(this).removeClass();
          }
        });

        if (!$(this).hasClass('shrink') && !$(this).hasClass('clicked')) {
          $(this).addClass('clicked');
        }

        var divId = this.id.replace("li", "ul");
        $div = $('#' + divId);
        eNext = $div.children('ul').get(0);

        $div.get(0).style.left = this.offsetLeft + "px";

        if ($(this).hasClass('clicked')) {
          slideOut();
          $(this).removeClass().addClass('shrink');
        }
        else {
          if ($div.children('ul').length > 0) {
            $div.stop().animate({ height: 0 }, 300); // contract once
          }
          $(this).removeClass();
        }
        slideIn();
      });

    });

    function slideOut() {
      if ($div.children('ul').length > 0) {
        var startPos = parseInt($div.get(0).offsetHeight);
        if (startPos == 0) {
          $div.stop().animate({ height: eNext.offsetHeight + 'px' }, 300); // expand
        }        
      } 
    }

    function slideIn() {
      $getListElts.each(function() {
        if (divId != this.id && this.style.height > 0 + 'px') {
          var curHeight = parseInt(this.style.height);
          var curNext = $(this).children('ul').get(0);
          if (curHeight == parseInt(curNext.offsetHeight)) {
            $('#' + this.id).stop().animate({ height: 0 }, 300);  // contract
          }
        }
      });
    }

  });
