jQuery(document).ready(function($) {

	if ($("#admin-header").length == 0) {
		$("div.carousel").addClass('carousel-loaded');
	}

	$(".carousel-loaded li.first > a").append("<span>Click for more details</span>");

	$(".carousel-loaded a").click(function() {
		if ($(".carousel-loaded").data("intervalId") != null) {
			window.clearInterval($(".carousel-loaded").data("intervalId"));
		}

		if (!$(this).parents("li").hasClass("first")) {
			switchCarouselItem(this);
			return false;
		}
	});
	
	$(".carousel-loaded").each(function() {
		var carousel = $(this);
		var intervalId = window.setInterval(function() {
			var current = parseInt(carousel.data('current'), 10);
			
			if (current == 4) {
				current = 0;
			}
			else {
				current ++;
			}
			carousel.data('current', current);
			
			switchCarouselItem(carousel.find("li:eq(" + current + ") a"));
		}, 5000);

		carousel.data('current', 0);
		carousel.data('intervalId', intervalId);
	});
});

function switchCarouselItem(item) {
	jQuery(".carousel .first a span").remove();
	jQuery(".carousel .first").removeClass('first');
	
	var selected = jQuery(item).parents("li");
	selected.addClass("first").hide();
	selected.find("> a").append("<span>Click for more details</span>");
	selected.fadeIn("slow");
	jQuery(".carousel .last").removeClass('last');
	jQuery(".carousel li:last-child").addClass('last');
}
