/* ************************ JQUERY MENU **************************** */

(function($){
	
	$.fn.menu = function(options){
		
		var opts = $.extend({}, $.fn.menu.defaults, options);
		
		return this.each(function(){
			
			// Cache the UL //
			var $this = $(this);
			
			// Cache the children //
			var $parentLinks = $this.children( opts.menuTagNames );
			
			// Hover for link items //
			$parentLinks.each(function(){
				
				var $link = $(this);
				
				var $dl = $link.children( opts.menuChildrenTagNames );
				
				$link.data('doAnimate', true);
				
				// On mouse over of each main link //
				$link.mouseover(function(){
					
					$link.data('doHide', false)
						.addClass(opts.hoverClass);
					
					if( siblingsShowing( $link ) ){
						// Show the dl of this element //
						$dl.show();
						
					} else {
						// Show the dl of this element //
						if(opts.animate){
							if($link.data('doAnimate')){
								$dl.fadeIn( opts.fadeTime );
							} else $dl.show();
						} else {
							$dl.show();
						}
					}
					
					// Hide any siblings of this parent link //
					$link.siblings().children( opts.menuChildrenTagNames ).hide();
				});
				
				// Mouse out on NAV item //
				$link.mouseout(function(e){
									
					$link.data('doHide', true)
						.data('doAnimate', false)
						.removeClass(opts.hoverClass)
					
					$.doTimeout('hideThis', 200, function(){
						hideList($link);
					});
					
				});
				
				$link.children('dl').mouseover(function(){
					$link.data('doHide', false);
				});
				
				$link.children('dl').mouseout(function(){
					$link.data('doHide', true);
				});
				
			});
		});
		
		function siblingsShowing($link){
			var displayed = false;
			$link.siblings().each(function(){
				var $this = $(this);
				$this.children('dl').each(function(){
					var $dl = $(this);
					if( $dl.css('display') == 'block' ){
						displayed = true;
						return false;
					}
				});
				
				if( displayed ){
					return false;
				}
				
			});
			
			
			return displayed;
		}
		
		function hideList($link){
			var $dl = $link.children('dl');
			if($link.data('doHide')){
				if(opts.animate){
					$dl.fadeOut( opts.fadeTime, function(){	
						$link.data('doAnimate', true);
					});
				} else {
					$dl.hide();
				}
			}
		}
	}
	
	// Menu default options //
	$.fn.menu.defaults = {
		menuTagNames:'li',
		menuChildrenTagNames:'dl',
		fadeTime:500,
		hoverClass:'hover'
	};
	
	
})(jQuery);
