
// GLOBAL VARS
var carouselItems = Array();	// List of carousel .item s
var curCarouselItem;			// Current position in carouselItems

(function($){

	$.fn.carousel = function(options) {

		// Override default options
		if (options) { $.extend($.fn.carousel.defaults, options); }

		// Bind the event listeners
		$.fn.carousel.bindEventListeners();
		
		// Build the list of slides
		$.fn.carousel.indexSlides();
		
		// Return valid jQuery object
		return this;

	};


	$.fn.carousel.bindEventListeners = function() {
	// Bind all the event listeners to the button classes	
		
		$('.nextbutton').live('click', function () {
			//console.log("hi");
			$.fn.carousel.nextSlide();
			return false;
		});

		$('.seek_button').live('click', function () {
			
			// Translate href to div id
			var target = $(this).attr('href');
			target = $(target);
			
			// Animate to it
			$.fn.carousel.displaySlide($(target));
			
			// // Disable default link behaviour
			return false;
		});



		$('.backbutton').click(function () {
			$("#scroll_wrapper").animate({
				left: '-=' + $("#scroll_wrapper").css('left') 				
			}, speed);

			return false;
		});

		$('.backbutton').hover(function () { 
			$(this).addClass('active');
		},
		function () { 
			$(this).removeClass('active');
		}
		);
	};
	
	
	$.fn.carousel.indexSlides = function() {
	// Collect all .items and put them in global vars for reference
	
		$("#carousel .item").each(function(i,v) {
			window.carouselItems.push(v);
		});
		window.curCarouselItem = 0;
		
	}

	
	$.fn.carousel.displaySlide = function(target) {
	// Load up a specific slide
	
		var position = target.position();
		var offset = position.left;
		var speed = $.fn.carousel.defaults['speed'];
		var speed_actual = (offset / parseInt(target.css("width"))) * speed;
		
		//console.log("moving #scroll_wrapper to " + target.attr("id") + " at " + offset + ", at a speed of " + speed_actual + "px/ms");
		
		$("#scroll_wrapper").animate({ left: '-=' + offset }, speed_actual, 'easeOutQuad');
		
	};
	
	$.fn.carousel.nextSlide = function() {
	// Load up the next slide, by passing the next 
	// available target to displaySlide()
	
		//console.log("Trying to get next slide");
	
		// Set new index depending on position
		if ((window.curCarouselItem - 1) == window.carouselItems.length) {
			window.curCarouselItem = 0;
		} else {
			window.curCarouselItem++;
		}
		
		// Pass new target to displaySlide
		var newSlide = window.carouselItems[window.curCarouselItem];
		$.fn.carousel.displaySlide(newSlide);
		
	}
	
	
	$.fn.carousel.prevSlide = function() {
	// Load up the previous slide, by passing the last
	// available target to displaySlide()
	
			
	}
	
	
	$.fn.carousel.defaults = {
	      'speed'    : '600',
	      'div_id' 	 : 'carousel'
	};



})( jQuery );
