var carouselImageCount=0;
var carouselCurrentImage=0;
var carouselStarted=false;
var carouselInterval=7000;

$(function(){
	
	// get all available images
	carouselImageCount=$("#carousel .images li").length;
	
	// get active image
	carouselCurrentImage=1;
	
	// carousel started
	carouselStarted=true;
	
	// start carousel if any images, change images at every 2 seconds
	startCarousel(carouselInterval);
	
});

/**
 * Start/Execute images carousel
 * 
 * @param int interval Interval in ms at which images should be changed
 */
function startCarousel(interval) {

	// if no image or carousel stoped return
	if (carouselImageCount==0 || !carouselStarted)
		return;

	// initialize image navigation if not yet done and if more than one image
	if ($("#carousel .navigation li.active").length==0 && carouselImageCount>1) {
		$("#carousel .navigation li").remove();
		for (var i=1;i<=carouselImageCount;i++) {
			var html="<li"+(i==carouselCurrentImage?' class="active"':'')+"><a href='javascript:selectImage("+i+",true)'>"+i+"</a></li>";
			$("#carousel .navigation").append(html);
		}
	}
	
	// calculate next image index
	imageToSelect=carouselCurrentImage+1;
	if (imageToSelect>carouselImageCount)
		imageToSelect=1;
	
	// change visible image if needed
	window.setTimeout("selectImage("+imageToSelect+",false)",interval);
	
	
	// queue next call if needed
	if (carouselImageCount>1)
		window.setTimeout("startCarousel("+interval+")",interval);
}

/**
 * Changes currently displayed image in carousel
 * 
 * @param image Index of the image to be shown
 * @param stopCarousel Whenever carousel should be stoped
 */
function selectImage(image,stopCarousel) {
	
	// stop carousel if needed
	if (stopCarousel)
		carouselStarted=false;

	// exit if called from timer but already stopped
	if (!stopCarousel && !carouselStarted)
		return;
	
	// hide currently selected image
	$("#carousel .images li:eq("+(carouselCurrentImage-1)+")").removeClass("active").addClass("back");
	
	// reset navigation
	$("#carousel .navigation li").removeClass("active");
	
	// show Nth image
	$("#carousel .images li:eq("+(image-1)+")").hide().removeClass("back").addClass("active").fadeIn("slow",function(){
		$("#carousel .images li").removeClass("back");
	});
	
	// select Nth navigation
	$("#carousel .navigation li:eq("+(image-1)+")").addClass("active");
	
	// change currently selected image
	carouselCurrentImage=image;
}