/* ------------------------------------------------------------------------------

 - JQuery Plugin : Diaporama     
 - Version : 0.7
 - Date : July, 28, 2011         
 - Developped by : SEV/Ouest-Communication       
 - Licence : GNU GPL             
 - Website: http://www.ouest-communication.com
 - Require : JQuery 1.3.2 or later

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 
 ------------------------------------------------------------------------------ */

(function($){
	$.fn.extend({
        diaporama: function(options){
			function start(){
				timeout = setTimeout(function(){ next(); }, options.duration);
			}
			function stop(){
				if(1==status){ status = 0; }
			}
			function next(){
				if(1==status){
					$(diaposArray[current]).fadeOut(options.speed); 	// disparition de la current
					if((current+1)==nbDiapos){ current=0;
					}else{ current++; }
					$(diaposArray[current]).fadeIn(options.speed); 	// apparition de la next
				}else clearTimeout(timeout);
				timeout = setTimeout(function(){ next(); }, options.duration);
			}
			
			var defaults = {
				'speed'		: 2000, // Vitesse de l'animation
				'duration'	: 5000	// Temps durant lequel l'image est visible
			};
			var options = $.extend(defaults, options); 
			
			// Var
			var timeout;
			var current = 0;
			var diapo = this;
			var diapos = diapo.find('img');
			var diaposArray = diapos.toArray();
			var nbDiapos = diaposArray.length;
			var status;
			var i=nbDiapos;
			var pos = diapo.css('position');
			
			// Style
			if('absolute'!=pos) $(this).css('position', 'relative');
			$(this).css('overflow', 'hidden');
			
			// Initialisation de l'affichage des images
			diapos.css('position', 'absolute');
			diapos.hide().first().show();
			diapos.each(function(){
				var img = new Image;
				img.src = this.src;
				$(this).css('z-index', i);
				if(diapo.height() < $(this).height()){ // Alignement
					var temp = diapo.height()-$(this).height();
					$(this).css('top', (temp/2));
				}
				i--;
			});
				
			status = 1;
			if(1<nbDiapos){ start(); }
		}
	});
})(jQuery);
