/*
 * jQuery Plugin for rendering dropdown menus
 *
 * @license		Not for redistribution
 * @copyright	2009 Coronis and midd.ag
 * 				http://www.coronis.nl and http://www.midd.ag
 *
 * @version		$Id: cfr.js 15 2009-01-30 14:43:30Z v.delfant $
 */

jQuery.fn.menu = function(settings){
	// Set the default settings for the menu
	if (settings == undefined)
	{
		settings = {
			fade: true
		};
	}

	// Iterate through the matched jQuery elements and set them as a menu
	return this.each(function(){
		var container = jQuery(this);

		jQuery(this).children('li').each(function(){
			var parent = jQuery(this);

			jQuery(this).children('ul').each(function(){
				var menu = jQuery(this);

				// Make sure all client LI-elements have the same width
				menu.children('li').width(menu.width());

				// Container gets z-index by default thanks to the helpful jQuery devs at http://dev.jquery.com/ticket/4679...
				container.css('z-index', 1);

				// Set the required CSS
				menu.css({
					'position'		: 'absolute',
					'display'		: 'none',
					'z-index'		: container.css('z-index') + 1
				});

				// Hovering over the menu UL itself should always show the menu
				menu.hover(function(){
					menu.data('hovering', true);
					parent.children('a:first').addClass('hover');
				}, function(){
					menu.data('hovering', false);
					parent.children('a:first').removeClass('hover');

					if (settings.fade)
					{
						menu.fadeOut(100);
					}
					else
					{
						menu.hide();
					}
				});

				// ... whilst hovering over the trigger A needs some thinking
				parent.children('a:first').hover(function(){
					parent.children('a:first').addClass('hover');

					if (settings.fade)
					{
						menu.fadeIn(100);
					}
					else
					{
						menu.show();
					}
				}, function(){
					menu.oneTime(1, null, function(){
						if (!menu.data('hovering'))
						{
							parent.children('a:first').removeClass('hover');

							if (settings.fade)
							{
								menu.fadeOut(100);
							}
							else
							{
								menu.hide();
							}
						}
					});
				});
			});
		});
	});
};