/**
 * The Last Detail Mega Navigation
 * Copyright 2010
 * Author: Luke Robinson.
 */
 
$(document).ready(function(){
	
	// Mega Navigation Initialisation
	var $mega_nav = $('#mega_nav');
	var fade_in_speed = 300;
	var fade_out_speed = 380;
	var hover_out_timer = 550;
	
	$('.sub_category_wrapper',$mega_nav).data('active_hover', false);
	$('.menu_item > a',$mega_nav).data('active_hover', false);
	
	// The hover event has an intent action that stops the mouse over function
	// from running immediately. We need to set the active_hover data 
	// attribute to true using the mouseenter event to overcome this problem.
	
	$('.menu_item > a',$mega_nav).mouseenter(function(){
		$(this).data('active_hover',true);										  
	});
	
	$('.menu_item > a',$mega_nav).hover(							 
		function()
		{
			var $anchorElement = $(this);

			// If this anchor doesn't have an active class, then we know it's
			// safe to clear the add the active class, clear the fade timer and
			// display the main listing area.
			
			if(! $anchorElement.hasClass('active'))
			{
				clearTimeout($anchorElement.data('pauseTimer'));
				
				// If there are no other visible sub category listings then
				// it's much nicer to use a fade in effect rather than show
				
				if($('.sub_category_wrapper:visible',$mega_nav).length == 0)
				{
					$anchorElement.next().fadeIn(fade_in_speed);
				}
				else
				{
					$('.sub_category_wrapper',$mega_nav).hide();
					$anchorElement.next().show();						
				}
				
				$('.active',$mega_nav).removeClass('active');
				$anchorElement.addClass('active');	
			}
		},
		function()
		{
			var $anchorElement = $(this);
			$anchorElement.data('active_hover',false);
			$anchorElement.data('pauseTimer', listener($anchorElement.next()) );
		}
	);
	
	// Large listing pane
	$('.sub_category_wrapper',$mega_nav).hover(
		function()
		{
			$(this).data('active_hover',true);
		},
		function()
		{
			$(this).data('active_hover',false);	
			listener($(this));
		}
	);
	
	// Mouse position listener
	var listener = function($category_listing)
	{
		var pauseTimer = setTimeout(function()
		{
			// The user should be hovering over the large listing area or the 
			// the top related heading element before closing the listing area.
			
			if($category_listing.data('active_hover') == false 
				&& $category_listing.prev().data('active_hover') == false)
			{
				$category_listing.prev().removeClass('active');
				$category_listing.fadeOut(fade_out_speed);
			}
		},hover_out_timer);
		
		return pauseTimer;
		
	}
	
});