var featureCount = 5; // The number of features on the page.
var holdDuration = 10000; // The amount of time between cycles.
var shortFadeDuration = 500; // The time to animate between features.
var longFadeDuration = 1000;
var timer; // Reference to the timer that cycles through the features.
var lastEntryTime = 0; // The time the user last entered the Features area.
var currentFeatureID; // The number of the feature currently being shown; set in the php.

function cycleTo(targetFeatureID, animDuration)
{
	// Set the default animation length...
	if (animDuration == null)
	{
		animDuration = longFadeDuration;
	}

	// Highlight the selected feature button.
	for (var i = 1; i <= featureCount; i++)
	{
		if ( i == targetFeatureID )
		{
			$(".feature-" + i).addClass("selected");
		}
		else
		{
			$(".feature-" + i).removeClass("selected");
		}		
	}

	// Fade to the selected feature and update the current feature ID value.
	$("#feature-"+currentFeatureID).slideUp(animDuration, function() {
		$("#feature-"+targetFeatureID).slideDown(animDuration);
	});
	currentFeatureID = targetFeatureID;
	
	// Restart the timer.
	startCycleTimer();
	
}

function startCycleTimer(pauseTime)
{
	// Reset the animation timer...
	clearTimeout(timer);
	
	// Set the next feature number...
	var nextFeatureID = currentFeatureID + 1;
	if (nextFeatureID > featureCount)
	{
		nextFeatureID = 1;
	}
	
	if(pauseTime == null)
	{
	pauseTime = holdDuration;
	}
	
	timer = setTimeout("cycleTo(" + nextFeatureID + ")", pauseTime);
}

function onFeatureMouseEnter()
{
	// Store the current time
	var d = new Date();
	lastEntryTime = d.getTime();
	
	// Stop cycling the features.
	clearTimeout(timer);
}

function onFeatureMouseLeave()
{
	// Store the current time
	var d = new Date();
	var elapsedTime = d.getTime() - lastEntryTime;
	
	if( elapsedTime > holdDuration)
	{
	// Start cycling the features again.
	startCycleTimer(0);
	}
	else
	{
	// Start cycling the features again.
	startCycleTimer(holdDuration - elapsedTime);
	}

}

function onMenuItemMouseEnter(featureID)
{
	// Stop any current animation...
	$("#feature-"+currentFeatureID).stop(true,true);

	// Cycle to the highlighted feature.
	cycleTo(featureID, shortFadeDuration);
	
	// Stop cycling the features.
	clearTimeout(timer);
}

function onMenuItemMouseLeave(featureID)
{
	// Start cycling the features again.
	startCycleTimer();
}

$(document).ready(function(){
	
	for (var i = 1; i <= featureCount; i++)
	{
		// Create listeners for the feature links.
		$(".feature-" + i + " span").mouseenter( new Function("onMenuItemMouseEnter(" + i + ");") );
		$(".feature-" + i + " span").mouseleave( new Function("onMenuItemMouseLeave(" + i + ");") );
	}
	
	$("#feature-content").mouseenter( new Function("onFeatureMouseEnter();") );
	$("#feature-content").mouseleave( new Function("onFeatureMouseLeave();") );
	
	// Start the timer.
	startCycleTimer();
	
});