// Wordpress safe JQuery invocation
var $j = jQuery.noConflict();
$j(function()
{
	// Stores the currently showing element
	var visibleBox;
	
	// Stores the reference to the current timer.
	var currentTimerID = false;
	
	// Function that will show the specified featured item, deselecting
	// all the previous items.
	function showElement(eleName)
	{
		// Hide all previous
		$j("#featured-posts .post-box").hide();
		
		// De-select all previous
		$j(".morelist ul li a").removeClass('selected');
		
						
		showElem = $j("#" + eleName);
		if (showElem && showElem.length != 0)
		{
			// Store visible
			visibleBox = eleName;
			
			// Show selected
			showElem.fadeIn();
			
			// Show link as selected
			$j("." + eleName).addClass('selected');
		}
	}	
	
	// When called, this function loops to the next featured item to be shown
	// after the currently shown item.
	function runChangeLoop() 
	{
		if (visibleBox.length > 0)
		{
			// Strip the 'featured-post-' of the string.
			var postID = visibleBox.substring(14, 15);
			var nextPost = parseInt(postID) + 1;
			
			// See if next post exists
			nextPostElem = $j("#featured-post-" + nextPost);
			if (nextPostElem && nextPostElem.length != 0) {
				showElement("featured-post-" + nextPost);
			} 
			// Doesn't exist, go back to start
			else {
				showElement("featured-post-1");
			}
		}
	}
	
	// Creates a new interval timer
	function resetTimer()
	{
		// Remove any existing timer
		clearTimeout(currentTimerID);
		
		// Create a timer using a 5 sec interval
		currentTimerID = setInterval(function() {
			runChangeLoop();
		}, 5000);
	}
	
		
	// Show the first featured by default
	var first = $j(".featured-post-1");
	if (first && first.length != 0) {
		showElement("featured-post-1");
	}	
	

	// Start loop by default
	resetTimer();

	// Add event to change the post for the featured when clicked
	for (var $index = 1; $index <= 5; $index++)
	{
		// See what buttons we have, and if we find one, 
		// add the event to show the featured post.
		button = $j(".featured-post-" + $index);
		if (button && button.length != 0)
		{
			button.click(function (e) 
			{
				// Stop the current timer if it exists.
				clearTimeout(currentTimerID);
								
				// Timeout after 5 seconds and start the loop again (which starts after 5 seconds).
				setTimeout(function() {
					resetTimer();
				}, 5000);
				
				// Show selected
				var clicked = e.target;		
				showElement(clicked.className); 
		    });
		}
	}

	
});