var nbSlides = 0;
var slideWidth = 268;
var currentSlide = 1;
var time = 4000;
var timer;
var sliding = false;

var $j = jQuery.noConflict();

$j(document).ready(function(){
	nbSlides = $j(".slide").length;
	
	//set the width of the #slidesContainer relatively to
	//the number of slides
	$j(".slideshow #slidesContainer").css("width", nbSlides*slideWidth+"px");
	
	//buttons behaviors
	setBtnAction("left");
	setBtnAction("right");
	
	//deactivate the apropriate button if the current
	//slide is min or max
	activateBtn();
	
	//autoplay
	timer = setTimeout("slide('right')", time); 
	
	//deactivate autoplay when slideshow is hovered
	$j(".slideshow").hover(
		function(){
			clearTimeout(timer);		
		},
		
		function(){
			clearTimeout(timer);
			timer = setTimeout("slide()", time); 
		}
	)	   
});



function slide(action){
	if (action == undefined) 
		action = "right";
	
	if (!sliding) {
		sliding = true;
		var operation = (action == "right") ? 1 : -1;
		clearTimeout(timer);
		timer = setTimeout("slide('right')", time);
		var prevSlide = currentSlide;
		currentSlide = (currentSlide >= nbSlides) ? 1 : currentSlide + operation;
		currentSlide = (action == "left" && currentSlide == 1) ? prevSlide - 1 : currentSlide;
		var distance = (currentSlide - 1) * -slideWidth;
		
		
		//if it's not the last slide
		if (distance != 0 || action == "left") {
			//opacity
			$j(".slideshow #slidesContainer").animate({"opacity" : 0.3}, 150, function(){
				$j(".slideshow #slidesContainer").animate({"opacity" : 1}, 350, function(){sliding = false;});
			});
			
			//translation
			$j(".slideshow #slidesContainer").animate({"margin-left" : distance+"px"}, 500, function(){sliding = false;});
		
		//else, go back to the first slide
		}else {
			//opacity
			$j(".slideshow #slidesContainer").stop().animate({"opacity" : 0}, 150, function(){
				$j(".slideshow #slidesContainer").css("margin-left", "0px");
				$j(".slideshow #slidesContainer").animate({"opacity" : 1}, 350, function(){
					sliding = false;
				});
			});
		}

			
		
		//activate the apropriate button
		activateBtn();
	}else {
		clearTimeout(timer);
		timer = setTimeout("slide('right')", time);
	}
}


//deactivate the apropriate button if the current
//slide is min or max, otherwise activate it
function activateBtn() {
	if (currentSlide == 1) {
		$j(".slideshow .left").unbind("click");
		$j(".slideshow .left").addClass("inactive");
	}else {
		setBtnAction("left");
		$j(".slideshow .left").removeClass("inactive");
	}
	
	if (currentSlide == nbSlides) {
		$j(".slideshow .right").unbind("click");
		$j(".slideshow .right").addClass("inactive");
	}else {
		setBtnAction("right");
		$j(".slideshow .right").removeClass("inactive");
	}
}

function setBtnAction(btn) {
	$j(".slideshow ."+btn).click(function(){		
		slide(btn);
	});
}



