/**
 * features.js
 * Functionality for navigating through features on home page.
 *
 * Requres jQuery.
 *
 */

var index = 0;
var previousIndex = 0;
var features = Array();
var timer = null;
var enableSlideshow = true;
var duration = 10000;

$(window).bind('load', function(){
	// Get the features
	features = $('#homeSlideshow .item');
	// Only enable the slideshow if there is more than one feature
	if (features.length < 2) enableSlideshow = false;
	// Only start slideshow timer if slideshow is enabled
	if (enableSlideshow) timer = setTimeout(nextFeature, duration);
	$('#homeSlideshow .nav li.control a').bind('click', function(){
		// If timer is set, stop the slideshow, otherwise resume
		if (timer) {
			// Pause
			enableSlideshow = false;
			timer = clearTimeout(timer);
			$('#homeSlideshow .nav li.control img').attr('src', 'img/buttons/play-front.gif');
			$('#homeSlideshow .nav li.control img').attr('alt', 'Play');
			$('#homeSlideshow .nav li.control a').attr('title', 'Play');
		} else {
			// Play
			enableSlideshow = true;
			nextFeature();
			$('#homeSlideshow .nav li.control img').attr('src', 'img/buttons/pause-front.gif');
			$('#homeSlideshow .nav li.control img').attr('alt', 'Pause');
			$('#homeSlideshow .nav li.control a').attr('title', 'Pause');
		}
	});	
});

function nextFeature() {
	// Set index to zero if on last feature
	if (index == (features.length - 1)) {
		// Reset index to first item
		index = 0;
	} else {
		// Increment index by one
		index++;
	}
	// Show feature
	showFeature(index);
}

function previousFeature() {
	// Set index to last feature if on first feature
	if (index == 0) {
		// Reset index to last item
		index = features.length - 1;
	} else {
		// Decrement index by one
		index--;
	}
	// Show feature
	showFeature(index);
}

function showFeature(newIndex) {
	// Reset timer
	if (enableSlideshow) {
		clearTimeout(timer);
		timer = setTimeout(nextFeature, duration);
	}
	// Set global index variable to new index value
	index = newIndex;
	// Fade out the previous feature
	features.eq(previousIndex).fadeOut(750, function(){
		// Remove "on" class from previous feature number
		var items = $('#homeSlideshow li:not(.control)');
		items.removeClass('on');
		items.eq(index).addClass('on');	
		// Fade in new feature
		features.eq(index).fadeIn(500, function(){
			previousIndex = index;
		});
	});
}