var FS_index = 0;
var $FS_nextDiv = 0;
var $FS_nextImage = 0;
var FS_FadeDelay = 6000;
var FS_nextFadeDelay = FS_FadeDelay;
var timeoutRef = 0;
var FS_Running = false;

function FS_Fadeout() {
	var $currentDiv = $('#FS_container div:visible').eq(0); //Get first visible div
	
	//Grab the next image for fading in afterwards
	$FS_nextDiv = $currentDiv.next('div:hidden');
	$FS_nextImage = $FS_nextDiv.find('img').eq(0);
	
	//If we don't have a next image return to the first image
	if ($FS_nextImage.attr('src') == undefined) {
		$FS_nextDiv = $('#FS_container div').eq(0);
		$FS_nextImage = $FS_nextDiv.find('img').eq(0);
	}
	
	//Reset the fadeDelay to the default 6000
	FS_nextFadeDelay = FS_FadeDelay;
	//Fade out current div, when done call FS_Fadein
	$currentDiv.fadeOut('fast', FS_Fadein);
}

function FS_Fadein() {
	//Fade the 'next' div in and then queue it to be faded out
	if (FS_Running) {
		$FS_nextDiv.fadeIn('fast', FS_queueFadeout);
	} else {
		$FS_nextDiv.fadeIn('fast');
	}
}

function FS_queueFadeout() {
	timeoutRef = setTimeout(FS_Fadeout, FS_nextFadeDelay);
}

function FS_resume() {
	FS_Running = true;
	FS_queueFadeout();
}
function FS_pause() {
	clearTimeout(timeoutRef);
	FS_Running = false;
}

function FS_next() {
	var was_running = FS_Running;
	FS_pause();
	FS_nextFadeDelay = 1;
	FS_resume();
	if (was_running == false) {
		setTimeout(FS_pause, 5);
	}
}
function FS_previous() {
	var was_running = FS_Running;
	FS_pause();
	var $currentDiv = $('#FS_container div:visible').eq(0); //Get first visible div
	//Grab the next image for fading in afterwards
	$FS_nextDiv = $currentDiv.prev('div:hidden');
	$FS_nextImage = $FS_nextDiv.find('img').eq(0);
	
	//If we don't have a next image return to the last div/image
	if ($FS_nextImage.attr('src') == undefined) {
		$FS_nextDiv = $('#FS_container div').last(0);
		$FS_nextImage = $FS_nextDiv.find('img').eq(0);
	}
	
	FS_Running = was_running;
	//Fade out current div, when done call FS_Fadein
	$currentDiv.fadeOut('fast', FS_Fadein);
}

/*function FS_DEBUG_CHECK() {
	$('#debuginput').value = FS_Running;
	setTimeout(FS_DEBUG_CHECK, 250);
}*/

$(document).ready(function() {
	FS_resume();
	$('#FS_leftArrow').click( function() {
		FS_previous();
	} );
	$('#FS_rightArrow').click( function() {
		FS_next();
	} );
	$('#FS_playpause').click( function() {
		$MyBtn = $('#FS_playpause');
		if (FS_Running) {
			FS_pause();
			$MyBtn.attr('src', '/images/Scroller/res/btn-play.png');
			$MyBtn.attr('alt', 'Click to resume slideshow');
			$MyBtn.attr('title', $MyBtn.attr('alt'));
		} else {
			FS_nextFadeDelay = 1000;
			FS_resume();
			$MyBtn.attr('src', '/images/Scroller/res/btn-pause.png');
			$MyBtn.attr('alt', 'Click to pause slideshow');
			$MyBtn.attr('title', $MyBtn.attr('alt'));
		}
	} );
	/*FS_DEBUG_CHECK();*/
});
