/*
 * jQuery DropMenu
 * ---
 * No-frills drop-downs.
 *
 * (C) 2009 MyNorth Media
 * michael@traversemagazine.com
 */

(function($) {
  $.fn.dropMenu = function(settings) {
    var config = {
      'droppedClass': 'dropped',
      'clickDrag': true,
      'fadeInSpeed': 200,
      'fadeOutSpeed': 400,
      'subSelector': '> ul',
      'subTimeout': 800
    };

    $.extend(config, settings);

    function hideDropDown(menuItem, useTimeout) {
      function gtfoDropdown() {
        $(menuItem).removeClass(config.droppedClass);
        $(menuItem).find(config.subSelector).stop(true, true).fadeOut(config.fadeOutSpeed);
      };

      clearTimeout($(menuItem).data('fadeInt'));

      if (useTimeout) {
        $(menuItem).data('fadeInt', setTimeout(function() {
          gtfoDropdown();
        }, config.subTimeout));
      } else {
        gtfoDropdown();
      }

    };

    function hideAllOtherDropDowns(menuItem) {
      $(menuItem).parent().find('.' + config.droppedClass).each(function() {
        if (this != menuItem) {
          hideDropDown(this, false);
        }
      });
    };

    function showDropDown(menuItem) {
      hideAllOtherDropDowns(menuItem);
      clearTimeout($(menuItem).data('fadeInt'));

      $(menuItem).addClass(config.droppedClass);
      $(menuItem).find(config.subSelector).stop(true, true).fadeIn(config.fadeInSpeed);
    };

    this.each(function() {

      if (config.clickDrag) {
        /* Disable text selection and allow dragging.
        * Not dragging and dropping; that's retarded.
        * This allows you to click-drag off of a link
        * like you would in most UIs. Try it, you'll
        * see what I'm talking about.
        */
        $(this)
          .css({'MozUserSelect': 'none'})
          .bind('selectstart' + '.disableTextSelect' , function() { return false; })
          .bind('mousedown'   + '.disableTextSelect' , function() { return false; })
      }

      $(this).find('> li').each(function() {
        if ($(this).find(config.subSelector).length) {
          $(this).hover(function() {
            showDropDown(this);
          }, function() {
            hideDropDown(this, true);
          });

        } else {
          $(this).mouseover(function() {
            $(this).parent().find('.' + config.droppedClass).each(function() {
              hideDropDown(this, false);
            });
          });
        }
      });

    });

    return this;

  };
})(jQuery);


