/**
 * Drop-down Menu
 */
;(function($){
	$.fn.dropDownMenu = function(options){
		this.each(function(){
			var o = {};
			jQuery.extend(o, $.fn.dropDownMenu.defaults, options);
			
			/**
			 * Init
			 */
			$(this).data('top-level', true);
			$(this).find('a').each(function(){
				$(this).addClass(o.itemClass);
				if (o.menuMinWidth) $(this).css('min-width', o.menuMinWidth);
			});
			$(this).find('ul').each(function(){
				$(this).css('width', o.subMenuWidth);
				if (o.menuMinWidth) $(this).css('min-width', o.menuMinWidth);
				$(this).data('top-level', false).hide();
			});
			
			/**
			 * Add mouse handlers
			 */
			$(this).find('li').each(function(){
				/**
				 * Check children
				 */
				var ul = $(this).find('ul');
				if (ul.length > 0)
				{
					if (!$(this).data('ul'))
					{
						$(this).data('ul', true);
						if (o.showArrows)
						{
							$(this).find("a:first").append(o.arrowCode);
						}
					}
				}
				
				/**
				 * Mouse enters LI
				 */
				$(this).mouseenter(function(){
					$(this).find('a:first').removeClass(o.itemClass);
					$(this).find('a:first').addClass(o.hoverClass);
					var ul = $(this).find('ul:first');
					if (ul.length && !ul.is(':visible'))
					{
						var topLevel = $(this).parent().hasClass('drop-down-menu');
						if (o.layout == 'vertical')
						{
							$(ul).css('left', topLevel ? parseInt($(this).width())-1 : parseInt(o.subMenuWidth)-1).css('top', '0px');
						}
						else
						{
							if (!topLevel) 
							{
								$(ul).css('left', parseInt(o.subMenuWidth) - 1).css('top', '0px');
							}
						}
						$(ul).show();
					}
				});
				
				/**
				 * Mouse leaves LI
				 */
				$(this).mouseleave(function(){
					$(this).find('a:first').removeClass(o.hoverClass);
					$(this).find('a:first').addClass(o.itemClass);
					$(this).find('ul:first').hide();
				});
			});
		});
	};
	
	// expose defaults
	$.fn.dropDownMenu.defaults = {
		align			: 'horizontal',						// 'horizontal', 'vertical'
		itemClass		: 'drop-down-menu-item',			// 'ddm-menu-item'
		hoverClass		: 'drop-down-menu-item-hover',		// 'ddm-menu-item-hover'
		showArrows		: true,								// true, false
		menuMinWidth	: false,							// false, or width
		subMenuWidth	: '200px',							// with or 'parent' to inherit 
		arrowCode		: '&nbsp; &#187;'					// 
		
	};
})(jQuery);
