/* Author:
2011.09.25 Cl�udio Medina

*/
jQuery(function ($) {
	/* You can safely use $ in this code block to reference jQuery */
	$(document).ready(function(){
		
		$('.carousel').each(function(){
			$('ul', this).addClass('items');
			var $car = $(this),
				$itemsList = $('.items', $car),
				$items = $('li', $itemsList),
				$linksList = $('<ul class="links" />'),
				count = 1;
			$car.append($linksList);
			$items.each(function(){
				var $item = $(this),
					$link = $('<li class="link"><a href="#">'+(count++)+'</a></li>');
				$linksList.append($link);
				$link.click(function(){
					clearTimeout(window.timer);
					$items.hide().removeClass('active');
					$item.show().addClass('active');
					/*
					var nx = $item.position().left;
					$itemsList.stop().animate({left:-nx}, 'slow');
					*/
					$(this).addClass('active').siblings('li').removeClass('active');
					startSlideshow();
				})
			});
			var $links = $('li.link', $linksList);
			
			$links.first().click();
			$previousLink = $('<li class="previous"><a href="#">&lt;</a></li>');
			$nextLink = $('<li class="next"><a href="#">&gt;</a></li>');
			$nextLink.click(function(){
				var $active = $links.filter('.active'),
					$next = $active.next('.link').length ? $active.next('.link') : $links.first();
				$next.click();
			});
			$previousLink.click(function(){
				var $active = $links.filter('.active'),
					$next = $active.prev('.link').length ? $active.prev('.link') : $links.last();
				$next.click();
			});
			$linksList.prepend($previousLink);
			$linksList.append($nextLink);
			function startSlideshow(){
				clearTimeout(window.timer);
				window.timer = setTimeout(function(){
					/*var $active = $links.filter('.active'),
						$next = $active.next().length ? $active.next() : $links.first();
					*/
					$nextLink.click();
				}, 8000)
			}
			startSlideshow();
		});
		
		
		
		
	})
	
});
