/*

	Slide show
	Written by S Tomlinson @ Winona
	11/02/2008

*/


var current = 1;
var totalSlides = 0;
var timer = "";

$(document).ready(function(){
	
	slideShow();
	
	// Bind click to the animation
	$("#animate").click(function(){
	
		animateit("#slide0","#slide1");
		return false;
	
	});
	
	//timer = setInterval('animateit()',8000);

});

function slideShow() {
	
	$("#slideshow ul li:first").addClass("active");

	// Set up the globals
	totalSlides = $("#slideshow ul > li").length;

	// Add the elements to the DOM we need	
	$("#slideshow").append('<div id="overlay"></div>');
	$("#slideshow").append('<div id="pager"></div>');

	// Populate the pager
	for(i = 1; i <= totalSlides; i++) {
		var pagerlink = $('<a href="#">' + i + '</a>');
		pagerlink.bind('click',function(e){
			changeSlide($(e.target).text());
			return false;
		});
		$("#pager").append(pagerlink);
	}
	
	// Set the timer to auo roate through the slides
	timer = setInterval('rotateSlide()',10000);
	
}

function rotateSlide() {

	if (current < totalSlides) {
	
		changeSlide(current + 1);
	
	} else {
	
		changeSlide(1);
	
	}

};

function changeSlide(slide) {
	// Stop the timer
	clearInterval(timer);

	currentSlide = $("#slideshow .active");
	nextSlide = $('#slideshow ul > li:nth-child(' + slide + ')');

	if (slide > 0 && slide <= totalSlides) {
	
		//console.log(currentSlide,nextSlide);
		animateit(currentSlide, nextSlide);
	
	}
	
	$('#pager .current').removeClass("current");
	$('#pager > a:nth-child('+ slide +')').addClass("current");
	current = slide;
	
	// Restart the timer
	timer = setInterval('rotateSlide()',10000);
}


function animateit(currentSlide,nextSlide) {

	var o = $("#overlay");

	// Reset the styles on the overlay and text
	o.css({
		top: -322,
		opacity: 1
	});
	$("#pager").css("right",-100);
		
	// Stop any currently running animation
	o.stop();

	// Animate the overlay to cover the image
	o.animate({ 
		top: 0
	}, 300, false,function(){
	
		// Hide the caption
		$(".blurb").hide();
		$(".background").css({
			top: 322,
			opacity: 1
		});
	
		// Change slide
		$(currentSlide).hide().removeClass("active");
		$(nextSlide).show().addClass("active");
	
		// Animate the overlay to below the viewable area
		o.animate({
			top: 322
		}, 200, false, function(){
		
			// Bring the overlay back up to around half way
			$(".background").animate({ 
				top: 0,
				opacity: 0.8
			}, 500, false, function(){
			
				// Show the text
				$(".blurb").fadeIn("fast");
				
				// Slide in the pager
				$("#pager").animate({
					right: 10
				},100);
			
			});

		});
	

	});


}
