/**
 * @author rdesisto
 * @created April 2010
 * @usage Currently set up for one per page, it's a revolving slide show with simple "you are here"
 * indicator.
 */

if (typeof($p) == 'undefined') $p = {};

$p.goRound = function() {
	
	// Variables
	var size = $('#slides li').size();
	var controller = document.getElementById('control');
	var timer = '';
	
	// Show the next slide (either in order or by user choice)
	function showNext(target, index){
		var next;
		// Find where we are
		var current = $('#slides li.active');
		var byUser = typeof(target) == 'object';
		// we didn't actually pass a target
		if(!byUser){
			// To pass to the navigation
			var index = $('#slides li').index(current);
			// Find the next one
			next = $(current).next('#slides li');
			// If there are no more start over
			if(next.length == 0){
				next = $('#slides li')[0];
			}
		} else {
			next = target;
		}
		// clear current from navigation
		$('#grNav span.active').removeClass('active');
		// animate the transition
		$(current).fadeOut(500, function(){
			$(current).removeClass('active');
			$(next).fadeIn(500, function(){
				$(next).addClass('active');
				// set the naviation
				changeNav(byUser ? index : index + 1);
			})
		});
	}
	// Start the rotation
	function play(){
		timer = window.setInterval(showNext, 5000);
		$(controller).removeClass('paused');
	}
	// Stop the rotation
	function pause(){
		window.clearInterval(timer)
		$(controller).addClass('paused');
	}
	// Keep the nav buttons up to date
	function changeNav(index){
		if(index == (size)) index = 0;
		$('#grNav span:eq(' + index +')').addClass('active');
		
	}
	// Start it up
	function init(){
		play();
		
		// Individual navs
		$('span.slideNav').click(function(){
			// Stop the show
			pause();
			// if it's not the currently active one, we get deep
			if(!$(this).hasClass('active')) {
				// find which number they're trying to navigate to
				var index = $('span.slideNav').index(this);
				showNext($('#slides li')[index], index);
			} 
		});
		
		// Pause/Play Button
		$('#control').click(function(){
			if($(this).hasClass('paused')){
				showNext();
				play();
			} else {
				pause();
			}
		});
	}
	return function(){
		init();
	}
}();

$(document).ready(function(){
	$p.goRound();
});
