if (typeof($c) == 'undefined') $c = {};

$c.slideShow = 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
		$('#ssNav li.active').removeClass('active');
		// animate the transition
		$(current).fadeOut(550, function(){
			$(current).removeClass('active');
			$(next).fadeIn(550, function(){
				$(next).addClass('active');
				// set the naviation
				changeNav(byUser ? index : index + 1);
			})
		});
	}
	// Start the rotation
	function play(){
		timer = window.setInterval(showNext, 6000);
		$(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;
		$('#ssNav li:eq(' + index +')').addClass('active');
		
	}
	// Preload the images
	function preload(){
		 var img = new Image();
		 
		 for(var i = 0; i<6; i++){
			 img.src = '/images/slide-show/lb' + i + '.jpg'; 
		 }
	}
	// Jump to the slides target
	function jumpTo(slide){
		// Clear old cookie
		$c.clearCookie('cawScrollTo');
		var target = $(slide).find('a')[0];
		// Break the the link into the URL and the id
		var places = $(target).attr('href').split('#');
		var link = places[0];
		// set the id to a cookie
		$c.createCookie('cawScrollTo', '#'+places[1])
		// go to the link so the scroller can do it's thing
		window.location = link;		
	}
	// Start it up
	function init(){
		preload();
		play();
		
		// Individual navs
		$('#ssNav li').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 = $('#ssNav li').index(this);
				showNext($('#slides li')[index], index);
			} 
		});
		
		// Pause/Play Button if one exists
		$('#control').click(function(){
			if($(this).hasClass('paused')){
				showNext();
				play();
			} else {
				pause();
			}
		});

		// For jumping from the slide to he page
		$('#slides>li').live('click', function(){
			jumpTo(this);
		});
	}
	return function(){
		init();
	}
}();

$(document).ready(function(){
	$c.slideShow();
});

