/*! Carousel v1 <http://nvinteractive.co.nz>
	Copyright (c) NV Interactive
	
	References:
		jquery-1.2.6.js
		
	Release Notes:

	Usage:
		Carousel list items must be a fixed width.
		
*/

var NV_IE_png;

nv_carousel = function(){
	
	var SPEED = 750;
	var AUTO_SPEED = 5000;
	
	var init = function(){
		$(".carousel").each(setupCarousel);
	}
	
	var setupCarousel = function(){
		
		//Check that we have enough items
		var li = $("li", this);
		if(li.length <= 1)return;	

		$(this).append('<div class="tools"><div class="prev"></div><div class="next"></div></div>').addClass("carousel_enabled");
		
		if(NV_IE_png){
			$(".tools div", this).each(	NV_IE_png.processCssBackground );
		}
		
		$("li:first", this).addClass("active");
		$(".next", this)
			.bind("click", {carousel: this}, stopAuto)
			.bind("click", {carousel: this, direction: 1}, navigate);
		
		$(".prev", this)
			.bind("click", {carousel: this}, stopAuto)
			.bind("click", {carousel: this, direction: -1}, navigate);
		
		startAuto(this);
	}
	
	var navigate = function(evt){
		
		var carousel = evt.data.carousel;
		
		//Abort if already animating
		if($("ul:animated", carousel).length > 0)return;
		
		var ul = $("ul", carousel);
		var x = ul.position().top;
		var active = $(".active", carousel);
		
		if(evt.data.direction == 1){
			var target = active.next();
			var callback = updateAfterNext;
		}else{

			$("li:last", ul).prependTo(ul);
			ul.css("top", 0 - $(".active", ul).position().top);
			var callback = updateAfterPrev;
			var target = active.prev();
		}
		
		if(target.length==0)return;
		var targety = 0 - target.position().top;		

		ul.animate({top: targety}, SPEED, callback);
		
		target.addClass("active");
		active.removeClass("active");
		
		//Autorun				
		if( $(carousel).data("auto") ){
			$(carousel).animate({"top": "0"}, AUTO_SPEED, auto);
		}		
		
	}
	
	var updateAfterNext = function(){
		var ul = $(this);
		$("li:first", ul).appendTo(ul);
		ul.css("top", 0 - $(".active", ul).position().top);
	}
	
	var updateAfterPrev = function(){
	}
	
	
	var auto = function(){
		navigate( {data: {carousel: this, direction: 1}} );
	}	
	
	var startAuto = function(carousel){
		$(carousel).data("auto", true);
		$(carousel).animate({"top": "0"}, AUTO_SPEED, auto);
		//navigate( {data: {carousel: carousel, direction: 1}} );
	}
	
	var stopAuto = function(evt){
		$(evt.data.carousel).stop().data("auto", false);
	}	
	
	return {
	/* Public API
	*/
	init: init
	}
		
}();

$(document).ready(nv_carousel.init);

