
/*
 **** Menufy plugin

 TODO: Document CSS Styles required for initialization
 TODO: Document HTML strucytre required

  Usage: $(<<element_selector>>).menufy(<options>);

  options:
      target: selector that will show up when hovered over

*/
(function($){

  /* Global timer :( */
  var hide_timer = null;
  var last_item;
  var last_otions;

  $.fn.menufy = function(settings){

    var options = $.extend({target: "ul:hidden", hideDelay: 1000, parent: "div"}, settings);

    //console.log(this);

    return $(this).mouseover(function(){ show(this, options); })
                  .mouseout(function(){ shouldHide(this, options); })
                .css('z-index', '1')
            .find(options.target)
                .css('z-index', '1');
  };

  function show(item, options){
    if (hide_timer != null){
      hide(last_item, last_options);
    }

    last_item = item; last_options = options;
    var panel = $(item).siblings(options.target);

    panel
      .closest(options.parent)
        .css('z-index', '2')
        .siblings().css('z-index', '1').end()
      .css('z-index', '20').end()
    .css('z-index', '5');

    panel.fadeIn().find('a').click(function() { hide(last_item, options); return true; });
    panel.mouseenter(shouldShow).mouseleave(function(){ shouldHide(item, options); });
  }

  function shouldHide(item, options){
    hide_timer = setTimeout(function(){ hide(item, options); }, options.hideDelay);
  }

  function shouldShow(){
    clearTimeout(hide_timer);
    hide_timer = null;
  }

  function hide(item, options){
    clearTimeout(hide_timer);
    hide_timer = null;

    var panel = $(item).siblings(options.target);

    if (panel != null){
      panel
        .closest(options.parent).css('z-index', '1').end()
        .css('z-index', '1');

      panel.fadeOut(function(){

        panel.unbind('mouseenter').unbind('mouseleave');
      });
    }
  }

})(jQuery);