/**
 * @author Vincent FERNIOT - Les Ateliers Apicius
 */ 
;(function($) {
	// définition du plugin jQuery
	var timeout;
	var settings = {
				delay		: 3000,
				animateIn	: {	properties: {opacity:1}, 
								duration: 1000,
								easing: 'swing',
								complete: function(){}},
				animateOut	: {	properties: {opacity:0}, 
								duration: 500,
								easing: 'swing',
								complete: function(){}},
				slideshow	: false,
				thumbHeight : 50,
				thumbTitle	: 'Cliquer pour agrandir',
				thumbWidth	: 50,
				legend      : false	,
				fullscreen	: false        
			};
		
	var methods = {
	    init : function(options) {
	    	
	    	return this.each(function(){
				
				if (options) 
					$.extend(settings, options);
				
				var $this = $(this),
					images = $('<div class="images" />'),
		         	thumbs = $('<div class="thumbs" />'),
		         	legends = $('<div class="legends" />');
		         	
		        
		        $this.append(images);
				$this.append(thumbs);
				$this.append(legends);
				$this.wrapInner('<div class="laaGallery" />');
				
				$this.data('laaGallery', {
					animateIn	: settings.animateIn,
					animateOut	: settings.animateOut,
					delay		: settings.delay,
					fullscreen	: settings.fullscreen,
					images		: images,
					legend		: settings.legend,
					legends		: legends,
					slideshow	: settings.slideshow,
					target		: $this,
					thumbs		: thumbs,
					thumbHeight	: settings.thumbHeight,
					thumbTitle	: settings.thumbTitle,
					thumbWidth	: settings.thumbWidth
				});
				
				// Déclenchement de l'événement qui prévient que les éléments de la galerie sont disponibles dans le DOM
				$this.trigger('ready');
				
				methods.build.apply($this, arguments);
				
			});
		},
			
		build : function() {
			clearTimeout(timeout);
			
			return this.each(function(){
	    		
	    		var data = $(this).data('laaGallery'),
	    			$this = $(this),
	    			images = data.images,
	    			i = 0,
	    			n = $this.find('img').length;
	    			thumbs = data.thumbs,
	    			legends = data.legends,
	    			thumbTitle = data.thumbTitle,
	    			thumbHeight = data.thumbHeight,
	    			thumbWidth = data.thumbWidth;	
				
				
				
				$this.find('img').each(function() {
					
					// Permet d'éviter un bug au niveau du trigger de l'événement onload sur des images déjà en cache
					$(this).one("load",function() {
					
						var	$image = $(this),
							$thumb = $('<a href="#" title="' + thumbTitle + '" class="thumb"></a>').append($image.clone()),
							$legend = $(this).siblings('p'),
							$parent = $image.parent(),
							$thumbImage = $thumb.children('img'),
							ratio =  $image.height() / $image.width(),
							thumbRatio = thumbHeight / thumbWidth,
							css = {
								'height'	: thumbHeight,
								'width'		: thumbWidth,
								'overflow'	: 'hidden',
								'opacity' : 0
							};
						
						
						$image.appendTo(images);
						$image.animate({opacity:0}, 0);
						
						$thumb.appendTo(thumbs).css(css).animate({opacity:1}, 1000);
						
						if(data.legend){
							$legend.appendTo(legends).css({opacity:0});
						} else {
							legends.hide();
						}
						
						$parent.remove();
							
						
						// redimensionnement et centrage de l'image de la vignette
						if (thumbRatio > ratio)
						{
							$thumbImage.height(thumbHeight);
							$thumbImage.width(thumbHeight / ratio);
							$thumbImage.css({'marginLeft' : (thumbWidth - thumbHeight / ratio) / 2});
						}
						else {
							$thumbImage.width(thumbWidth);
							$thumbImage.height(thumbWidth * ratio);
							$thumbImage.css({'marginTop' : (thumbHeight - thumbWidth * ratio) / 2})
						}				
						
						// action à l'événement click						
						$thumb.bind({
							click: function(event){
								event.preventDefault();
								images.find('.active').animate(data.animateOut.properties, data.animateOut.duration, data.animateOut.easing, data.animateOut.complete).removeClass('active');
								thumbs.children().removeClass('active');
								
								if(data.legend) {
								
									legends.find('.active').animate({opacity:0}).removeClass('active');
									$legend.addClass('active').animate({opacity:1}, 1000);
								}
								
								$image.animate(data.animateIn.properties, data.animateIn.duration, data.animateIn.easing, data.animateIn.complete).addClass('active');
								$(this).addClass('active');
							},
							mouseenter: function(){
								if (data.slideshow)
									clearTimeout(timeout); 
							},
							mouseleave: function(){
								if (data.slideshow)
									timeout =  setTimeout(function(){methods.nextImage.apply($this, arguments)}, data.delay); 
							}
						});
						
						
						// si l'option fullscreen est sélectionnée on passe la fonction fullscreen à l'image,
						// on écoute l'événement resize de la fenêtre, sinon on centre l'image
						if (data.fullscreen) {
							$image.fullscreen();
							
							$(window).resize(function(){
								$image.fullscreen();
							});
							
						}
						else {
							$image.css({left: ($image.parent().width() - $image.width()) / 2});
						}
						
						
						
						if (i == 0) {
							$thumb.trigger('click');
							//thumbs.find('a').hide();
						}
							
						
						
						if (i == 1 && data.slideshow) {
							//thumbs.find('a').show();
							timeout =  setTimeout(function(){methods.nextImage.apply($this, arguments)}, data.delay);
						}
							
								
						i++;
						
						
					
					})
					// 2e partie du correctif
					.each(function(){
						if(this.complete) {
							$(this).trigger('load');
						}
						
						// Evénement déclenché quand la galerie est complètement chargée
						n--;
						
						if (n == 0) {
							$(this).trigger('complete');
						}
					});					
				});
			});
	    },
	     
	    nextImage : function(){
	    	
	    	return this.each(function(){
	    		
	    		var data = $(this).data('laaGallery');
	    		var $this = $(this);
		    	var thumb = data.thumbs.children('.active').next();
		    	
		    	
		    	// test pour revenir à la 1e image quand on est au bout du slideshow
		    	if (thumb.is('a'))
	    			thumb.trigger('click');
	    		else
		    		data.thumbs.children(":first").trigger('click');
		    		
		    	if (data.slideshow) {
		    		timeout =  setTimeout(function(){methods.nextImage.apply($this, arguments)}, data.delay);
		    	}
	    	});
	    },
	    
	    resize : function(){
	    	
	    	return this.each(function(){
	    		
	    		var data = $(this).data('laaGallery');
	    		var $this = $(this);
		    	var images = data.images;
		    	
		    	
		    	images.children().each(function(){
		    		$(this).fullscreen();
		    	});
		    	
	    	});
	    },
	    
	    update : function(options) {
			
			return this.each(function(){
				
				if (options) 
					$.extend(settings, options);
				
				var data = $(this).data('laaGallery'),
	    			$this = $(this);
		        
				$this.append(data.images.empty());
				$this.append(data.thumbs.empty());
				$this.append(data.legends.empty());
				$this.wrapInner('<div class="laaGallery" />');
				
				data.animateIn = settings.animateIn;
				data.animateOut = settings.animateOut;
				data.delay = settings.delay;
				data.fullscreen = settings.fullscreen;
				data.legend = settings.legend;
				data.slideshow = settings.slideshow;
				data.thumbHeight = settings.thumbHeight;
				data.thumbTitle = settings.thumbTitle;
				data.thumbWidth = settings.thumbWidth;
				
				methods.build.apply($this, arguments);
				
			});
		
	    }
	};
	
	
	$.fn.fullscreen = function() {
		var imgHeight = $(window).height();
		var imgWidth = (imgHeight * $(this).width()) / $(this).height();
		
		
	
		if (imgWidth > $(window).width()) {
			var range = Math.round((imgWidth - $(window).width()) / 2);
			$(this).css('margin', 'auto');
			$(this).css('marginLeft', '-'+range+'px');
		}
		else {
			imgWidth = $(window).width();
			imgHeight = (imgWidth * $(this).height()) / $(this).width();
			$(this).css('margin', 'auto');
			var range = Math.round((imgWidth - $(window).width()) / 2);
			$(this).css('marginTop', '-'+range+'px');
		}
	
		$(this).css('width', imgWidth+'px');
		$(this).css('height', imgHeight+'px');
	};
	


	
	
		
	$.fn.laaGallery = function(method) {	
		
		// logique des appels des methods
		if (methods[method]) {
	      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
	    } 
	    else if ( typeof method === 'object' || !method ) {
	      return methods.init.apply( this, arguments );
	    } 
	    else {
	      $.error( 'Method ' +  method + ' does not exist on jQuery.laaGallery' );
	    } 
	};
})(jQuery);

