// Declare global variables.
var interval = 10000;
var fadeTime = 1500;
var randomPick = false;
var stopOnHover = false;

var $siblings;

// The image switch function.
function slideSwitch() {
	var $next;
	// Get the active slide.
	var $active = $('#slideshow div.active');

	// If none is found, take the last one.
	if ($active.length == 0) $active = $('#slideshow div:last');

	// Choose the next slide based on random or not.
	if (randomPick) {
		var rndNum = Math.floor(Math.random() * $siblings.length);
		$next = $($siblings[rndNum]);
		if ($next == $active) { 
			$next = $active.next().length ? $active.next() : $('#slideshow div:first');
		}
	}
	else {
		$next = $active.next().length ? $active.next() : $('#slideshow div:first');
	}
	// Change the active slide to fade out.
	$active.addClass('last-active')
			.animate({ opacity: 0.0 }, fadeTime);
	// Change the next slide to fade in.
	$next.css({ opacity: 0.0 })
			.addClass('active')
			.animate({ opacity: 1.0 }, fadeTime, function() {
				$active.removeClass('active last-active');
			});
}

$(document).ready(function() {
	// Cache all image divs if we randomize.
	if (randomPick) $siblings = $('#slideshow div');

	// And schedule the rotation.
	var playSlideshow = setInterval("slideSwitch()", interval);

	if (stopOnHover)
	{
		$('#slideshowImages').hover(function() {
			// Stop sliding when the user hovers over the slides.
			clearInterval(playSlideshow);
		},
		function() {
			// Start sliding again when the user leaves the slides.
			playSlideshow = setInterval("slideSwitch()", interval);
		});
	}
});
