/*****
author: karl@interclue.com

//usage 
$(".menu").menu();

//advanced
$(".menu").menu({
	onshow: function(){
	},
	
	onhide: function(){
	}
});

*****/

(function($){

	$.fn.menu = function(options){
		
		var opts = $.extend({}, $.menu.defaults, options);
		
		return this.each(function(){
		
			var $ul = $(this).is('ul') ? $(this) : $(this).find('ul:first');
		
			if ($ul.length){
				$ul.find('> li').hover(function(){
					var $submenu = $(this).find("ul:first");
					
					//make sure only the current page's submenu is being shown
					//and immediately hide any other menu that happens to be open
					if ($submenu.length){
						$ul.find("ul").each(function(){
							if (this !== $submenu[0]){
								$(this).hide();
							}
						});
						
						if ($submenu.is(":hidden")){
							//and show this menu
							$submenu.css(opts.css);
							opts.showFunc($submenu[0], function(){
								opts.onShow(this);
							});
						}
					}
				}, function(){
					var $submenu = $(this).find("ul:first");
					opts.hideFunc($submenu[0], function(){
							opts.onHide(this);
						
					});
				});
			}
			else {
				throw Error("Menu: Unable to find ul")
			}
		});
	};
	
	
	$.menu = {
		defaults: {
			showFunc: function(ele, callback){
				$(ele).fadeIn(callback);
			},
			
			hideFunc: function(ele, callback){
				$(ele).fadeOut(callback);
			},
			
			onHide: function(){},
			
			onShow: function(){},
			
			css: {
				zIndex: 9999
			}
		}
	}

})(jQuery)
				
