jQuery(document).ready(function(){

	if( $('#featured').length ){
	
		// Initialise timer object to fire every second
		last = jQuery('.slide').length-1;
		totalSec = 6;
		timer = setInterval(countdown, 1000);
		
		// Hide all slides and text
		jQuery('.slide').hide();
		
		current = 0;
		
		// Mark first control as selected
		jQuery('#control'+current).addClass('selected');
		
		// Display first slide
		jQuery('#slide'+current).show();
			
		// Assign hover effect to each control
		jQuery("#featured-menu a").each( function (IntIndex) {
		
				jQuery(this).hover(featureOn, featureOff);
				
				function featureOn() {
					pause();
					if(IntIndex != current){
						swap(IntIndex);
					}
				}
				
				function featureOff() {
					play();
				}
				
		});
		
		//Assign hover effect to the slides
		$('#featured .slide').mouseover(function(){
			pause();
		});
		$('#featured .slide').mouseout(function(){
			play();
		});
		
		//Assign hover effect to the slides
		$('#featured .slide').hover(pause, play);
		
	}
});

var totalSec;
var timer;
var isPlaying = true;
var current;
var last;

// Swaps to selected control
function swap(next) {

	// Unmark current control	
	jQuery('#control'+current).removeClass('selected');
	
	// Select next control
	jQuery('#control'+next).addClass('selected');

	// Hide all slides and text
	jQuery('#slide'+current).stop(true, true).fadeOut(500);//, function(){
			
	// Display next slide
	jQuery('#slide'+next).stop(true, true).fadeIn(500);
	
	//});
		
	current = next;
}

// Restarts the timer
function play() {
    if (isPlaying == false) {
		totalSec = 3;
        timer = setInterval(countdown, 1000);
		isPlaying = true;
    }
}

// Stops the timer and resets the count down
function pause() {
    if (isPlaying == true) {
        clearInterval(timer);
		isPlaying = false;
    }
}

// Rotates to next slide if timer is at 0
function countdown() {
	// If timer has reached 0
    if( totalSec < 0 ){
	
		// Reset the timer
    	totalSec = 3;
		
		// Get the current slide id number
    	var next = current+1;
		
		// If past the last slide then return to the start
    	if(next > last){			
    		next = 0;
    	}
		
		// Rotate to next slide
		swap(next);
		
    }else{
	
		// Decrement the counter
		totalSec--;	
		
    }
}
