$(function () {
	var carousel = new Carousel();
	carousel.init();
});

var Carousel = function () {
	var TIME = 5000;
	
	var activeId = 1;
	var activeThumbnailMarker = $("<div></div>");
	var numberOfImages = $(".carousel li").length;
	var timer;
	
	this.init = function () {
		addIds();
		addLinks();
		addActiveThumbnailMarker()
		
		startTimer();
	}
	
	function addIds() {
		var carouselImageId = 1;
		$(".carousel > div").each(function () {
			$(this).attr("id", "carousel-image-" + carouselImageId);
			carouselImageId += 1;
		});
		
		var carouselThumbnailId = 1;
		$(".carousel li").each(function () {
			$(this).attr("id", "carousel-thumbnail-" + carouselThumbnailId);
			carouselThumbnailId += 1;
		});
	}
	
	function addLinks() {
		var link = $('<a href="#"></a>');
		link.click(function (event) {
			stopTimer();
			activeId = parseInt($(this).closest("li").attr("id").replace("carousel-thumbnail-", ""));
			update();
			event.preventDefault();
		});
		
		$(".carousel li").wrapInner(link);
	}
	
	function addActiveThumbnailMarker() {
		$("#carousel-thumbnail-" + activeId).append(activeThumbnailMarker);
	}
	
	function startTimer() {
		timer = setTimeout(function () { updateActiveId(); update(); }, TIME);
	}
	
	function stopTimer() {
		clearTimeout(timer);
	}
	
	function updateActiveId () {
		if (activeId == numberOfImages) {
			activeId = 1;
		} else {
			activeId += 1;
		}		
	}
	
	function update() {
		updateImage();
		updateThumbnails();
		startTimer();
	}
	
	function updateImage() {
		$(".carousel > .active").removeClass("active");
		$("#carousel-image-" + activeId).addClass("active");
	}
	
	function updateThumbnails() {
		$("#carousel-thumbnail-" + activeId).append($(".carousel ul div").remove());
	}
};
