var duration = 7000;
var imgs = new Array();
var current_img = 0;
var next_img = 1;
var timer = null;
var timer_change = null;
var is_ready = true;
var autorotate = 0;

function initCaroussel(){
    var i = 0;
    $(".full").each(function(){
        $(this).attr("id", "Selected" + i);
        imgs[i] = 'Selected'+i;
        i++;
    });
    i = 0;
    $(".teaser a").each(function(){
        var nb = i; 
        //$(this).click(function(){initLinks(nb)});
        $(this).hover(function(){initLinks(nb)});
        i++;
    });
	if(autorotate && imgs.length > 1) initTimers();
}

function initLinks(nb){
    var clickedTeaser = $(".teaser:eq(" + nb + ")");
    $(".teaser").each(function(){
        if(clickedTeaser.attr("class") != $(this).attr("class")){
            $(this).removeClass("on");
        }
    }); 
    clickedTeaser.addClass("on");
    fadeThis(nb);
}

function fadeThis(i){
	if(is_ready && current_img != i){
		is_ready = false;
		next_img = i;
		 clearTimeout(timer);
		timer_change = self.setTimeout("makeItReady()", 120);
		fadeInOut();
	}
}

function makeItReady(){
	is_ready = true;
	clearTimeout(timer_change);
}

function initTimers(){
	timer = self.setTimeout("fadeInOut()",duration);
	timer_change = null;
}

function fadeInOut(){
    $("#" + imgs[current_img]).fadeOut("slow");
	$("#" + imgs[next_img]).fadeIn("slow");
    if(next_img == (imgs.length - 1)){
	    current_img = next_img;
	    next_img = 0;
    }
    else{
	    current_img = next_img;
	    next_img++;
    }
    if(autorotate) initTimers();
}

$(document).ready(function(){
    initCaroussel();
});