/**
 * Changement d'image avec fondu suite à un clic sur un lien
 * Initialisation : ImageFade.init( 'conteneur', [ ['id_lien1', 'url_image1'], ['id_lien2', 'url_image2'], ... ] );
 *
 *  /!\ Nécessite la librairie JQuery !
 */
var ImageFade = {
	
	// initialisation
	init: function (container, images) {
		this._container = document.getElementById(container);
		this._images = images;
		this._currentIndex = 0;
		this._fadeDuration = 1000;
		this._fadeOutOn = false;
		this._fadeInOn = false;
		this._imgFadeOut = 'imgFade1';
		this._imgFadeIn = 'imgFade2';
		this.preload(0);
	},
	
	// précharge les images
	preload: function (index) {
		var img = new Image();
		img.onload = function () {
			if (index < ImageFade._images.length - 1)
				ImageFade.preload(++ index);
			else
				ImageFade.displayFirst();
		}
		img.src = this._images[index][1];
	},
	
	// affiche la première image
	displayFirst: function () {
		var styles = 'position:absolute; top:0; left:0; width:100%; height:100%;';
		this._container.innerHTML = '<img src="' + this._images[0][1] + '" id="imgFade1" alt="" style="' + styles + '" />'
		                          + '<img id="imgFade2" alt="" style="' + styles + ' display: none;" />';
		for (var i = 0; i < this._images.length; i ++) {
			this.clickEvent(i);
		}
		if (this._images[0][2]) {
			document.getElementById('textImgFade').innerHTML = this._images[0][2];
		}
	},
	
	// ajout des évènements click aux liens des images
	clickEvent: function (index) {
		jQuery('#' + this._images[index][0]).click(function () {
			ImageFade.change(index);
		});
	},
	
	// change l'image courante (avec effet de fondu)
	change: function (index) {
		if ( this._currentIndex != index && !this._fadeInOn && !this._fadeOutOn ) {
			var imgFadeIn = this._imgFadeIn, imgFadeOut = this._imgFadeOut;
			this._currentIndex = index;
			this._fadeInOn = true;
			this._fadeOutOn = true;
			document.getElementById(this._imgFadeIn).src = this._images[index][1];
			jQuery('#' + this._imgFadeOut).fadeOut(this._fadeDuration, function () {
				ImageFade._imgFadeOut = imgFadeIn;
				ImageFade._fadeInOn = false;
			});
			jQuery('#' + this._imgFadeIn).fadeIn(this._fadeDuration, function () {
				ImageFade._imgFadeIn = imgFadeOut;
				ImageFade._fadeOutOn = false;
			});
			if (this._images[index][2]) {
				document.getElementById('textImgFade').innerHTML = this._images[index][2];
			}
		}
	}
	
}