/**
 * darmaSlideshow plugin
 *
 * Copyright (c) 2009 Armelle Coquart (darma.fr)
 *
 */
 
(function($) {
	$.fn.darmaSlideshow = function(options) {
		
	var defaults = {			
		slideshow: 'darmaslideshow',
		timer: 5000 //vitesse du slide
	};
	
	this.each(function() {
		
		var obj = $(this);
		var o = $.extend(defaults, options);
		var currentPos = 0;
		var maxPos = $('#' + o.slideshow + '-list li').size() - 1;
		var current_image_indice = 1;
		var moving = false;
		var clock = null;

		$('.' + o.slideshow + '-page, .' + o.slideshow + '-page-selected').click(function(){
			clearInterval(clock);		
		    var a = $(this).attr('id').split('-');
			var id = a[a.length-1];
			currentPos = id;
			move();
		});
		$('#' + o.slideshow).click(function(){
			clearInterval(clock);		
			currentPos++;
			if(currentPos > maxPos) currentPos = 0;
			move();
		});		
		
		function move(){
		    if(moving) return;		
			moving = true;
			$('.' + o.slideshow + '-page, .' + o.slideshow + '-page-selected').attr('class', o.slideshow + '-page');
			$('#' + o.slideshow + '-page-' + currentPos).attr('class', o.slideshow + '-page-selected');		
		    var content = $('#' + o.slideshow + '-list li').eq(currentPos).html();	
		    var title = $('#' + o.slideshow + '-list li img').eq(currentPos).attr('title');					
			$('#' + o.slideshow + '-legend').text(title);									
			var next_image_indice = 3 - current_image_indice;		
			$('#' + o.slideshow + '-img' + next_image_indice).css('z-index', 10);						
			$('#' + o.slideshow + '-img' + current_image_indice).css('z-index', 11);
			$('#' + o.slideshow + '-img' + next_image_indice).html(content);
			$('#' + o.slideshow + '-img' + next_image_indice).css('display', 'block');	
			$('#' + o.slideshow + '-img' + current_image_indice).fadeOut(300, function(){
				$('#' + o.slideshow + '-img' + next_image_indice).css('z-index', 12);
				moving = false;				
			}); 
			current_image_indice = 3 - current_image_indice;			
		}
		
		function autoMove(){
		    if(maxPos < 1) return;
		    if(currentPos < maxPos){
				currentPos++;
            }else{
				currentPos = 0;
            }		
			move();
		}
		
		clock = setInterval(function(){autoMove();}, o.timer);			
		
	});
	
}})(jQuery);



