/**
 * @author Vincent FERNIOT - Les Ateliers Apicius
 */ 
(function($) {
	// définition du plugin jQuery
	var timeout;
		
	var methods = {
	    init : function(options) {
	    	var settings = {
				delay		: 4000,
				animateIn	: {	properties: {opacity:1}, 
								duration: 1500,
								easing: 'swing',
								complete: function(){}},
				animateOut	: {	properties: {opacity:0}, 
								duration: 500,
								easing: 'swing',
								complete: function(){}},
				folder		: '',
				slideshow	: false,
				thumbHeight : 50,
				thumbWidth	: 100,
				xml			: '../xml/laa.xml-animation.xml'		        
			};
	    	
			
	    	
			return this.each(function(){
				
				if (options) 
					$.extend(settings, options);
				
				var $this = $(this),
					images = $('<div class="images" />'),
		         	thumbs = $('<div class="thumbs" />');
		        
		       
				$this.append(images);
				$this.append(thumbs);
				$this.wrapInner('<div class="laaXmlAnimation" />');
				
				
				$.ajax({
					type: 'GET',
					url: settings.xml,
					dataType: 'xml',
					success: function(xml) {
						$this.data('laaXmlAnimation', {
							delay		: settings.delay,
							folder		: settings.folder,
							images		: images,
							animateIn	: settings.animateIn,
							animateOut	: settings.animateOut,
							slideshow	: settings.slideshow,
							target		: $this,
							thumbs		: thumbs,
							thumbHeight	: settings.thumbHeight,
							thumbWidth	: settings.thumbWidth,
							xml			: xml
						});
						methods.loadImage.apply( $this, arguments );
					},
					error: function(j, t, e) {
						alert('jqXHR : ' + j + '\nStatus : ' + t + '\n' + e);
					}
				});
			});
	    },
	     
	    nextImage : function(){
	    	
	    	return this.each(function(){
	    		
	    		var data = $(this).data('laaXmlAnimation');
	    		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');
		    		
		    	timeout =  setTimeout(function(){methods.nextImage.apply($this, arguments)}, data.delay);
		    	
	    	});
	    },
	    
	    update : function(){
	    	
	    	return this.each(function(){
	    		
		    	var $this = $(this);
		    	var data = $(this).data('laaXmlAnimation');
		  		
		  		if (data.slideshow)
					clearTimeout(timeout);
					
		  		
		  		data.thumbs.animate({opacity:0}, 500, function(){
		  			$(this).empty().children().remove();
		  			$(this).animate({opacity:1}, 0);
		  			
		  		});
		  		data.images.animate({opacity:0}, 500, function(){
		  			$(this).empty().children().remove();
		  			$(this).animate({opacity:1}, 0);
		  			methods.loadImage.apply( $this, arguments );
		  		});
		  		
			});
	    },
		
		clear : function(){
	    	
	    	return this.each(function(){
	    		
		    	var $this = $(this);
		    	var data = $(this).data('laaXmlAnimation');
		  		
		  		if (data.slideshow)
					clearTimeout(timeout);
					
		  		
		  		data.thumbs.animate({opacity:0}, 500, function(){
		  			$(this).empty().children().remove();
		  			$(this).animate({opacity:1}, 0);
		  			
		  		});
		  		data.images.animate({opacity:0}, 500, function(){
		  			$(this).empty().children().remove();
		  			$(this).animate({opacity:1}, 0);
		  		});
		  		
			});
	    },		
	    
		loadImage: function() {
			
			return this.each(function(){
				var $this = $(this),
					data = $(this).data('laaXmlAnimation'),
					fileName = '';
				
				if (data.folder != '')
				{
					fileName = data.folder;
				}
				else
				{
			    	fileName = getPageFileName().replace(/\.php/, '');
			    }
			    	
		  		var url = $(data.xml).find('galerie').attr('chemin') + fileName;
		  		var xml = $(data.xml).find('pointdevente[nomfichier="'+ fileName +'.php"]').children();
		  		var index = 0;
		  		
		  		if (xml.length == 1)
				{
					var $image = $('<img src="' + url + '/' + $(xml[index]).attr('fichier') + '" />');
					
					$image.load(function() {
						$(this).appendTo(data.images).css({opacity:0}).animate({opacity:1}, 1000);
						
					});
				}
				else
				{
		  		
		  			var load = function(){
			  			var $image = $('<img src="' + url + '/' + $(xml[index]).attr('fichier') + '" />');
			  			
						$image.load(function() {
							
							var $thumb = $('<a href="#" title="' + $(xml[index]).attr('legende') + '" class="thumb"></a>').append($(this).clone());
							var css = {
								'height'	: data.thumbHeight,
								'width'		: data.thumbWidth,
								'overflow'	: 'hidden',
								'opacity' : 0
							}
							
							$thumb.appendTo(data.thumbs).css(css).animate({opacity:1}, 1000);
													
							if ($(xml[index]).attr('hauteur') > $(xml[index]).attr('largeur'))
								$thumb.children().width(data.thumbWidth);
							else
								$thumb.children().height(data.thumbWidth);
													
														
							$thumb.bind({
								click: function(event){
									event.preventDefault();
									data.images.children('.active').animate(data.animateOut.properties, data.animateOut.duration, data.animateOut.easing, data.animateOut.complete).removeClass('active');
									data.thumbs.children().removeClass('active');
									
									$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); 
								}
							});
							
							
							$(this).appendTo(data.images).animate({opacity:0}, 0);
							
							if (index == 0)
								$thumb.trigger('click');
							
							if (index == 1 && data.slideshow)
								timeout =  setTimeout(function(){methods.nextImage.apply($this, arguments)}, data.delay);
									
							index++;
								
							if (index < xml.length)
								load();
							
						});
			  		};
			  		
			  		load();
			  	}
			});
		}
	};
	
	
	
	
	//----------------------------------
	//  getPageFileName
	//----------------------------------
	
	function getPageFileName() {
		//création d'un tableau avec comme valeurs les chaînes de caractères compris entre les slashs. On renvoie ensuite la dernière valeur de ce tableau
		var url = document.location.href.split('\/').pop();
		
		//si dans la chaîne il y a un ? on crée un tableau et on renvoie la dernière valeur
		if (url.indexOf('?') != -1) {
			url= (url.split('?')).pop();
		}
		//si dans la chaîne il y a un # on crée un tableau et on renvoie la dernière valeur
		if (url.indexOf('#') != -1) {
			url= (url.split('#')).pop();
		}
		
		if (url == '')
			url = 'index.php';
		
		return url;
	};
		
	$.fn.laaXmlAnimation = 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.laaXmlAnimation' );
	    } 
	    
	   
	    
	};
})(jQuery);

