/*
	Author: Rodrigo Munoz
	Customized Infinite Carousel based on http://jqueryfordesigners.com/jquery-infinite-carousel/
	Made some modifications (some are very bad due to me being lazy)
*/
(function(){
	$.fn.infiniteCarousel = function () {
		function repeat(str, n) {
			return new Array( n + 1 ).join(str);
		}
		return this.each(function () {
		var $wrapper = $('> .wrapper', this),
		    $slider = $wrapper.find('> ul').css('width','999em'), //slider ul needs to be super wide
			$items = $slider.find('> li'),
			$first = $items.filter(':first'),
			$last = $items.filter(':last'),
			$circles = $('.circles', this),
			singleWidth = $first.outerWidth(),
			currentPage = 1,
			pages = $items.length;
			
			//clone first li after last li, and clone last li to first li
			$items.filter(':last').after($first.clone().addClass('cloned'));
			$items.filter(':first').before($last.clone().addClass('cloned'));

			
			//update $items because now there are cloned items in the ul
			$items = $slider.find('> li');
			
			//initialize where the scroller should be
			$wrapper.scrollLeft(singleWidth);
			
			function gotoPage(page) {
				var dir = page < currentPage ? -1 : 1,
					n = Math.abs(currentPage - page),
					left = singleWidth * dir * n;
					
				$wrapper.filter(':not(:animated)').animate({
					scrollLeft : '+=' + left
				}, 500, function () {
					if (page > pages) {
						$wrapper.scrollLeft(singleWidth);
						page = 1;
					} else if (page == 0) {
						page = pages;
						$wrapper.scrollLeft(singleWidth * pages);
					}
					currentPage = page;
					if (currentPage == 1) {
						$circles.css('background-position', '0 0');
					} else if (currentPage == 2) {
						$circles.css('background-position', '0 -19px');
					} else if (currentPage == 3) {
						$circles.css('background-position', '0 -39px');
					}
				});	
				
			}
			
			// Arrow links
			$('.back').click(function(){gotoPage(currentPage - 1)});
			$('.forward').click(function(){gotoPage(currentPage + 1)});
			
			// Circles
			$circles.find('.page1').click(function(){gotoPage(1);return false;});
			$circles.find('.page2').click(function(){gotoPage(2);return false;});
			$circles.find('.page3').click(function(){gotoPage(3);return false;});
			
			// Automate it
			$(this).bind('goto', function(event, page){
				gotoPage(page);
			});
			
			$(this).bind('next', function(event, page){
				gotoPage(currentPage + 1);
			});
			
		});		
	};
})(jQuery);

$(document).ready(function () {
	var autoscrolling = true;
	
	$('.infiniteCarousel').infiniteCarousel().mouseover(function (){
		autoscrolling = false;
	}).mouseout(function (){
		autoscrolling = true;
	});
	
	setInterval(function() {
		if (autoscrolling){
			$('.infiniteCarousel').trigger('next');
		}
		
	}, 8000)
	
});












