/**
 * Gallery Class Javascript basée sur Prototypes http://prototypejs.org/
 * cré une gallery de présentation d'image basée sur les iumages contenu dans le containeur passé en parametre
 * @Author :: Nours312@nours312.com
 * @version :: 0.1
 *
 * 1. ajouter les fichiers prototype.js et popupNews.js dans l'attribut <head de votre document de la forme suivante ::
  	<script type="text/javascript" src="../url_relative/prototype.js" ></script>
  	<script type="text/javascript" src="../url/relative/popupNews.js"></script>
 * 2. faire indépendemment l'évennement d'ouverture
 * (le fichier protopype.js est récupérable à ladresse suivante : http://prototypejs.org/assets/2009/8/31/prototype.js
 *
 *
 */

var GalleryMotor = Class.create({
	timer: null,
	divImg:null,
	autoPlay : false,
	tempo : null,
	cont:null,
	views : [],
	viewsGallery:[],
	current : 0,
	temp:{},
	param : {},
	initialize : function(id, param){
		this.timer = null;
		this.divImg = null;
		this.autoPlay = false;
		this.param.tempo = 4;
		this.cont = null;
		this.views = [];
		this.current = 0;
		this.param = {};
		this.temp = {
			id		: id,
			cont	: $(id),
			title	: $$('#'+id+' .GalleryTemplateTitle')[0],
			desc	: $$('#'+id+' .GalleryTemplateDesc')[0],
			temp	: $$('#'+id+' .GalleryTemplate')[0],
			viewer	: $$('#'+id+' .GalleryTemplateViewer')[0],
			next	: $$('#'+id+' .GalleryTemplateNext'),
			prev	: $$('#'+id+' .GalleryTemplatePrev'),
			play	: $$('#'+id+' .GalleryTemplatePlay'),
			views	: $$('#'+id+' .GalleryViews')[0],
			loader	: $(id).down('.GalleryLoader'),
			icone	: $(id).down('.GalleryIcone'),
			iconeOv	: $(id).down('.GalleryIconeOv'),
			params	: $$('#'+id+' .GalleryParams')[0]
		};
		this.autoPlay = param.autorun;
		this.cont = this.temp.viewer;
		this.param = Object.extend(this.param, param || {});
		this.param.duration = (param.duration && param.duration != undefined)? parseFloat(param.duration) : 2;
		this.param.tempo = (param.tempo && param.tempo != undefined && param.tempo >= 1)? parseFloat(param.tempo) : 2;
		this.tempo = this.param.duration + this.param.tempo;
		this.views = this.temp.views.childElements();
		this.load[this.param.effect].bind(this)();
		if(!this.param.popup || this.param.popup == '0'){
			this.loadEventButton();
			if(this.autoPlay){
				this.autoPlay = false
				this.play();
			}
		} else {
			if(this.temp.loader != undefined && this.temp.icone != undefined)
				$(this.temp.loader).observe('click', this.openGallery.bindAsEventListener(this));
			if(this.temp.icone != undefined && this.temp.iconeOv != undefined){
				var iconeOvSpan = this.temp.iconeOv.ancestors()[0];
				var q = this.temp.id+'OverQueues';
				this.temp.loader.observe('mouseover', function(){if(iconeOvSpan.style.display == 'none')Effect.Appear(iconeOvSpan, {duration:1, queue: { position:'end', scope:  q}})});
				this.temp.loader.observe('mouseout', function(){var queue = Effect.Queues.get(q);queue.each(function(effect) { effect.cancel(); });Effect.Fade(iconeOvSpan, {duration:1, queue: {position:'end', scope:  q}})});
			}
		}
	},
	load : {
		none : function(){
			for(var i=0; i<this.views.length; i++)
				this.cont.insert(this.views[i]);
			this.cont.show();
			this.temp.views.hide();
		},
		grow : function(){
			for(var i=0; i<this.views.length; i++)
				this.cont.insert(this.views[i]);
			this.cont.show();
			this.temp.views.hide();
		},
		slide : function(){
			var div = new Element('div');
			this.cont.insert(div);
			for(var i=0; i<this.views.length; i++)
				div.insert(this.views[i]);
			this.cont.show();
			this.temp.views.hide();
		},
		blind : function(){
			var div = new Element('div');
			this.cont.insert(div);
			for(var i=0; i<this.views.length; i++)
				div.insert(this.views[i]);
			this.cont.show();
			this.temp.views.hide();
		},
		appear : function(){
			for(var i=0; i<this.views.length; i++)
				this.cont.insert(this.views[i]);
			this.cont.show();
			this.temp.views.hide();
		},
		move : function(){
			for(var i=0; i<this.views.length; i++)
				this.cont.insert(this.views[i]);
			this.cont.show();
			this.temp.views.hide();
		}
	},
	effect : {
		none : function(afterEff){
			this.views[this.current].show();
			afterEff();
		},
		grow : function(afterEff){
			var c = this.views[this.current];
			var q = this.temp.id+'_queues';
			Effect.Grow(c, {duration:this.param.duration, afterFinish:afterEff, direction: 'center', queue: { scope:  q} });
		},
		slide : function(afterEff){
			var c = this.views[this.current];
			c.setOpacity(0.01);
			c.show();
			var q = this.temp.id+'_queues';
			new Effect.SlideDown(c.ancestors()[0], {duration:this.param.duration, afterFinish:afterEff, afterUpdate:function(){c.setOpacity(1);}, queue: { position: 'end', scope:  q} });
		},
		blind : function(afterEff){
			var c = this.views[this.current];
			c.setOpacity(0.01);
			c.show();
			var q = this.temp.id+'_queues';
			new Effect.BlindDown(c.ancestors()[0], {duration:this.param.duration, afterFinish:afterEff, afterUpdate:function(){c.setOpacity(1);}, queue: { position: 'end', scope:  q} });
		},
		appear : function(afterEff){
			var c = this.views[this.current];
			c.setOpacity(0.01);
			c.show();
			var q = this.temp.id+'_queues';
			new Effect.Appear(c, {from:0, to:1, duration:this.param.duration, afterFinish:afterEff, queue: { position: 'end', scope:  q} });
		},
		move : function(){
			var c = this.views[this.current];
			var dim = c.getDimension();
			var parent = c.ancestors()[0];
			var dimParent = parent.getDimension();
			var positionParent = parent.positionedOffset();
			c.setStyle({'marginTop' : '0px', 'marginLeft': dimParent[0]+'px'});
			var q = this.id+'_queues';
			new Effect.Move(c, {x:-(dimParent[0] + dim[0])/2 , y:0, mode:'relative', queue: { position: 'end', scope:  q} });
		}
	},
	afterEffect :{
		def : function(){
			var dimP = this.cont.ancestors()[0].getDimensions();
			var dim = this.cont.getDimensions();
			this.cont.setStyle({
				background:'url('+this.views[this.current].src+') center center ',
				width:this.views[this.current].getWidth()+'px',
				height:this.views[this.current].getHeight()+'px',
				top:(dimP.height - dim.height)/2+'px',
				left:(dimP.width - dim.width)/2+'px'
			});
		},
		move : function(){
			this.cont.setStyle({
				background:'url('+this.views[this.current].src+') center center ',
				width:this.views[this.current].getWidth()+'px',
				height:this.views[this.current].getHeight()+'px'
			});
		}
	},
	avance : function(){
		window.clearTimeout(this.timer);
		var queue = Effect.Queues.get(this.temp.id+'_queues');
		queue.each(function(effect) {
			effect.cancel();
		});
		if (this.autoPlay == true)
			this.timer = window.setTimeout(this.avance.bind(this), this.tempo*1000);
		this.current++;
		if (this.current >= this.views.length) this.current = 0;
		if (this.current < 0) this.current = this.views.length-1;
		var eff = (Object.isFunction(this.effect[this.param.effect])) ? this.effect[this.param.effect].bind(this) : this.effect.def.bind(this);
		var afterEff = (Object.isFunction(this.afterEffect[this.param.effect])) ? this.afterEffect[this.param.effect].bind(this) : this.afterEffect.def.bind(this);
		this.views.invoke('hide');
		eff(afterEff);
	},
	play : function(){
		if(this.autoPlay == false){
			this.autoPlay = true;
			for(i=0;i<this.temp.play.length;i++)
				if(this.temp.play[i].src && this.temp.play[i].src != undefined)
					this.temp.play[i].src = this.temp.play[i].src.gsub(/play/, 'pause');
			this.avance();
		} else {
			window.clearTimeout(this.timer);
			this.autoPlay = false;
			for(i=0;i<this.temp.play.length;i++)
				if(this.temp.play[i].src && this.temp.play[i].src != undefined)
					this.temp.play[i].src = this.temp.play[i].src.gsub(/pause/, 'play');
		}
	},
	plus : function(){
		this.avance();
	},
	moins : function(){
		this.current = this.current -2;
		this.avance();
	},
	loadHtml: function(){
		var currentView = this.viewsGallery[this.current];
		new Effect.Opacity(currentView, {to:1.0});
	},
	loadEventButton : function(){
		this.temp.prev.invoke('observe', 'click', this.moins.bindAsEventListener(this));
		this.temp.next.invoke('observe', 'click', this.plus.bindAsEventListener(this));
		this.temp.play.invoke('observe', 'click', this.play.bindAsEventListener(this));
	},
	openGallery : function(e){
		var title = (e.element().src && e.element().src != undefined) ? e.element().title : e.element().down('img').title;
		new Popup3acTemplate(this.temp.temp.innerHTML, title, {popupOptions:{width:'100%'}, backgroundOptions:{background:'black'}});
		this.cont = $$('#FloatFrame .GalleryTemplateViewer')[0];
		this.views = $$('#FloatFrame .Gallery'+this.temp.id);
		this.temp.next = $$('#FloatFrame .GalleryNext');
		this.temp.prev = $$('#FloatFrame .GalleryPrev');
		this.temp.play = $$('#FloatFrame .GalleryPlay');
		this.loadEventButton();
		if(this.autoPlay){
			this.autoPlay = false
			this.play();
		}
	}

});


var Gallery = Class.create({
	imgLoader : 'http://www.gseforsale.aero/images/ajax-loader.gif',
	defaultOpacity : 0.5,
	autoPlay : false,
	tempo : 5, // secondes
	pauseLink: null,
	cont:null,
	backFrame : null,
	floatFrame : null,
	views : [],
	viewsGallery:[],
	current : null,
	next : null,
	prev : null,
	playButton : null,
	container:null,
	menu:null,
	margin : {x:70, y:20},
	livePosition : {x:0, y:0},
	initializeMoveParam : {x:0,y:0},
	timer: null,
	divImg:null,
	initialize : function(views, current){
		this.openGallery();
		this.views = views; // urls des images à charger
		this.current = (current && current != 'undefined') ? current : this.views.length;

		for(i=0; i<this.views.length; i++){
			var img = new Element('img');
			img.src = this.views[i];
			this.container.insert(img);
			this.viewsGallery[i] = img;
		}
		this.initializeMoveParam.x = (document.viewport.getWidth()+this.moveParam.x)/2;
		this.initializeMoveParam.y = (parseFloat(this.popupOptions.height)-(parseFloat(this.imgCss.height)+parseFloat(this.imgCss.border)*2+20))/2;
		this.divImg.setStyle({top:this.initializeMoveParam.y+'px', left:this.initializeMoveParam.x+'px'});
		this.avance();
	},
	avance : function(){
		console.log(this.views);
		window.clearTimeout(this.timer);
		var Go = this.avance;
		if (this.autoPlay == true)
			this.timer = window.setTimeout(this.avance.bind(this), this.tempo*1000);

		this.viewsGallery.invoke('setOpacity', this.defaultOpacity);
		this.current++;
		if (this.current >= this.viewsGallery.length) this.current = 0;
		if (this.current < 0) this.current = this.viewsGallery.length-1;
		if (!this.views[this.current].position){
			var newparam = {x:0,y:0};
			for (i = 0; i<this.current; i++){
				newparam.x += this.views[i].getWidth()+this.margin.x;
			}
			newparam.y = (this.container.getHeight-this.views[i].getHeight())/2;
			this.views[this.current].position = newparam;
		}
		var moveParam = (this.current == 0)? this.initializeMoveParam :{x:this.views[this.current].position.x+this.initializeMoveParam.x, y:this.views[this.current].position.y+this.initializeMoveParam.y};
		var c = this.container;
		new Effect.Move(c, 
			{x: moveParam.x, y:moveParam.y, mode : 'absolute', transition: Effect.Transitions.sinoidal}
		);
	},
	play : function(){
		if(this.autoPlay == false){
			this.autoPlay = true;
			this.avance();
			this.playButton.src = this.pauseLink;
		} else {
			window.clearTimeout(this.timer);
			this.autoPlay = false;
			this.playButton.src = this.playLink;
		}
	},
	plus : function(){
		this.avance();
	},
	moins : function(){
		this.current = this.current -2;
		this.avance();
	},
	loadHtml: function(){
		var currentView = this.viewsGallery[this.current];
		new Effect.Opacity(currentView, {to:1.0});
	},
	openGallery : function(){
		var url = this.urlDossImgGallery;

		this.next = $('GalleryNext');
		this.prev = $('GalleryNext');
		this.playButton = $('GalleryPlay');
		this.menu = $('GalleryMenu');
		this.container = $('GalleryContainer');
		this.playLink = this.playButton.src;
		this.pauseLink = this.playLink.gsub(/\/(play)\./, '/pause.');

		$$('.GalleryButton').invoke('setOpacity', 0.7);
		$$('.GalleryButton').invoke('observe', 'mouseover', function(){this.setOpacity(1);});
		$$('.GalleryButton').invoke('observe', 'mouseout', function(){this.setOpacity(.7);});

		this.next.observe('click', this.plus.bindAsEventListener(this));
		this.prev.observe('click', this.moins.bindAsEventListener(this));
		this.playButton.observe('click', this.play.bindAsEventListener(this));
	}
});
/**
 *  remplace une url monImage.png par monImage_over.png (si c'est hover) ou suprime _over dans l'url ...
 */
/* var changeUrlOver = function(position){
	var url = this.getStyle('backgroundImage');
	if(position == 'out')
		this.setStyle('backgroundImage', url.gsub(/.png/, '_over.png'));
	else
		this.setStyle('backgroundImage', url.gsub(/_over/, ''));
}
var ChangeOver = function(event){
	event.element().childElements.invoke('changeUrlOver', 'over');
}
var ChangeOut = function(event){
	event.element().childElements.invoke('changeUrlOver', 'out');
}
document.observe('dom:loaded', function(){
	$$('#menu a').invoke('observe', 'mouseover', ChangeOver);
	$$('#menu a').invoke('observe', 'mouseout', ChangeOut);
});
*/