/*
* jdMenu 1.4.1 (2008-03-31)
*
* Copyright (c) 2006,2007 Jonathan Sharp (http://jdsharp.us)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://jdsharp.us/
*
* Built upon jQuery 1.2.1 (http://jquery.com)
* This also requires the jQuery dimensions >= 1.2 plugin
*/

(function($) {
    function addEvents(ul) {
        $('> li', ul)
          .bind('mouseenter.jdmenu mouseleave.jdmenu', function(evt) {
            if ( $(this).parent().hasClass('jdMenu') ) {
               var ul = $('#' + $(this).attr('id') + '-submenu');
            } else {                    
               ul = $('> ul', this);
            }
            if (ul.length == 1) {
               clearTimeout( this.$jdTimer );
               if ( evt.type == 'mouseenter' ) {
                  this.$jdTimer = setTimeout(function() { showMenu(ul[0], $.fn.jdMenu.defaults.onAnimate, $(ul).hasClass('jdMenu_vertical')); }, $.fn.jdMenu.defaults.showDelay);
               } else {
                   if( !($(this).parent().hasClass('jdMenu') && ul.x() - $(".content")[0].scrollLeft <= evt.pageX && evt.pageX <= ul.x() - $(".content")[0].scrollLeft + ul.width()) ) {
                     this.$jdTimer = setTimeout(function() { hideMenu(ul[0], $.fn.jdMenu.defaults.onAnimate, $(ul).hasClass('jdMenu_vertical')); }, $.fn.jdMenu.defaults.hideDelay);
                   }
               }
           }
       })
       .bind('click.jdmenu', function(evt) {
           var ul = $('#' + $(this).attr('id') + '-submenu');
           if ( ul.length == 1 && ($.fn.jdMenu.defaults.disableLinks === true || $(this).hasClass('accessible') ) ) {
               showMenu( ul, $.fn.jdMenu.defaults.onAnimate, $.fn.jdMenu.defaults.isVertical );
           }
           return false;
       });
    
       $('ul.mainSubmenuClone')
          .bind('mouseleave.jdmenu', function(evt) {
              var ul = $(this);
              var li = $('#' + $(this).attr('id').split('-submenu')[0]);
              if ( li.length == 1 ) {
                clearTimeout( this.$jdTimer );
                if( !((li.x() - $(".content")[0].scrollLeft) <= evt.pageX && evt.pageX <= (li.x() - $(".content")[0].scrollLeft + li.width() ) && (li.y() - $(".content")[0].scrollTop + li.height() + parseInt(li.css('border-bottom-width'), 10) ) >= evt.pageY) ) {
                  this.$jdTimer = setTimeout(function() { hideMenu(ul[0], $.fn.jdMenu.defaults.onAnimate, $(ul).hasClass('jdMenu_vertical') , $.fn.jdMenu.defaults.hideDelay);});
                } 
              }
          });
   }

   function showMenu(ul, animate, vertical) {
     if ( $(ul).is(':visible') ) {return;}
    
     $(ul).bgiframe();
    
     var maxZ = 4;
     $('ul.jdm_events:visible').each(function() {
        maxZ = Math.max(maxZ, parseInt($(this).css('z-index'),10));
     });
     $(ul).css('z-index', ++maxZ);
     
     if ($(ul).parent().hasClass('content')) {
       var li = $('#' + $(ul).attr('id').split('-submenu')[0]);
     } else {
       li = $(ul).parent();
     }
     
     $(ul).trigger('jdMenuShow')
          .positionBy({target: li[0], 
                       targetPos: ( vertical === true || !li.parent().hasClass('jdMenu') ? 1 : 3 ), 
                       elementPos: 0,
                       hideAfterPosition: true
                    });
     if ( !$(ul).hasClass('jdm_events') ) {
       $(ul).addClass('jdm_events');
       addEvents(ul);
     }
      
     // Hide any adjacent menus
     li.siblings('li').find('> ul:eq(0):visible').each(function(){ hideMenu( this ); });
     if ( animate === undefined ) {
       if($(ul).hasClass('mainSubmenuClone')) {
         //recalculate position with scrolling positions
    	 //if($(".content").attr("tagName")){
    	   if($(".content").attr("tagName") === "DIV"){
	         $(ul).css('top',parseInt($(ul).css('top'), 10)+$(".content")[0].scrollTop-1);
	         $(ul).css('left',parseInt($(ul).css('left'), 10)+$(".content")[0].scrollLeft);
    	 }
       }
       $(ul).show();
     } else {
       animate.apply( ul, [true] );
     }
   }
   
   function hideMenu(ul, animate) {
     $('.bgiframe', $(ul)).remove();
     $(ul).filter(':not(.jdMenu)')
          .find('> li > ul:eq(0):visible')
          .each(function() { hideMenu( this ); })
          .end();
     if ( animate === undefined ) {
       $(ul).hide();
     } else {
       animate.apply( ul, [false] );
     }
     $(ul).css('z-index', 4).trigger('jdMenuHide');       
   }
   
   // Public methods
   $.fn.jdMenu = function(options) {

    $.fn.jdMenu.defaults = $.extend({}, $.fn.jdMenu.defaults, options);

    if (!$.isFunction($.fn.jdMenu.defaults.onAnimate)) {
      $.fn.jdMenu.defaults.onAnimate = undefined;
    }
    return this.filter('ul.jdMenu').each(function() {
      var $mainMenu = $(this);
      $('> li > ul', this).each( function() {
        var $clone = $(this).clone(true).addClass("mainSubmenuClone").appendTo('.content');
        if ($mainMenu.hasClass("jdMenu_vertical")) {
          $clone.addClass("jdMenu_vertical");
        }
        $(this).remove();                
      });           
      addEvents(this);
    });
   };
   
   $.fn.jdMenu.defaults = {
     showDelay: 100, // Time in ms before menu shows
     hideDelay: 200, // Time in ms before menu hides
     disableLinks: false, // Should items that contain submenus not respond to clicks
     onAnimate:  null     // This callback allows for you to animate menus
   };
   
   $.fn.jdMenuUnbind = function() {
       $('ul.jdm_events', this).unbind('.jdmenu');
   };
   
   $.fn.jdMenuHide = function() {
       return this.filter('ul').each(function(){ 
           hideMenu( this );
       });
   };

   // Private methods and logic
   // Bind a click event to hide all visible menus when the document is clicked
   $(window).bind('click.jdmenu', function() {
       $('ul.jdMenu ul:visible').jdMenuHide();
       $('ul.mainSubmenuClone:visible').jdMenuHide();
   });
})(jQuery);
                