/**********************************************
	Carousel Script
		
	Written by: 
		Adam Quaile, adamquaile@gmail.com
		www.62degrees.co.uk

**********************************************/

// Give a list of images carousel functionality. 
// 
// Takes two css selectors, the first for the container 
// element wrapping the list
// ... and the second for the container which holds the controls.
// and a callback called on completion which must take the form
// function(index) {} which is passed as it's only parameter 
// the index of the current image.
function carousel(container_selector, controls_selector, completed_callback) {
	
	// Return the desired left: position of the ith image in set
	// with i starting from 0
	function pos(i) {
		
		// Max images goes to n, not n-1. ie not zero based
		max = max_images(container_selector);
		width = $(container_selector).width();
		
		if (i >= max) {
			return pos(i-max);
		} else if (i < 0) {
			return pos(max - 1);
		}
		
		return (-1 * i * width);
	}
	
	// Return the zero-based index of current image
	// being displayed in carousel
	function index(container_selector) {
		var left	= 	$(container_selector + ' .carousel').css('left');
		var length	=	left.length;
		var x_pos	= 	$(container_selector + ' .carousel').css('left').substring(0, length-2);
		var width	= 	$(container_selector).width();
		
		return (-1 * Math.floor(x_pos / width));
	}
	
	// Get the maximum number of images in set
	function max_images(container_selector) {
		max = $(container_selector + ' .carousel').width();
		width = $(container_selector).width();
		return (max / width);
	}
	
	// Scroll the container to a specified position in
	// x axis.
	// 
	// @param x pixels in x-axis to scroll to
	function scroll(x) {
		
		// Simple animation to scroll the left position
    	$(container_selector + ' .carousel').animate({
    											left: (x)+'px'
    										}, 
									    	{
									    		duration: 'slow', 
									    		complete: function() {
    														completed_callback(index(container_selector));
															}
											}
		)
		
	}
	
	// Handle the previous buttons
	$(controls_selector + ' .prev').click(function() {
		
		// Generate the new position...
		new_pos = pos(index(container_selector)-1);
		// ... and go there
		scroll(new_pos);
		
	})
	// Handle the next buttons
	$(controls_selector + ' .next').click(function() {
		
		// Generate the new position...
		new_pos = pos(index(container_selector)+1);
		// ... and go there
		scroll(new_pos);
		
	})
}


	

