
$(document).ready(function()
{
	onMenuOver = function()
	{
		var sub = $(this).find('.sub');
		
		// Hide all other submenus before opening this one		
		$('#menu-top').find('.sub').hide();
		
		// Fade in
		sub.stop().fadeTo('fast', 1).show();
		
		userAgent = $.browser.version;
		userAgent = userAgent.substring(0, userAgent.indexOf('.'));
		version   = userAgent;
		
		if ($.browser.msie && version < 8) {
			// Reposition the submenu width after a little timeout (IE < 8 fix)
			setTimeout(function() {
				moveSub(sub);
			}, 50);
		} else {
			moveSub(sub);
		}
	}
	
	moveSub = function(sub)
	{
		var menu_width = $('#menu-top').width();
		var item_left  = sub.parent().position().left || 0;
		var sub_width  = sub.width();
		
		// Positioning the submenu
		if (item_left + sub_width > menu_width)
		{
			// Submenu position would overflow the container; Recalculate 
			// the new submenu and submenu arrow positions
			var diff       = (item_left + sub_width) - menu_width;
			var arrow_left = 15; // css 'left' value
			
			sub.find('.arrow').css('left', diff + arrow_left);
			sub.css('left', menu_width - sub_width);
		} 
		else 
		{
			sub.css('left', item_left);
		}
	}
	
	onMenuOut = function()
	{
		var sub = $(this).find(".sub");
		
		// Fade out
		sub.stop().fadeTo(100, 0, function() {
			$(this).hide(); 
		});
	}
	
	var hoverCfg = {    
		 sensitivity  : 2,           // number = sensitivity threshold (must be 1 or higher)    
		 interval     : 200,         // number = milliseconds for onMouseOver polling interval    
		 over         : onMenuOver,  // function = onMouseOver callback (REQUIRED)    
		 timeout      : 800,         // number = milliseconds delay before onMouseOut    
		 out          : onMenuOut    // function = onMouseOut callback (REQUIRED)    
	};

	$("#menu-top li .sub").css({'opacity':'0'});
	$("#menu-top > li").hoverIntent(hoverCfg);
});
