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

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

    if (settings) $.extend(config, settings);

    function hideDropDown(menuItem, useTimeout) {
      function gtfoDropdown() {
        $(menuItem).removeClass(config.droppedClass);
        $(menuItem).find('> ul').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('> ul').stop(true, true).hide().fadeIn(config.fadeInSpeed);
    };

    this.each(function() {
      $(this).find('> li').each(function() {
        if ($(this).find('> ul').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);

