/*
Author:
	luistar15, <leo020588 [at] gmail.com>
	Arnaud Langlade <arnaud [at] novae-communication.com>
License:
	MIT License

Class
	slideShow v0.2 (14-07-09)

Arguments:
	div            : Id de la div où se trouve les imges à afficher
	options        : voir Paramètre ci dessuis

Parametres:
	divClickInit   : (string) Id d'un élément sur lequel on souhaite ajouter un event onclick afin d'afficher le diaporama, defaut : null
	                 ouvre directement le slideShow.
	useBackGround  : (boolean) utilisation du background
	mode           : (string) mode de transition du diaporama (top, left bottom, alpha, right), defaut : alpha
	size           : (array) tableau définissant les tailles des différents élément du diaprama
	- width        : (integer) Largeur totale du diaporama
	- height       : (integer) Hauteur totale du diaporama
	- marginLeft   : (integer) Marge intérieure gauche
	- marginRight  : (integer) Marge intérieure droite
	- marginBottom : (integer) Marge intérieure basse
	- marginTop    : (integer) Marge intérieure haute
	- borderIn     : (integer) Border du cadre intérieur (doit correspondre à la bordure définie dans ".diaporama div")
	- borderOut    : (integer) Border du contenu général (doit correspondre à la bordure définie dans ".diaporama")
	picPath        : (string) Chemin vers le répertoire où se trouve les icône
   fxOptions      : (string) Option effet fx
	interval       : Temporisation entre chaque image lorsqu'on joue le diaporama

Requires:
	mootools 1.2 core

Style (minimal) à joindre:

.diaporama
{
	position:absolute;
	z-index:300000000;
	display:none;
}

.diaporama div
{
	display:none;
}
*/

var SimpleSlideShow = new Class({
	
	Implements: Options,
	
	options: {
		divClickInit : null,
		useBackGround : true,
   	mode: 'alpha',
		sizes: {
			width: 850,
			height: 700,
			marginLeft: 10,
			marginRight: 10,
			marginBottom: 40,
			marginTop: 30,
			borderIn: 1,
			borderOut: 1
		},
		picPath : 'images/slideShow/',
		fxOptions: {
			duration: 500
		},
		interval: 3000
		
	},

	initialize: function(picture,options){
     		
			// Tableau d'image
         this.picture = picture;
			
			// Merge les options
   		this.setOptions(options);
   		
   		// Initialisation des autres varaibles
   		this._current = 0;
   		this._previous = null;
   		this.disabled = false;
   		this.timer = null;
   		
   		// Hauteur totale des marges
   		this.hSizeMargin = this.options.sizes.marginTop + this.options.sizes.marginBottom;
   		
   		// Largeur totale des marges
   		this.wSizeMargin =  this.options.sizes.marginLeft + this.options.sizes.marginRight;
   		
   		// Hauteur de la div du diapo
   		this.hMainDivSize = this.options.sizes.height + this.options.sizes.borderOut * 2;
   		
   		// Largeur de la div du diapo
   		this.wMainDivSize = this.options.sizes.width + this.options.sizes.borderOut * 2;
   		
   		// Hauteur du pied du diapo
   		this.hFooterSize = this.options.sizes.marginBottom;
   		
   		// Hauteur de la div intérieure du diapo
   		this.hSecDivSize = this.options.sizes.height - this.hSizeMargin - this.options.sizes.borderIn * 2;

   		//Largeur de la div intérieure du diapo
   		this.wSecDivSize = this.options.sizes.width - this.wSizeMargin - this.options.sizes.borderIn * 2;
   		
			// Effet Tween
			/*this.attrs = new Array();
			var a = this.attrs[this.options.mode].associate(['p','f','t','u']);
			this.items[this._current].setStyles($extend({'display':'block','z-index':'2'},JSON.decode('{"'+a.p+'":"'+a.f+a.u+'"}')));
			this.items[this._current].set('tween',$merge(this.fxOptions,{})).tween(a.p,a.f,a.t);*/
			
			
			// Si l'id d'un element html a été pricisé alors on déclenche un évement sur celui ci.
			if($(this.options.divClickInit))
			{
				$(this.options.divClickInit).setStyle('cursor', 'pointer');
	         $(this.options.divClickInit).addEvent('click', function()
				{
	            // On positionne le diaporama lors du clic
	            this.initSlideShow();
					this.displaySlideShow();
	            
				}.bind(this));
			}
	      else
	      {
	         this.initSlideShow();
				this.displaySlideShow();
	      }
	},
	
	
		
		
	/*
	 * Initialise le diaporama pour la photo de rang 0, appellé dans le contructeur
	 * déclenche l'evenement onclick sur un évement si cela est demandé dans les options
	 */
	
	initSlideShow: function(){

		this.skinSlideShow();
		this.items = new Array();
		this.picture.each(function(src, index)
		{
		   //alert(index + " = " + src);
			/*this.items[index] = new Element('img', {
			    'src': src
			});*/
			 
			this.items[index] = new Asset.image(src, {onload:function(){
			 	this.resizePicture(index);
				this.positionPicture(index);
			}.bind(this)});
			
			this.items[index].setStyles({
				'display' : 'none',
				'position' : 'absolute',
				'border' : 'none'
	   	});
		
			this.items[index].inject(this.insideContent);
		}.bind(this));
		

		this.items[this._current].setStyle('display','block');
	},
	
   displaySlideShow: function (){
		this.outsideContent.setStyle('display', 'block')
   }, 
	
	
	hideSlideShow: function (){
		this.outsideContent.dispose();
		if (this.options.useBackGround)
		{
	  		this.sSbackGround.dispose();
	  	}
   }, 
	
	
   
   /*
    * Affiche le diaporama, avec la bonne marge (top) et son background
   */
   
   skinSlideShow: function (){
		// Content du diaporama
		this.contentSlideShow();
		
		// Bouton du diaporama
      this.butonSlideShow();
      
		// Background slide show
		this.backGroundSlideShow();
   }, 
   
   
	/*
	 * BackGround du diaporama (div qui recouvre l'ensemble de la page avec une opacity
	 * de 50 pourcents)
	 */
   
	backGroundSlideShow:function()
	{
		if (this.options.useBackGround)
		{
			// On vérifie que le background existe si c'est le cas on le réaffiche sinon on le crée

			var scrollSize = document.body.getScrollSize();
			this.sSbackGround = new Element('div', {
				'id': 'sSbackGround',
				'styles': {
					'position': 'absolute',
					'top': '0px',
					'left': '0px',
					'z-index': '3000',
					'width': '100%',
					'height': (scrollSize.y) + 'px',
					'background-color': '#000000'
				}
			});
			this.sSbackGround.inject($(document.body));
			
			
			// Merci IE
			if (Browser.Engine.trident)
			{
				this.sSbackGround.setStyle('filter', 'alpha(opacity=50)');
			}
			else
			{
				this.sSbackGround.setStyle('opacity', '0.5');
			}
			
		}		
   },
   
   
   
   /*
	 * Footer du diaporama soit on printe une legende s'il y a qu'une image ou menu pour gérer
	 * le diaporama si le nombre d'images est supérieur à 1
	 */
   
	butonSlideShow:function()
	{
		
		// Création du bouton fermeture et injection dans la div contentgeneral 
		this.closePicture = new Element('img',{
			'src': this.options.picPath+'close.png',
			'id': 'btnCloseSlide',
			'styles': {
				'left': this.wMainDivSize - 16 - 7+'px',
				'cursor': 'pointer',
				'float': 'right', 
				'bottom': this.hMainDivSize - 16 - 7+'px',
				'position' : 'absolute'
			},
			'events':{
				'click': function(){
					this.hideSlideShow();
				}.bind(this)
			}
		});
      this.closePicture.inject(this.outsideContent);
		
      
		
      // S'il n'y a qu'une image alors on ne fait qu'une légende dans le footer dans le cas 
      // contraire on affiche un diparama
      if(this.picture.length == 1)
      {
         // Création de la dic legend et injection dans la div contentgeneral 
         this.legend = new Element('span',{
   			'html': 'Photo du bien',
   			'id': 'divLegende',
   			'styles': {
   				'float': 'left',
   				'left': '0px',
               'text-align' : 'center',
   				//'margin' :(this.hFooterSize - this.options.sizes.borderIn * 2 -16)/2+'px 0px 0px 0px',
   				'position' : 'absolute',
               'top': this.hMainDivSize - 30+'px',
               'width' : '100%',
               'display' : 'block'
   			}
   		});
         this.legend.inject(this.outsideContent);
      }
      else
      {
         // Création du bouton précédent et injection dans la div contentgeneral 
         this.prevPicture = new Element('img',{
   			'src': this.options.picPath+'previous.png',
   			'id': 'btnPrevSlide',
   			'styles': {
   				'cursor': 'pointer',
   				'float': 'left',
   				'left': this.wMainDivSize/2 - 2*20+'px',
   				//'margin' :(this.hFooterSize - this.options.sizes.borderIn * 2 -16)/2+'px 0px 0px 0px',
               'top': this.hMainDivSize -27+'px',
   				'position' : 'absolute'
   			},
   			'events':{
   				'click': this.previous.bind(this,[true])
   			}
   		});
         this.prevPicture.inject(this.outsideContent);
   		
         // Création du bouton suivant et injection dans la div contentgeneral 
   		this.nextPicture = new Element('img',{
   			'src': this.options.picPath+'next.png',
   			'id': 'btnNextSlide',
   			'styles': {
   				'cursor': 'pointer',
   				'float': 'left',
   				'left': this.wMainDivSize/2 + 20+'px',
   				//'margin' :(this.hFooterSize - this.options.sizes.borderIn * 2 -16)/2+'px 0px 0px 0px',
               'top': this.hMainDivSize -27+'px',
   				'position' : 'absolute'
   			},
   			'events':{
   				'click':this.next.bind(this,[true])
   			}
   		});
         this.nextPicture.inject(this.outsideContent);
   		
         // Création du bouton jouer et injection dans la div contentgeneral 
   		this.playPicture = new Element('img',{
   			'src': this.options.picPath+'play.png',
   			'id': 'btnPlaySlide',
   			'styles': {
   				'cursor': 'pointer',
   				'float': 'left',
   				'left': (this.wMainDivSize - 20)/2+'px',
   				//'margin' :(this.hFooterSize - this.options.sizes.borderIn * 2 - 16)/2+'px 0px 0px 0px',
               'top': this.hMainDivSize -27+'px',
   				'position' : 'absolute'
   			},
   			'events':{
   				'click': this.play.bind(this,[false])
   			}
   		});
   		this.playPicture.inject(this.outsideContent);
   		
      }
   },
	
   
   
	/*
	 * Création de l'habillage du diaporama
	 */
	
	contentSlideShow: function(){
      // Cadre extérieur du diaporama (contenu général)
      this.outsideContent = new Element('div',{
			'id': 'sSoutsideContent',
			'class': 'diaporama',
			'styles': {
				'width': this.wMainDivSize,
				'height': this.hMainDivSize,
				'margin-right' : -this.wMainDivSize/2,
				'right': '50%',
				'position':'absolute',
				'top' : '0px'
			}
		});
		
		this.insideContent = new Element('div',{
			'id': 'sSinsideContent',
			'styles': {
				'width': this.wMainDivSize - this.wSizeMargin,
			   'height': this.hMainDivSize - this.hSizeMargin,
			   'margin': this.options.sizes.marginTop+'px '+(this.options.sizes.marginRight - this.options.sizes.borderIn)+'px 0px '+(this.options.sizes.marginLeft - this.options.sizes.borderIn)+'px',
				'overflow' : 'hidden',
				'position' : 'relative'
			}
		});															 

		this.insideContent.inject(this.outsideContent);

		// On met le tout dans le body
		this.outsideContent.inject($('body'));
	},
	
	
	
	
	
	/*
	 * Redimentionne la photo stockée à la N case du tableau de photos
	 */
	
	resizePicture: function (n){
	
		// Longueur et largueur maximum de l'image
		var maxWidth = this.wSecDivSize;
	   var maxHeight = this.hSecDivSize;

   	// Iniatilisation de la nouvelle taille
		this.newWidth = 0;
   	this.newHeight = 0;
   	
		
		// Récupération de la nouvelle taille de l'image, pas sur que ca soit très propre mais
		// ca fontion.
		//var h = this.newHeight = image.height;
		//var w = this.newWidth = image.width;
		
		var h = this.newHeight = this.items[n].height;
		var w = this.newWidth = this.items[n].width;

		//alert(h+'--'+w);
		
		// Si la largeur ou la hauteur depasse la taille maximale
		if ((h >= maxHeight) || (w >= maxWidth))
		{
			// on enlève 20 pixel pour éviter l'imge soit de la même hauteur que la div qui acceuille la photo.
			maxWidth = maxWidth - 20;
			maxHeight = maxHeight - 20;
			
			// Si la largeur et la hauteur depasse la taille maximale
			if ((h >= maxHeight) && (w >= maxWidth))
			{
				// On cherche la plus grande valeur
				if (h > w)
				{
					this.newHeight = maxHeight;
					// On recalcule la taille proportionnellement
					this.newWidth = parseInt((w * this.newHeight) / h, 10);
				}
				else
				{
					this.newWidth = maxWidth;
					// On recalcule la taille proportionnellement
					this.newHeight = parseInt((h * this.newWidth) / w, 10);
				}
			}
			else if ((h > maxHeight) && (w < maxWidth))
			{
				// Si la hauteur depasse la taille maximale
				this.newHeight = maxHeight;
				// On recalcule la taille proportionnellement
				this.newWidth = parseInt((w * this.newHeight) / h, 10);
			}
			else if ((h < maxHeight) && (w > maxWidth))
			{
				// Si la largeur depasse la taille maximale
				this.newWidth = maxWidth;
				// On recalcule la taille proportionnellement
				this.newHeight = parseInt((h * this.newWidth) / w, 10);
			}
		}
		
		// On redimentionne la nouvelle image
		if (w != this.newWidth)
		{
			this.items[n].setStyle('width',this.newWidth);
		}
		
		if (h != this.newHeight)
		{
			this.items[n].setStyle('height',this.newHeight);
		}
		
	},
	
	
	
	
	
	/*
	 * Position la photo dans le diapo, l'effet Tween de mootools ne peut gérer qu'une translation 
	 * (ou effet) à la fois donc suivant le mode on positionne la photo, puis on calcule les coordonnées
	 * de l'effet tween
	 */
	
	positionPicture: function(n){
		
		// Gestion du position des photos
		var marginTop	= ((this.hSecDivSize - this.newHeight)/2).round();
		var marginLeft = ((this.wSecDivSize - this.newWidth)/2).round();

		
		if (this.options.mode == 'top' || this.options.mode == 'bottom')
		{
			this.items[n].setStyle('margin-left', marginLeft+'px');
		}
		else if (this.options.mode == 'alpha')
		{
			this.items[n].setStyle('margin-top', marginTop+'px');
			this.items[n].setStyle('margin-left', marginLeft+'px');
		}
		else
		{
			this.items[n].setStyle('margin-top', marginTop+'px');
		}
		
		
		// Gestion des positions avec l'effet tween
		this.attrs = {
			left: ['left', -this.newWidth , ((this.wSecDivSize - this.newWidth)/2).round(), 'px'],
			top: ['top', -this.newHeight, ((this.hSecDivSize - this.newHeight)/2).round(), 'px'],
			right: ['left', this.wSecDivSize, ((this.wSecDivSize - this.newWidth)/2).round(), 'px'],
			bottom: ['top', this.newHeight, ((this.hSecDivSize - this.newHeight)/2).round(), 'px'],
			alpha: ['opacity', 0, 1, '']
		};
	},
	
	
	
		

	
	walk: function(n,manual){
		
		if(this._current !== n && !this.disabled)
		{
			this.disabled = true;
			this._previous = this._current;
			this._current = n;
			
			if(manual)
			{
				this.stop();
			}

			// On calcule la nouvelle taille de l'image et on redimensionne la photo (si besion)
			//this.resizePicture(this._current);
			
			// On positionne la photo
			//this.positionPicture(this._current);
			
			// Gestion des styles pour l'affiche
			var a = this.attrs[this.options.mode].associate(['p','f','t','u']);
			for(var i=0;i<this.items.length;i++)
			{
				
				if(this._current===i)
				{
					this.items[i].setStyles($extend({'display':'block','z-index':'2'},JSON.decode('{"'+a.p+'":"'+a.f+a.u+'"}')));
				}
				else if(this._previous===i)
				{
					this.items[i].setStyles({'z-index':'1', 'display':'none'});
				}
				else
				{
					this.items[i].setStyles({'display':'none','z-index':'0'});
				}
			}
			
			// Affichage de l'image avec un effet tween
			this.items[n].set('tween',$merge(this.fxOptions,{onComplete:this.onComplete.bind(this)})).tween(a.p,a.f,a.t);
		}
	},




	play: function(wait)
	{
		//this.stop();
		if(!wait)
		{
			$('btnPlaySlide').setProperty('src', this.options.picPath+'pause.png');
			$('btnPlaySlide').removeEvents('click');
			$('btnPlaySlide').addEvent('click', this.stop.bind(this,[true]));
			this.next();
		}
		this.timer = this.next.periodical(this.options.interval,this,[false]);
	},



	stop: function()
	{
		$('btnPlaySlide').setProperty('src', this.options.picPath+'play.png');
		$('btnPlaySlide').removeEvents('click');
		$('btnPlaySlide').addEvent('click', this.play.bind(this,[false]));
		$clear(this.timer);
	},



	next: function(manual)
	{
		this.walk(this._current+1<this.items.length ? this._current+1 : 0,manual);
	},



	previous: function(manual)
	{
		this.walk(this._current>0 ? this._current-1 : this.items.length-1,manual);
	},



	onComplete: function()
	{
		this.disabled = false;
		if(this.onWalk) this.onWalk(this._current);
		
	}
});
