(function($)
{
    $.fn.simpleDiaporama = function(params)
    {
    	params = $.extend( { delay: 5000, fade: 1000, buttonNext: $("a.next"), buttonPrev: $("a.prev"), buttonGoto: $("a.goto"), autoplay: true }, params);
        
        var delay       = params['delay'];
        var fade 		= params['fade'];
        var buttonNext  = params['buttonNext'];
        var buttonPrev  = params['buttonPrev'];
        var buttonGoto 	= params['buttonGoto'];
        var autoplay    = params['autoplay'];
        
        var illustrations = [];
    	var height = 0;

    	var current = 0;
		
		var is_animating = false;
		
    	var timer = null;

    	this.each(function()
    	{
        	var $diaporama = $(this);

        	illustrations = $diaporama.children();
			/*
        	$.each(illustrations, function()
        	{
        	    if($(this).height() > height)
        	    {
        	    	height = $(this).height();
        	    }
        	});
			
        	$.each(illustrations, function()
        	{
            	$(this).height(height);
            });
            */
            $diaporama.css({
        	    //'height': height,
        	    'overflow': 'hidden'
            });
			
			illustrations.css({
				'position': 'absolute',
				'top': 0
			});
            
            $(buttonGoto).eq(0).addClass('active');
            
            buttonNext.click(function(e){
                e.preventDefault();
                next()
            });

            buttonPrev.click(function(e){
                e.preventDefault();
                prev();
            });
            
            buttonGoto.click(function(e){
                e.preventDefault();
                var index = e.currentTarget.rel;
                if( index != current )
                {
                	showImage(index);
                }
            });

            illustrations.not(':eq(0)').hide();

            if(autoplay)
            {
            	timer = setTimeout(next, delay);
            }
            
    	});

        function next()
        {
            var index = ((current + 1) >= illustrations.length) ? 0 : current + 1;
            showImage(index);
        }

        function prev()
        {
            var index = ((current - 1) < 0 ) ? illustrations.length - 1 : current - 1;
            showImage(index);
        }

        function showImage(index)
        {
			if( !is_animating )
			{
				is_animating = true;

	        	clearTimeout(timer);

				buttonGoto.removeClass('active');
	        	$(buttonGoto).eq(index).addClass('active');

				illustrations.stop(true, true);

				illustrations.eq(current).fadeOut(fade);

				illustrations.eq(index).fadeIn(fade, function()
				{
					current = index;

					is_animating = false;

		            if(autoplay)
		            {
		            	timer = setTimeout(next, delay);
		            }
				});
			}
        }

    	return this;
    };
    
})(jQuery);
