var duration = 4500;
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 = true;
var teasers = [];

function initCaroussel(){
    $(".full").each(function(eq){
        $(this).attr("id", "Selected" + eq);
        imgs[eq] = 'Selected'+eq;
    });
    teasers = $(".teaser");
    teasers.find("a:not(.not-trigger), .trigger").each(function (eq) {
        if ($(this).get(0).tagName.toLowerCase() == "div") {
            $(this).click(function () {
                window.location.href = $(this).find('a:eq(0)').attr('href');
            });
        }
        $(this).hover(function () { initLinks(eq) });
    });
    if ($('#Accueil').length > 0) {
        var bullets = $('#ActuBullets').find('a');
        bullets.each(function (eq) {
            $(this).click(function () {
                bullets.removeClass('on');
                $(this).addClass('on');
                $('#Actu').children('div').fadeOut().eq(eq).fadeIn();
            });
        });
    }
	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");
    teasers.eq(current_img).removeClass('on');
    teasers.eq(next_img).addClass('on');
    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();
});
