/* */

var SwapImages = new Class({
	Implements : Options,
	
	options : {
		target 		: 'image',
		links		: '.swap',
		loader		: 'image_loader',
		morphDuration	: 0,
		loaderFadeDuration : 250
	},

	initialize : function (options) {
		if ($(this.options.target)) {
			this.setOptions(options);
	
			if (this.activeImage = $(this.options.target)) this.default_src = this.activeImage.getProperty('src');
			else return;
	
			this.containerImage 	= this.activeImage.getParent();
			this.loader 		= $(this.options.loader);
			
			$$(this.options.links).each(function(el){
				new Asset.image(el.href);
				el.addEvent('click', function(e){
					new Event(e).stop();
					
					
					
					
					this._showImg(el);
				}.bind(this))
			}, this);
			
			var coord = this.activeImage.getCoordinates();
			this.containerImage.setStyles({
				'width'  : coord.width,
				'height' : coord.height
			});
	
			this.loader.set('morph', {duration: this.options.loaderFadeDuration, wait: false});
		}
	},

	_showImg : function(el) {
		
		
		
		//On lance la deco
		if ($('image').getProperty('src') == el.getProperty('href') ) return;
		this._positionLoader('in');
		new Fx.Tween('image', {
			duration: 200,
			wait : false,
			transition: Fx.Transitions.linear
		}).start('opacity', 0.1);
		
		//load image
		this.image = new Element('img', {
			'src' : el.href,
			id : 'image',
			styles : { visibility : 'hidden' },
			events : {
				'load' : function(){
					
				}.bind(this)
			}
		});
		
		this._positionLoader('out');
					this._swapImages(el);
	},

	_swapImages : function(el) {
		var url = el.getProperty('href');
		//On fini le fade de la première
		new Fx.Tween('image', {
			duration: 200,
			transition: Fx.Transitions.linear,
			onComplete : function(){
				//On change la taille de $image
				new Fx.Morph(this.containerImage, {
					duration: this.options.morphDuration,
					transition: Fx.Transitions.Quart.easeOut,
					onComplete : function() {
						$('image').destroy();
						this.image.inject(this.containerImage).tween('opacity', 0, 1);
					}.bind(this)
				}).start({
					'height': this.image.height,
					'width': this.image.width
				});
			}.bind(this)
		}).start('opacity', 0);	
	},
	
	_positionLoader : function (way) {
		if (way == 'in') {
			var coord = $('image').getCoordinates();
			var loaderCoord = this.loader.getCoordinates();
			this.loader.setStyles({
				'left' : coord.width/2 + coord.left - loaderCoord.width/2,
				'top' : coord.height/2 + coord.top - loaderCoord.height/2
			});
			this.loader.morph({opacity : 1});
		} else {
			this.loader.morph({opacity : 0});
		}
	}
});

window.addEvent('load', function() {
	new SwapImages();
});
