/*

The MIT License

ByZoomer (http://www.byscripts.info/mootools/byzoomer)
Copyright (c) 2008 ByScripts.info (http://www.byscripts.info)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

var ByZoomer = new Class({
	//Implements: Options,
	Implements: [Options,Events],
	//Implements: [Options],
	options: {
		zoom: 1,
		blurLink: true,
		duration: 'normal',
		transition: 'linear',
		onZoomInStart: $empty,
		//onZoomInStart: function(){},
		onZoomInComplete: $empty,
		//onZoomInComplete: function(){},
		onZoomOutStart: $empty,
		//onZoomOutStart: function(){},
		onZoomOutComplete: $empty,
		//onZoomOutComplete: function(){},
		waitIcon: 'wait.gif',
		errorIcon: 'error.png'
	},
	
	initialize: function(selector, options){
		if(!$chk(options)) options = this.options;
		this.setOptions(options);
		this.id = 1;
		this.selector = $pick(selector, 'byzoomer');
		this.links = $$('.' + this.selector);
		this.previewElements = $H();
		this.infoElements = $H();
		this.largeElements = $H();
		this.pleaseWait = new Element('div', {
			styles: {
				zIndex: 10,
				position: 'absolute',
				opacity: 0.8,
				backgroundColor: '#ffffff',
				border: '1px solid #707070',
				backgroundImage: 'url(' + this.options.waitIcon + ')',
				backgroundRepeat: 'no-repeat',
				backgroundPosition: 'center center'
			}
		});
		
		this.links.each(function(link){
			this.prepareLink(link);
		}, this);
	},
	
	prepareLink: function(link){
		var id = this.selector + 'Elm' + this.id++;
		var preview = link.getElement('img');
		if(!preview)
			preview = link;

		var info = null;
		link.get('class').split(' ').each(function(styleClass){
			if(styleClass.contains('info\[')) {
				info = $(eval(styleClass.replace('info',''))[0]);
			}
		});
		//var info = link.getElement('span');
		if(info) {
		//if(info && info.getPrevious() != document.body) {
			//var clone = info.clone();
			//info.dispose();
			//info = clone;
			document.body.adopt(info);
		}
		this.previewElements[id] = preview;
		this.infoElements[id] = info;
		this.largeElements[id] = $H({
			element: null,
			loaded: false,
			width: 0,
			height: 0,
			src: link.get('href')
		});

		document.addEvent('click', function(link){
			this.unzoom(this.zoomed);
		}.bind(this));
		
		link.addEvent('click', function(evt, link){
			new Event(evt).stop();
			document.fireEvent('click', this);
			this.zoom(id);
			if(this.options.blurLink) link.blur();
		}.bindWithEvent(this, link));
	},
	
	loadLarge: function(id){
		this.largeElements[id].loaded = true;
		
		this.pleaseWait.setStyles({
			width: this.previewElements[id].getWidth() - 2,
			height: this.previewElements[id].getHeight() - 2,
			top: this.getPosition(this.previewElements[id]).y,
			left: this.getPosition(this.previewElements[id]).x
		});
		
		$(document.body).adopt(this.pleaseWait);
		
		this.largeElements[id].element = new Asset.image(this.largeElements[id].src, {
		//this.largeElements[id].element = new Asset.image('/public/img/productos/CATESPNAC/frontal/es003010.jpg', {
			id: id,
			onerror: function(){
				this.pleaseWait.dispose();
				this.setError(id);
			}.bind(this),
			onload: function(large){
				this.pleaseWait.dispose();
				if(!large.width)
					this.setError(id);
				else
				{
					this.largeElements[id].extend({
						width: large.width,
						height: large.height
					});
					this.zoom(id);
				}
			}.bind(this)
		}).setStyles({
			//'border': '3px ridge',
			'z-index': 999//Se corresponde con el valor zUpper de interflora.css
		});
		
		this.largeElements[id].element.set('morph', {
			duration: this.options.duration,
			transition: this.options.transition
		});
	},
	
	zoom: function(id){
		
		if(!this.largeElements[id].loaded) {
			this.loadLarge(id);
			return;
		}
		
		if($(id))
			return;
		
		this.zoomed = id;
		
		this.largeElements[id].element.setStyles({
			position: 'absolute',
			opacity: 0,
			width: this.previewElements[id].getWidth(),
			height: this.previewElements[id].getHeight(),
			top: this.getPosition(this.previewElements[id]).y,
			left: this.getPosition(this.previewElements[id]).x
		});

		$(document.body).adopt(this.largeElements[id].element);

		this.fireEvent('onZoomInStart', this);
		this.makeWraper();
		this.largeElements[id].element.get('morph').start({
			opacity: 1,
			width: (this.largeElements[id].width * this.options.zoom),
			height: (this.largeElements[id].height * this.options.zoom),
			left: window.getScroll().x + (window.getWidth() - this.largeElements[id].width) / (2 * this.options.zoom),
			top: window.getScroll().y + (window.getHeight() - this.largeElements[id].height) / (2 * this.options.zoom)
		}).chain(function(){
			this.makeInfo(id);
			this.makeClose(id);
			this.fireEvent('onZoomInComplete', this);
		}.bind(this));
	},
	
	unzoom: function(id){
		if(!id)
			return;
		
		this.zoomed = false;
		this.fireEvent('onZoomOutStart', this);
		this.disposeWraper();
		this.disposeInfo(id);
		this.disposeClose();
		this.largeElements[id].element.get('morph').start({
			opacity: 0,
			width: this.previewElements[id].getWidth(),
			height: this.previewElements[id].getHeight(),
			left: this.getPosition(this.previewElements[id]).x,
			top: this.getPosition(this.previewElements[id]).y
		}).chain(function(){
			this.largeElements[id].element.dispose();
			this.fireEvent('onZoomOutComplete', this);
		}.bind(this));
	},
	
	setError: function(id){
		var error = this.pleaseWait.clone();
		error.setStyles({
			backgroundColor: '#ffd0d0',
			backgroundImage: 'url(' + this.options.errorIcon + ')',
			width: this.previewElements[id].getWidth() - 2,
			height: this.previewElements[id].getHeight() - 2,
			left: this.getPosition(this.previewElements[id]).x,
			top: this.getPosition(this.previewElements[id]).y
		});

		$(document.body).adopt(error);
	},
	
	getPosition: function(element) {
		if (!Browser.Engine.trident) return element.getPosition();
		var b = element.getBoundingClientRect(), html = element.getDocument().documentElement;
		return {
			x: b.left + html.scrollLeft - html.clientLeft,
			y: b.top + html.scrollTop - html.clientTop
		};
	},

	makeWraper: function() {
		var height = document.documentElement.scrollHeight;
		var width = document.documentElement.scrollWidth;
		height = height < document.getCoordinates().height? document.getCoordinates().height: height;
		width = width < document.getCoordinates().width? document.getCoordinates().width: width;
		this.contenedor= new Element('div', {
			id: 'contenedorZoom',
			styles: {
				background: '#000',
				position: 'absolute',
				opacity: 0,
				zIndex:998,//Se corresponde con el valor zUpper -1 de interflora.css
				left: 0,
				top: 0,
				height: height,
				width: width,
				morph: {
						duration: this.options.duration,
						transition: this.options.transition
					}
			}
		});
		$(document.body).adopt(this.contenedor);
        this.contenedor.get('morph').start({
			opacity: 0.75
		});
	},

	makeInfo: function(id) {
		if(!this.infoElements[id])return;
		this.infoElements[id].addClass('infoProducto');
		this.infoElements[id].setStyles({
			position: 'absolute',
			display: 'inline',
			zIndex:999,//Se corresponde con el valor zUpper de interflora.css
			left: window.getScroll().x + (window.getWidth() - this.largeElements[id].width) / (2 * this.options.zoom) + (this.largeElements[id].width * this.options.zoom),
			top: (window.getScroll().y + (window.getHeight() - this.largeElements[id].height) / (2 * this.options.zoom))
		});

		if((this.infoElements[id].getSize().y) < (this.largeElements[id].height * this.options.zoom) ) {
        	this.infoElements[id].setStyles({
				height: (this.largeElements[id].height * this.options.zoom)
			});
        }

        var infoAux = new Element ('div', {
			id: id + 'Aux',
			styles: {
				position: 'absolute',
				display: 'inline',
				background: '#FFF',
				zIndex:998,//Se corresponde con el valor zUpper -1 de interflora.css
				left: window.getScroll().x + (window.getWidth() - this.largeElements[id].width) / (2 * this.options.zoom),
				top: (window.getScroll().y + (window.getHeight() - this.largeElements[id].height) / (2 * this.options.zoom)),
				width: (this.largeElements[id].width * this.options.zoom),
				height: this.infoElements[id].getSize().y
			}
		});
		document.body.adopt(infoAux);
	},

	makeClose: function(id) {
		document.body.adopt(
			new Element('img', {
				id: 'byzoomerClose',
				src: '/restyling/img/obj/close2.gif',
				alt: 'Cerrar',
                width: 20,
                height: 20,
				styles: {
					position: 'absolute',
					display: 'inline',
					/*
					Posicionamiento del botón de cierre a la izquierda
					left: (window.getScroll().x + (window.getWidth() - this.largeElements[id].width) / (2 * this.options.zoom)) + 5,
					top: (window.getScroll().y + (window.getHeight() - this.largeElements[id].height) / (2 * this.options.zoom)) + 5,
					*/
					left: (this.infoElements[id].getCoordinates().left + this.infoElements[id].getCoordinates().width - 25),
					top: (this.infoElements[id].getCoordinates().top + 5),
					zIndex:999,//Se corresponde con el valor zUpper de interflora.css
					cursor: 'pointer'
				}
			})
		);
	},

	disposeWraper: function(){
        this.contenedor.get('morph').start({
			opacity: 0
		}).chain(function() {
			this.contenedor.dispose();
		}.bind(this));
	},

	disposeInfo: function(id) {
		if(!this.infoElements[id])return;
		this.infoElements[id].setStyles({
			display: 'none'
		});
		if($chk($(id + 'Aux')))$(id + 'Aux').dispose();
	},

	disposeClose: function() {
		if($('byzoomerClose')) $('byzoomerClose').dispose();
	}

});