/*
 * Droppy 0.1.2
 * (c) 2008 Jason Frame (jason@onehackoranother.com)
 */
(function(jQuery) {
  
  jQuery.fn.droppy = function(options) {

    options = jQuery.extend({speed: 500, className: 'droppy', trigger: 'hover'}, options || {});

    this.each(function() {

      var root = this, zIndex = 2000;

      jQuery(root).addClass(options.className);
			jQuery(root).find('li:has(> ul) > a').addClass('has-subnav');

      function getSubnav(ele) {
        if (ele.nodeName.toLowerCase() == 'li') {
          var subnav = jQuery('> ul', ele);
          return subnav.length ? subnav[0] : null;
        } else {
          return ele;
        }
      };

      function getActuator(ele) {
        if (ele.nodeName.toLowerCase() == 'ul') {
          return jQuery(ele).parents('li')[0];
        } else {
          return ele;
        }
      };

      function hide() {
        var subnav = getSubnav(this);
        if (!subnav) return;
        jQuery.data(subnav, 'cancelHide', false);
        setTimeout(function() {
          if (!jQuery.data(subnav, 'cancelHide')) {
            jQuery(subnav).slideUp(options.speed);
          }
        }, 500);
      };

      function show() {
        var subnav = getSubnav(this);
        if (!subnav) return;
        jQuery.data(subnav, 'cancelHide', true);
        jQuery(subnav).css({zIndex: zIndex++}).slideDown(options.speed);
        if (this.nodeName.toLowerCase() == 'ul') {
          var li = getActuator(this);
          jQuery(li).addClass('hover');
          jQuery('> a', li).addClass('hover');
        }
        return false;
      };
      
      if (options.trigger == 'click') {
        jQuery('> li', this).click(show);
        jQuery('> li ul, > li li', this).hover(show, function() {});
        jQuery('ul, li', this).hover(function() {}, hide);
      } else {
        if (typeof jQuery.fn.hoverIntent == 'function') {
          jQuery('ul, li', this).hoverIntent(jQuery.extend({
            sensitivity: 2, interval: 50, timeout: 100
          }, options.hoverIntent || {}, {over: show, out: hide}));
        } else {
          jQuery('ul, li', this).hover(show, hide);
        }
      }
      
      jQuery('li', this).hover(
        function() { jQuery(this).addClass('hover'); jQuery('> a', this).addClass('hover'); },
        function() { jQuery(this).removeClass('hover'); jQuery('> a', this).removeClass('hover'); }
      );

    });

  };

})(jQuery);

