/**
 * Revistas - Galeria/Slideshow Revistas RBA
 *
 * @ejemplo
 *
 *	window.addEvent('domready', Revistas.init);
 *
 * @version		1.2.1
 *
 * @autor		Luis Merino <luis [at] scopealley.com>
 */
var Revistas = window.retrieve('Revistas', {});

/**
 * @propiedad {stack} Lote de elementos revista que se está mostrando
 */
Revistas.stack = [];

/**
 * Constructor - init
 */
Revistas.init = function() {
	var z = 1000;
	//IE z-index bug, asignamos valores descendentes de z-index a cada elemento
	if (Browser.Engine.trident) $$('#contenido-productos li').each(function(el, index) {
		el.setStyle('z-index', z - index);
	});
	var coleccion = $$('#contenido-productos li') || [];
	if (!coleccion.length) return false;
	var links = $$('#seleccion-productos li a').addEvent('click', function() {
		links.getParent().removeClass('seleccionado');
		this.getParent().addClass('seleccionado');
		Revistas.change.call(coleccion, this.id || null);
		return false;
	});
	$$('#contenido-productos li a[href]').addEvent('mouseenter', function(){
		visor = this.getElement('span.contenedor-visor');
		//Revistas.reposition.call(visor);
		if (!Browser.Engine.trident) Revistas.reposition.call(visor);
	});
	Revistas.change.call(coleccion, null);
	Revistas.viewer.init();
};

/**
 * Recoloca el elemento div.visor cuando el ratón está encima, para evitar que salga de los límites
 */
Revistas.reposition = function() {
	var EXTRA = 25; //CONST in pixels
	var wrapper = $('div-productos');
	var boundaries = wrapper.getSize();
	var coordinates = this.getCoordinates(wrapper);
	var offsetX = coordinates.right;
	var offsetY = coordinates.bottom;

	if ((offsetX - EXTRA) > boundaries.x) {
		var left = this.getStyle('left').toInt();
		this.setStyle('left', left - coordinates.width + EXTRA);
		this.store('originX', left);
	}
	if ((boundaries.y > coordinates.height) && (offsetY > boundaries.y + (coordinates.height / 2))) {
		var top = this.getStyle('top').toInt();
		this.setStyle('top', top - coordinates.height + EXTRA);
		this.store('originY', top);
	}
};

/**
 * Cambia el lote de revistas por tipo según los radio buttons de la barra superior
 *
 * @param {String} attributo rel, identificador para el tipo de lote/revistas
 */
Revistas.change = function(id) {
	Revistas.stack.empty();
	this.each(function(revista) {
		copy = revista.isMagazineCopy();
		if (id == null) {
			revista.setStyle('display', (copy) ? 'none' : 'block');
			if (!copy) {
				visor = revista.getElement('span.contenedor-visor');
				visor.setStyle('left', visor.retrieve('originX'));
				visor.setStyle('top', visor.retrieve('originY'));
				Revistas.stack.push(revista);
			}
		} else if (revista.getElement('a').get('rel') == id) {
			revista.setStyle('display', (copy) ? 'none' : 'block');
			if (!copy) {
				visor = revista.getElement('span.contenedor-visor');
				visor.setStyle('left', visor.retrieve('originX'));
				visor.setStyle('top', visor.retrieve('originY'));
				Revistas.stack.push(revista);
			}
		} else {
			revista.setStyle('display', (copy) ? 'block' : 'none');
		}
		if (!Revistas.stack.length) revista.setStyle('display', 'none');
	});
};

/**
 * Crea la cubierta semitransparente para el slideshow cuando este se encuentra activo
 *
 * @returns {Element} Devuelve un nuevo elemento Cover, crea una instancia
 */
Revistas.Cover = function() {
	if(!(wrapper = $('div-productos'))) return new Element('div');
	var size = wrapper.getSize();
	return new Element('div', {
		'styles': {
			'opacity': 0.85,
			'width': size.x,
			'height': size.y,
			'position': 'absolute',
			'z-index': 99,
			'background-color': '#ffffff',
			'left': 0, 'top': 0
		}
	}).set('tween', {property: 'opacity', duration: 300}).inject(wrapper, 'bottom');
};

/**
 * Objeto para crear, modificar y controlar el visor de revistas
 *
 * @method {init} - autoexplicativo
 * @method {nextImage} - autoexplicativo
 * @method {prevImage} - autoexplicativo
 * @method {loadImage} - pasa a la siguiente imagen en la carga, generando una nueva estructura de visor, instanciando la clase 'Revistas.Slideshow', (ver clase)
 *   ejemplo: $(new Revistas.Slideshow(nodo, recipiente)).replaces(recipiente);
 */
Revistas.viewer = {
	init: function() {
		this.cover = new Revistas.Cover().hide();
		
		var revistas = $$('#contenido-productos li a[href]').addEvent('click', function(){
			Revistas.viewer.cover.get('tween').start(0.85);
			this.addClass('mostrar');
			var node = this.getParent();
			Revistas.viewer.index = Revistas.stack.indexOf(node);
			var visor = $('visor-revista').set('tween', {property: 'opacity', duration: 400}).hide();
			var recipient = visor.getElement('div.contenido');
			$(new Revistas.Slideshow(node, recipient)).replaces(recipient);
			visor.get('tween').start(1);
			return false;
		});

		['nextImage', 'prevImage'].each(function(button){
			if (Browser.Engine.trident) {
				bt = $(button);
				src = bt.get('src');
				bt.set('src', src.substr(0, src.indexOf('.') + 1) + 'gif');
			}
			$(button).addEvents({
				'click': this[button].bind(this),
				'mouseover': function(){ this.setStyle('opacity', 0.75) },
				'mouseout': function(){ this.setStyle('opacity', 1) }
			});
		}.bind(this));
		
		document.addEvent('keydown', function(event){
			if(event.key == 'left') this.prevImage.bind(this)();
			else if(event.key == 'right') this.nextImage.bind(this)();
		}.bind(Revistas.viewer));
	},
	
	nextImage: function(){
		this.loadImage(this.index + 1);
	},
	
	prevImage: function(){
		this.loadImage(this.index - 1);
	},
	
	loadImage: function(index) {
		this.index = (index) % Revistas.stack.length;
		if (this.index < 0) this.index = Revistas.stack.length - 1;
		link = Revistas.stack[this.index].getElement('a');
		node = link.getParent();
		visor = $('visor-revista');
		recipient = visor.getElement('div.contenido');
		$(new Revistas.Slideshow(node, recipient)).replaces(recipient);
	}
};

/**
 * Revistas.Slideshow - Genera nuevos elementos visor con la estructura de una nueva revista
 *
 * @method {initialize} - Constructor
 *   @param {Element} - Elemento de la lista al que se toma referencia para construir la vista 
 *   @param {Element} - Elemento contenedor de lo que será el nuevo elemento
 * @method {close} - Genera el mecanismo para cerrar el visor
 *   ejemplo: $(new Revistas.Slideshow(nodo, recipiente)).replaces(recipiente);
 */
Revistas.Slideshow = new Class({
	
	toElement: function() {
		if (!this.element) {
			this.element = this.recipient.clone();
			var sources = [
				{
					'selector': this.source.getElement('span.visor img'),
					'fn': function(chld){ return this.clone(chld); }
				},
				{
					'selector': this.source.getElement('a'),
					'fn': function(){ return this.get('title'); }
				},
				{
					'selector': this.source.getElement('a'),
					'fn': function(){ return this.get('rel'); }
				},
				{
					'selector': this.source.getElement('div.descripcion'),
					'fn': function(){ return this.get('html'); }
				}
			];
			var recipients = [
				{
					'selector': this.element.getElement('div.revista img'),
					'fn': function(el){ return this.replaces(el); }
				},
				{
					'selector': this.element.getElement('div.interior h3'),
					'fn': function(el){ return el.set('html', this) }
				},
				{
					'selector': this.element.getElement('div.interior em'),
					'fn': function(el){ return el.set('text', this) }
				},
				{
					'selector': this.element.getElement('div.interior div'),
					'fn': function(el){ return el.set('html', this) }
				}
			];
			sources.each(function(el, index){
				var node = el.fn.run(false, el.selector);
				var spot = recipients[index].fn.run([recipients[index].selector], node);
			});
			this.element.getElement('div.cerrar img').addEvent('click', this.close.bind(this));
			document.addEvent('keydown', function(event){ if(event.key == 'esc') this.close(); }.bind(this));
		}
		return this.element;
	},
	
	initialize: function(source, recipient) {
		this.source = source;
		this.recipient = recipient;
	},
	
	close: function() {
		this.source.getElement('a').removeClass('mostrar');
		Revistas.viewer.cover.get('tween').start(0);
		$('visor-revista').get('tween').start(0);
	}
	
});

Element.implement({
	
	isMagazineCopy: function(){
		return this.getElement('a').hasClass('copia');
	},
	
	visible: function(){
		return this.getStyle('display') == 'none' || this.getStyle('visibility') == 'hidden' ? false : true;
	},
	
	show: function(){
		return this.setStyle('display', '').set('opacity', 1);
	},
	
	hide: function(collapse){
		return collapse ? this.setStyle('display', 'none') : this.set('opacity', 0);
	},
	
	toggle: function(collapse){
		return this.visible() ? this.hide(collapse) : this.show();
	}
	
});

window.addEvent('domready', Revistas.init);
