// DIAPORAMA:
/*
Usage:
new Diaporama (viewer, thumbmailContener, photoList, boutton_back, boutton_forward, options)
viewer = id de la zone recevant l'image vu
thumbmailContener = id de la zone contenant les miniature
photoList = liste de photo (de type Diaporama.Photo)
boutton_back = id du boutton pour revenir
boutton_forward = id du boutton pour avancer
options = {nom_1 : valeur_1 , nom_2_valeur_2 etc...}
Listes des options:
	direction : vertical par défaut, si précisé et autre que 'vertical', le defilement sera horizontal
	loop : pas implementé
	speed : vitesse en pixel, 1 par défaut, 5 dans le cas d'un moveByStep
	moveByStep : si définit, sa valeur sera l'avancement par pas en pixel au clic de la souri, et non au passage sur le boutton.
	slidePlay : boutton mettant le slideshow en route
	slidePause : boutton mettant le slideshow en pause
	slideShowTime : temps d'attente sur une photo
	nbPreloadedPict : nombre de photo a pre-charger en cache (en suivant l'ordre des miniatures)
*/
Diaporama = Class.create();
Object.extend(Diaporama.prototype,{
	thumbmailContener:null,
	viewer:null,
	currentPhotoNumber:null,
	currentFadeTimeout:null,
	photoList:null,
	fadeTmpPhoto:null,
	cachedPhotoTable:{},
	photoContener:null,
	currentSticker:null,
	
	initialize: function(viewer,thumbmailContener,photoList,options) {
	this.viewer = $(viewer);
	this.thumbmailContener = $(thumbmailContener);
	this.photoList = photoList;
	this.setOptions(options || {});
    this.createContener();

    /*Construction de l'image temporaire servant au fondu*/
	if(document.getElementById('DiapoFadeTmpPhoto') != null) Element.remove($('DiapoFadeTmpPhoto'))
	var fadeTmpPhotoInner;
	if(this.viewer.nodeName == "IMG")
		fadeTpPhotoInner = "<img src='' id='DiapoFadeTmpPhoto' />";
	else
		fadeTpPhotoInner = "<div src='' id='DiapoFadeTmpPhoto' style='background-position:center;background-repeat:none;'>&nbsp;</div>";
    new Insertion.After(this.viewer,fadeTpPhotoInner);
    this.fadeTmpPhoto = $('DiapoFadeTmpPhoto');
    //this.viewer.parentNode.appendChild(this.fadeTmpPhoto);
	/*Positionnement de cette image*/
	//viewerPosition = Position.positionedOffset(this.viewer);
		    /*Element.setStyle(this.fadeTmpPhoto,{
				display:'none',
				position:'absolute',
				top:viewerPosition[1]+"px",
				left:viewerPosition[0]+"px"
			});*/
			var heightPhoto = this.viewer.offsetHeight;
	Element.setStyle(this.fadeTmpPhoto,{
				marginTop:-heightPhoto+"px"
			});
	//this.fadeTmpPhoto.style.top = this.viewer.offsetTop + "px"; this.fadeTmpPhoto.style.left = this.viewer.offsetLeft + "px";
	var firstPhoto = this.photoList[0]
	this.changePhoto(Element.Methods.immediateDescendants(this.thumbmailContener)[0],firstPhoto);
  },
	  setOptions: function(options) {
	    this.options = Object.extend({
	      libele: options.libele ? $(options.libele) : null,
	      subTitle: options.subTitle ? $(options.subTitle) : null,
	      nbPreloadedPict : options.nbPreloadedPict || 2
	      },options || {});
	  },

  	//Fonction creant le div intermediaire qui glissera dans le div "thumbmailContener" et contenant toutes les photos
  	createContener: function() {
	  	/*on rattache toutes les photos*/
	    this.photoList.each(
			function(photo,index){
				var photoElement = document.createElement('div');
				var photoElementIMG = document.createElement('img');
				photoElementIMG.src = photo.srcTb;
				photoElementIMG.alt = photo.title;
				photoElementIMG.title = photo.title;
				photoElementIMG.className='imageContour';
				photoElement.appendChild(photoElementIMG);
				photoElement.innerHTML += photo.title != null ? "<br/><a href='javascript:void(0)'>"+photo.title+"</a>" : "<p>&nbsp;</p>";
				Element.setStyle(photoElement,{textAlign:'center'});
				this.thumbmailContener.appendChild(photoElement);
				if(index%2 == 1)
					{
					var clearLine = document.createElement('p');
					clearLine.className = 'cb';
					this.thumbmailContener.appendChild(clearLine);
					}				changePhotoFn = function(){
					this.changePhoto(photoElement,photo);
					}
			Event.observe(photoElement,"click",changePhotoFn.bind(this));
			this.photoContener = photoElement;
			}.bind(this));
	  },

	/*Fonction qui charge la photo au clic sur la miniature*/
	changePhoto:function(thumbmail,photo)
	{
		  if(this.currentSticker != null)
			  this.viewer.parentNode.removeChild(this.currentSticker);
	  	/*this.viewer.src = src;*/
		currImg = this.loadImgOnCache(photo.src);
		if(!this.imgIsLoaded(currImg))
			{
			Event.observe(currImg,"load",function(photo){
					this.startFadeEffect(photo.src);
					this.viewer.alt = photo.title;
					this.viewer.title = photo.title;
					if(this.options.libele != null)
						Element.update(this.options.libele,photo.title||"");
					if(this.options.subTitle!=null)
						Element.update(this.options.subTitle,photo.subTitle||"");
					}.bind(this,photo));
			}
			else
				{
				this.startFadeEffect(photo.src);
				this.viewer.alt = photo.title;
				this.viewer.title = photo.title;
				if(this.options.libele != null)
					Element.update(this.options.libele,photo.title||"");
				if(this.options.subTitle!=null)
					Element.update(this.options.subTitle,photo.subTitle||"");
				}

		var count = 0;
		/*Mise opacité des miniature*/
		Element.Methods.immediateDescendants(this.thumbmailContener).each(function(node){
		node.removeClassName("selected");
		if(node == thumbmail)
			{node.addClassName("selected");;this.currentPhotoNumber = count}
		count++;
		}.bind(this));
		/*Ajout d'un sticker si present*/
		if(photo.sticker)
			{
			this.currentSticker = photo.sticker;
			$(this.viewer.parentNode).insert({top:this.currentSticker});
			}
		else
			this.currentSticker = null;
		/*Prechargement des photos (si elles ne l'ont pas deja été)*/
		for(i=this.currentPhotoNumber+1;i<this.currentPhotoNumber+this.options.nbPreloadedPict+1 && i<this.photoList.length;i++)
			{
				src = this.photoList[i].src;
				if(!this.cachedPhotoTable[src])
				{
				Event.observe(this.loadImgOnCache(src),"load",function(url,i){
					this.cachedPhotoTable[url] = true;
					}.bind(this,src,i));
				}
			}
	},

	//Fonction chargeant en cache une image et renvoyant un element img non affiché
	loadImgOnCache:function(url)
		{
		var tmpImg = document.createElement('img');
		tmpImg.src = url;
		this.thumbmailContener.appendChild(tmpImg);
		Element.setStyle(tmpImg,{display:"none"});
		return tmpImg;
		},
	imgIsLoaded:function(img)
		{
		if (!img.complete) {return false;}
		if (typeof img.naturalWidth!= "undefined" && img.naturalWidth== 0) {return false;}
		return true;
		},
	startFadeEffect:function(targetSrc)
		{
		clearTimeout(this.currentFadeTimeout);
		this.currentFadeTimeout = null;
		tmpOpacity = 0.95;
		//viewerPosition = Position.positionedOffset(this.viewer);
		    /*Element.setStyle(this.fadeTmpPhoto,{
				top:viewerPosition[1]+"px",
				left:viewerPosition[0]+"px"
			});	*/
		var heightPhoto = this.viewer.offsetHeight;
		Element.setStyle(this.fadeTmpPhoto,{
					marginTop:-heightPhoto+"px"
				});
		Element.setStyle(this.viewer,{opacity:1-tmpOpacity});
		if(this.viewer.nodeName == "IMG")
			{
			this.fadeTmpPhoto.src = this.viewer.src;
			Element.setStyle(this.fadeTmpPhoto,{height:Element.getStyle(this.viewer,"height"),width:Element.getStyle(this.viewer,"width"),display:"block",opacity:tmpOpacity})
			this.viewer.src = targetSrc;
			}
		else
			{
			this.fadeTmpPhoto.style.backgroundImage=this.viewer.style.backgroundImage;
			this.viewer.style.backgroundImage="url("+targetSrc+")";
			Element.setStyle(this.fadeTmpPhoto,{height:Element.getStyle(this.viewer,"height"),width:Element.getStyle(this.viewer,"width"),display:"block",opacity:tmpOpacity})
			}
		setTimeout(this.fadeEffect.bindAsEventListener(this),100);
		},
	fadeEffect:function(targetSrc)
		{
		tmpOpacity = Element.getStyle(this.fadeTmpPhoto,"opacity");
		if(tmpOpacity <= 0)
			{
			Element.setStyle(this.fadeTmpPhoto,{opacity:1.01,display:'none'});
			}
		else
			{
			tmpOpacity -= 0.1;
			Element.setStyle(this.fadeTmpPhoto,{display:"block",opacity:tmpOpacity});
			Element.setStyle(this.viewer,{opacity:1-tmpOpacity});
			this.currentFadeTimeout = setTimeout(this.fadeEffect.bindAsEventListener(this),100);
			}
		}
});
/*Definition d'une photo, avec une liste d'option avec title=titre et alt, src = url de la photo et srcTb = url de la miniature*/
Diaporama.Photo = Class.create();
Object.extend(Diaporama.Photo.prototype, {
	title:null,
	subTitle:null,
	src:null,
	srcTb:null,
	tbTitle:null,
	loaded:false,
	sticker:null,
	initialize: function(arg) {
	this.title = arg.title;
	this.src = arg.src;
	this.srcTb = arg.srcTb;
	this.subTitle = arg.subTitle ? arg.subTitle : null;
	this.tbTitle = arg.tbTitle ? arg.tbTitle : null;
	if(arg.stickerURL)
		this.sticker = $(document.createElement('img')).setStyle({position:'absolute'}).writeAttribute({src:arg.stickerURL});
	}
});