var currentTab=0;
var isPlaying=true;
var delay=5000; // in ms
var timer1, tabCount;

/* Change the currently displayed tout */
function change(tabNum) {
	currentTab = tabNum;
	$("#carousel").find(".crslItem").hide().eq(tabNum).show();
	$("#bottomTabs .tab").removeClass("active").eq(tabNum).addClass("active");
}

/* change picture, wait some seconds, repeat */
function doRotation() {
	currentTab = (currentTab+1) % tabCount;
	change(currentTab);
	timer1 = setTimeout('doRotation()', delay);
}

/* executed when the play/pause button is selected */
function togglePlay() {
	isPlaying = !isPlaying;
	$("#carPausePlay").attr("class", isPlaying?"carouselPause":"carouselPlay"); /*carousel controls*/
	if (isPlaying) {
		doRotation(); /* restart the image loop */
	} else {
		clearTimeout(timer1); /* stop the image loop */
	}
}

/*executed when a tab is clicked */
function goToTab(tabNum) {
	isPlaying = false;
	$("#carPausePlay").attr("class", "carouselPlay"); /*carousel controls*/
	clearTimeout(timer1);
	change(tabNum);
}

function initCarousel() {
	tabCount = $(".crslItem").length;

	/* add structure for controllers */
	$("#carControlsWrapper").html('<div id="carControls"><a id="carPrev"></a><a id="carPausePlay" class="carouselPause"></a><a id="carNext"></a></div>');

	/* bind controllers with onclick functions */
	$("#carPrev").click(function(){
		goToTab((currentTab + tabCount - 1) % tabCount);
		return false;
	});
	$("#carPausePlay").click(function(){
		togglePlay();
		return false;
	});
	$("#carNext").click(function(){
		goToTab((currentTab + 1) % tabCount);
		return false;
	});

	/* add structure for bottom tabs */
	$(".crslItem").each(function(i) {
		$("#bottomTabs").append('<div class="tab"><a href="#">' + $(this).find(".tabTitle").text() + '</a></div>');
	});
	$("#bottomTabs").append('<div class="clear"></div>').find(".tab:eq(0)").addClass("active");
	$("#bottomTabs").find(".tab").click(function(){
		var position = $(this).prevAll(".tab").length;
		goToTab(position);
		return false;
	});

	/* hide crslItems after first and set up images for them */
	$(".crslItem:gt(0)").each(function(i) {
		$(this).hide();
		var imgHref = $(this).find(".crslItemHead a").attr("href");
		var imgSrc = $(this).find(".crslItemImg a").attr("href");
		var imgAlt = $(this).find(".crslItemImg em").text();
		$(this).find(".crslItemImg").html('<a href="' + imgHref + '"><img src="' + imgSrc + '" alt="' + imgAlt + '" /></a>');
	});

	/* wait until images are loaded then start rotation */
	$(".crslItem:last .crslItemImg img").load(function(){
		timer1 = setTimeout('doRotation()', delay);
	});
}

function waitUntilCarouselReady() {
	if ($("div#bottomTabs").length) {
		initCarousel();
	}
	else {
		setTimeout('waitUntilCarouselReady()', 100);
	}
}
waitUntilCarouselReady();

