/*! NV Carousel v2 <http://nvinteractive.co.nz>
	Copyright (c) NV Interactive
	
	References:
		jquery-1.3.x.js
		
	Release Notes:
		2.0 rewrote as a jquery plugin
*/


//
// create closure
//
(function($) {

    //
    // plugin definition
    //
    $.fn.nvcarousel = function(options) {
        debug("selection count: " + this.length);
        // build main options before element iteration
        var opts = $.extend({}, $.fn.nvcarousel.defaults, options);

        // iterate and reformat each matched element
        return this.each(function() { processcarousel(this, opts) });
    };

    //
    // private function for debugging
    //
    function debug(msg) {
        if (window.console && window.console.log)
            window.console.log('nvcarousel ' + msg);
    };

    //
    // define and expose our format function
    //
    processcarousel = function(element, opts) {
		
        $this = $(element);
		
        // build element specific options
        var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;
		
		var $ul = $("ul", $this);
		var isHorizontal = o.direction.indexOf("vert") != 0;
		$ul.data("isHorizontal", isHorizontal);
		
		var $li = $("li", $this);
		
		debug("this.width = " + $this.width() + " list.width = " + $li.length * $li.width() );
		
		if(isHorizontal && ( $li.length * $li.width() <= $this.width() ) || !isHorizontal && ( $li.length * $li.height() <= $this.height() ) )return;
		
		if(isHorizontal){
			$li.css({float: "left", display: "inline"});
			$ul.width( $this.width() + (2 * $li.width()) );
		}
			
		/*var $container = $( document.createElement("div") );
		$container.css({
					   width: $ul.width(),
					   height: $ul.height(),
					   overflow: "hidden",
					   position: "relative"
					   });

		$ul.wrap($container);*/
				
		//Randomise
		if(o.randomise)
			$( $("li", this).each( function(){ this.order = Math.random(); }  ).get().sort( carouselSort ) ).appendTo( $ul );

		
		//$ul.width(w + $li.width()).css("position", "absolute");
		
		$this.append('<div class="prev png"></div><div class="next png"></div>');
		
		$("li:first", $this).addClass("active");
		$(".next", $this).bind("click", {carousel: $this, direction: 1, opts: o}, navigate);
		$(".prev", $this).bind("click", {carousel: $this, direction: -1, opts: o}, navigate);
		
		if(o.autostart)
			startAuto($this, o);
        

    };


    //
    // Tools
    //
	var carouselSort = function(a, b)
	{
	   var first = a.order;
	   var second = b.order;
	   
	   if (first == second)
		  return 0;
	   if (first < second)
		  return -1;
	   else
		  return 1; 
	}

	
	var startAuto = function(e, o){		
		var i = setInterval(function(){ auto(e, o) }, o.autodelay);
		$(e).data("carousel-interval", i);	
	}
	
	var auto = function(e, o){
		navigate( {data: {carousel: e, direction: 1, auto: true, opts: o}} );
	}
	
	var navigate = function(evt){
		
				
		var $carousel = evt.data.carousel;

		if(!evt.data.auto){
			clearInterval( $carousel.data("carousel-interval") );
			clearTimeout( $carousel.data("carousel-timeout") );
			
			if(evt.data.opts.autorestart){
				var i = setTimeout(function(){ startAuto($carousel, evt.data.opts) }, evt.data.opts.autorestartdelay);
				$carousel.data("carousel-timeout", i);
			}
		}

		//Abort if already animating
		if($("ul:animated", $carousel).length > 0)return;
		
		var $ul = $("ul", $carousel);
		var isHorizontal = evt.data.opts.direction.indexOf("vert") != 0;
		$ul.data("isHorizontal", isHorizontal);
		var pos = isHorizontal ? $ul.position().left : $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);
			
			if(isHorizontal)
				$ul.css("left", 0 - $(".active", $ul).position().left);
			else
				$ul.css("top", 0 - $(".active", $ul).position().top);
			
			var callback = updateAfterPrev;
			var target = active.prev();
		}
		
		if(target.length==0)return;
		
		var targetPos = isHorizontal ? 0 - target.position().left : 0 - target.position().top;

		if(isHorizontal)
			$ul.animate({left: targetPos}, evt.data.opts.speed, callback);
		else
			$ul.animate({top: targetPos}, evt.data.opts.speed, callback);		
		
		target.addClass("active");
		active.removeClass("active");
		
	}
	
	var updateAfterNext = function(){
		var $ul = $(this);
		
		$("li:first", $ul).appendTo($ul);
		
		if( $ul.data("isHorizontal") )
			$ul.css("left", 0 - $(".active", $ul).position().left);
		else
			$ul.css("top", 0 - $(".active", $ul).position().top);

	}
	
	var updateAfterPrev = function(){
	}	    


    //
    // plugin defaults
    //
    $.fn.nvcarousel.defaults = {
		
		speed: 500,
		autodelay: 5000,
		autostart: false,
		autorestart: false,
		autorestartdelay: 5000,
		randomise: true,
		direction: "horizontal"

    };
    //
    // end of closure
    //
})(jQuery);