/*
 * jQuery menu plugin 0.1
 *
 * Copyright (c) 2011 Simon Luijk
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($){
  var initMenu = function(options){
    var defaults = {
      openDelay: 100,
      closeDelay : 300,
      subMenuSelector: '.nav_submenu',
      openClass: 'nav_open'
    };
    var options = $.extend(defaults, options);

    return this.each(function(){
      var block = false,
          openTimer = null,
          closeTimer = null,
          menuDiv = $(this),
          menuButtons = menuDiv.children('li');

      menuDiv.unbind('mouseleave').bind('mouseleave', function(event){
        window.clearTimeout(openTimer);
        closeTimer = window.setTimeout(function(){
          var count = 0;
          block = true;
          menuDiv.find(options.subMenuSelector).each(function(){
            count++;
            var buttonEle = $(this);
            buttonEle.parent().removeClass(options.openClass)
            buttonEle.stop(true, true).fadeOut('fast', function(){
              count--;
              window.setTimeout(function(){
                if ( count === 0 ){
                  block = false;
                }
              }, options.openDelay);
            });
          });
        }, options.closeDelay);
      });

      menuButtons.each(function(){
        var buttonEle = $(this);
        var subMenu = buttonEle.find(options.subMenuSelector);

        if (subMenu.length){
            subMenu.parents('ul, div').css('z-index', 2000);
        }

        buttonEle.unbind('mouseenter').bind('mouseenter', function(){
          menuButtons.find(options.subMenuSelector).not(subMenu).each(function(){
            var otherButtonEle = $(this);
            otherButtonEle.parent().removeClass(options.openClass);
            otherButtonEle.stop(true, true).hide();
          });

          if (subMenu.length){
            window.clearTimeout(closeTimer);
            window.clearTimeout(openTimer);
            openTimer = window.setTimeout(function(){
              if ( !block ) {
                subMenu.slideDown('fast').css('z-index', 1000);
                subMenu.parent().addClass(options.openClass);
              }
            }, options.openDelay);
          }
        });
      });
    });
  };

  $.fn.extend({
    initMenu: initMenu
  });
})(jQuery);

