/********************************************************************************
 *
 * Componentes utilizables con JQuery: Clases Desplazables, Galeria y SliderManager y objeto FancyboxWH
 *
********************************************************************************/


/**************************************** Div desplazable ****************************************
 * Presenta un div largo dentro de un contenedor más estrecho y utiliza dos elementods clickables para desplazar el contenido horizontalmente
 *
 * Hay que crear:
 *	- Un elemento con clase "desplazable"
 *	- Dos elementos con el mismo tipo que el desplazable
 *	- Estos dos elementos tienen que ser "siblings" del desplazable y tener las clases desplazar-anterior y desplazar-siguiente
 *
 * Ejemplo de html:
 *
<li class="desplazar-anterior">
	<a href="#">
		<img src="img/flecha_atras.gif" />
	</a>
</li>
<li>
<div class="desplazable">
... contenido ...
</div>
</li>
<li class="desplazar-siguiente">
	<a href="#">
		<img src="img/flecha_siguiente.gif" />
	</a>
</li>

 *
 * Utilización javascript (además de referenciar ui.js):
 *	var desplazables = new Desplazables();
 *		desplazables.init();
 * O bien, se puede construir el objeto pasando valores diferentes para las opciones utilizando JSON
 * Las opciones y sus valores por defecto son:
 *		desplazable: 'desplazable',
 *		anterior: 'desplazar-anterior',
 *		siguiente: 'desplazar-siguiente'
 *
 * Ejemplo de constructor pasando opciones (no es necesario pasar todas las opciones, sólo las que se quieren cambiar):
 * 	var desplazables = new Desplazables({
 * 		desplazable: 'mi-clase-desplazable',
 * 		anterior: 'mi-clase-desplazar-anterior',
 * 		siguiente: 'mi-clase-desplazar-siguiente'
 * 	});
 * 	desplazables.init();
 * 
 *
*/
function Desplazables(opts) {
	this.defaults = {
		desplazable: 'desplazable',
		anterior: 'desplazar-anterior',
		siguiente: 'desplazar-siguiente'
	};
	this.desplazable = this.defaults.desplazable;
	this.anterior = this.defaults.anterior;
	this.siguiente = this.defaults.siguiente;
	if (opts) {
		if (opts.desplazable != 'undefined') this.desplazable = opts.desplazable;
		if (opts.anterior != 'undefined') this.anterior = opts.anterior;
		if (opts.siguiente != 'undefined') this.siguiente = opts.siguiente;
	}
	var $desplazable = $('.' + this.desplazable);
	var $this = $(this);
	if ($desplazable.length == 0) {
		return;
	}
	this.elemento = $desplazable.parent().get(0).nodeName.toLowerCase();
	var maxHeight = 0;
	var totalWidth = 0;
	$desplazable.children().each(function(index) {
		$this = $(this);
		var h = parseInt($this.height());
		var t = parseInt($this.css('padding-top'));
		var b = parseInt($this.css('padding-bottom'));
		h += (t + b);
		if (h > maxHeight) {
			maxHeight = h;
		}
		var w = parseInt($this.width()) + parseInt($this.css('padding-left')) + parseInt($this.css('padding-right'));
		totalWidth += w;
	});
	$desplazable.height(maxHeight);
	$desplazable.width(totalWidth);
}
Desplazables.prototype = {
	init: function() {
		var elDesplazable = this;
		var desps = '.' + this.desplazable;
		var $desps = $(desps);
		$desps.each(function(index) {
			var $this = $(this);
			var leftDesplazable = $this.position().left;
			var rightDesplazable = (parseInt( $this.width()) - $this.position().left ) * -1;
			var $elElemento = $this.closest(elDesplazable.elemento);
			var ancho = $elElemento.width();
			var $ant = $elElemento.siblings('.' + elDesplazable.anterior);
			var $sig = $elElemento.siblings('.' + elDesplazable.siguiente);
			$ant.click(function() {
				return elDesplazable.clickDesplazar($(this), false, leftDesplazable, rightDesplazable, ancho);
			});
			$sig.click(function() {
				return elDesplazable.clickDesplazar($(this), true, leftDesplazable, rightDesplazable, ancho);
			});
		});

	},
	clickDesplazar: function($linkDesplazar, avanzar, leftDesplazable, rightDesplazable, ancho) {
	var $desplazable = $linkDesplazar.parent().find('.' + this.desplazable);
	var curLeft = parseInt($desplazable.position().left);
	var nextLeft = (avanzar ? curLeft - ancho : curLeft + ancho);
	if (avanzar) {
		if (nextLeft > rightDesplazable) {
			$desplazable.animate({
				left: "-=" + ancho + "px"
			}, "normal");
		}
	} else {
		if (curLeft < leftDesplazable) {
			$desplazable.animate({
				left: "+=" + ancho + "px"
			}, "normal");
		}
	}
	return false;

}

};

/**************************************** FINAL Div desplazable ****************************************/

/**************************************** Galeria inline con Anterior/Siguiente ****************************************/
/*
 *
 * Se crea un div que contenga solamente tres elementos:
 * 1. un elemento con clase "anterior". Si el elemento NO es <a>, debe contener un elemento de tipo <a> en el interior
 * 2. Una div que contenga otros divs con las imágenes de la galería. Estos divs deben tener atributo id
 * 3. un elemento con clase "siguiente". Si el elemento NO es <a>, debe contener un elemento de tipo <a> en el interior
 *
 * No es necesario que los ids de los elementos con imagen estén relacionados, pero sí es obligatorio que tengan id
 * La clase Galeria se encarga de poner los href a los elementos anterior/7/siguiente
 *
 * Ejemplo:
<a class="anterior" href="#">
	<img src="/buff/img/flecha_atras.gif" alt="flecha_atrás" />
</a>
<div>
	<div id="lo-que-sea" >
		<img class="gráfica" src="xxxx.jpg" alt="" />
	</div>
... otros divs
</div>
<a class="siguiente" href="#">
	<img src="/buff/img/flecha_siguiente.gif" alt="flecha_siguiente" />
</a>
 *
*/
function Galeria() {

}
Galeria.prototype = {
	init: function() {
		var laGaleria = this;
		var $ant = $('.anterior');
		if ($ant.length == 0) {
			return;
		}
		$ant.find('img').css('z-index', 3000);
		var $linkAnt = $ant;
		if ($ant.length > 0 && $ant.get(0).tagName.toLowerCase() != 'a') {
			$linkAnt = $ant.find('a').first();
		}
		var $imagenes = $linkAnt.parent().children().not('.anterior').not('.siguiente').children();
		if ($imagenes < 2) { // No tiene sentido anterior/siguiente si no hay imágenes o sólo hay una
			return;
		}
		var $sig = $('.siguiente');
		$sig.find('img').css('z-index', 3000);
		var $linkSig = $sig;
		if ($sig.length > 0 && $sig.get(0).tagName.toLowerCase() != 'a') {
			$linkSig = $sig.find('a').first();
		}
		var hrefAnt = '#' + $imagenes.get($imagenes.length - 1).id;
		var hrefSig = '#' + $imagenes.get(1).id;
		$linkAnt.attr('href', hrefAnt);
		$linkSig.attr('href', hrefSig);
		$ant.click(function(e) {
			laGaleria.clickAnteriorSiguiente($(this));
			return false;
		});
		$sig.click(function(e) {
			laGaleria.clickAnteriorSiguiente($(this));
			return false;
		});


	},
	clickAnteriorSiguiente: function($elemento) {
// Mirar si el elemento $link es de typo <a>. Si no, buscar su primer hijo de tipo <a>
		var $link = $elemento;
		if ($elemento.get(0).tagName.toLowerCase() != 'a') {
			$link = $elemento.find('a').first();
		}
		if ($link.attr('href') == '' || $link.attr('href') == '#') {
			return;
		}

// Buscar las imágenes (o divs con imágenes: son los hijos del elemento sibling de anterior y siguiente
		var $imagenes = $link.parent().children().not('.anterior').not('.siguiente').children();
		if ($imagenes < 2) { // No tiene sentido anterior/siguiente si no hay imágenes o sólo hay una
			return;
		}
		var avanzar = true;
		if ($elemento.hasClass('anterior')) {
			avanzar = false;
		} else if ($elemento.hasClass('siguiente')) {
			avanzar = true;
		}

// Buscar posición del elemento que se va a mostrar dentro de las imágenes
		var idElementoMostrar = $link.attr('href');
		var pos = idElementoMostrar.indexOf('#');
		if (pos < 0) {
			return;
		}
		var $mostrar = $(idElementoMostrar);
		var idxMostrar = 0;
		for (var i = 0; i < $imagenes.length; i++) {
			if(('#' + $imagenes.get(i).id) == idElementoMostrar) {
				idxMostrar = i;
			}
		}

// Buscar posición del elemento visible (será el anterior o siguiente al que se va a mostrar, según qué link se haya clickado)
		var idxActual = -1;
		if (avanzar) {
			idxActual = idxMostrar - 1;
		} else {
			idxActual = idxMostrar + 1;
		}
		if (idxActual < 0) {
			idxActual = $imagenes.length - 1;
		} else if (idxActual >= $imagenes.length) {
			idxActual = 0;
		}

		var $actual = $imagenes.eq(idxActual);
		$actual.css('z-index', 2001);
		$actual.css('opacity', 1);
		$mostrar.css('z-index', 2000);
		$mostrar.css('opacity', 1);

		var $laGaleria = this;
		$actual.animate({
			opacity: 0
		}, 1000, function() {
// Animation completa: poner hrefs del anterior/siguiente
			$laGaleria.actualizarLinks(idxMostrar, $imagenes);
		});

	},
	actualizarLinks: function(idxMostrar, $imagenes) {
// Buscar posición del elemento anterior y del siguiente al que se va a mostrar
		var idxNext = idxMostrar + 1;
		var idxPrev = idxMostrar - 1;
		if (idxNext >= $imagenes.length) {
			idxNext = 0;
		}
		if (idxPrev < 0) {
			idxPrev = $imagenes.length - 1;
		}
		var $linkPrev = $('.anterior');
		if ($linkPrev.get(0).tagName.toLowerCase() != 'a') {
			$linkPrev = $linkPrev.find('a').first();
		}
		$linkPrev.attr('href', '#' + $imagenes.get(idxPrev).id);

		var $linkNext = $('.siguiente');
		if ($linkNext.get(0).tagName.toLowerCase() != 'a') {
			$linkNext = $linkNext.find('a').first();
		}
		$linkNext.attr('href', '#' + $imagenes.get(idxNext).id);

	}

};
/**************************************** FINAL Galeria inline con Anterior/Siguiente ****************************************/

/**************************************** Fancybox con ancho configurable ****************************************/
/* Crea un fancybox con width/height diferentes a los valores por defecto  utilizando la clase fancyWWWxHHH,
 * donde WWW es el ancho y HHH el alto. Por ejemplo: la clase fancy836x528 crea un fancybox con ancho 836 y alto 528
*/
var FancyboxWH = {
	init: function() {
		$('a').filter('[class*=fancy]').not('[class=fancy]').each(function() {
			var t = '';
			var pos = this.className.indexOf('fancy');
			if (pos < 0) {
				return;
			}
			t = this.className.substring(pos + 5);
			pos = t.indexOf(' ');
			if (pos > 0) {
				t = t.substring(0, pos);
			}
			if (t == '') {
				return;
			}
			var w = -1;
			var h = -1;
			var wh = t.split('x');
			if (wh.length == 2) {
				w = wh[0];
				h = wh[1];
			}
			w = parseInt(w);
			h = parseInt(h);
			if ( w > 0 && h > 0) {
	// Modificar el z-index perque la galeriaHome tapa el video
				$(this).fancybox(
					{'width': w, 'height': h,
						'onStart': function() {
							$('#fancybox-wrap').css('z-index', '4000');
						}
				});
			}
		});
	}

};

/**************************************** FINAL Fancybox con ancho configurable ****************************************/


/**************************************** Clase Slider ****************************************
 *
 * Presenta "diapositivas" con texto asociado opcional
 *
 * Utilización javascript
 *
 *	var sliderManager = new SliderManager($('#fotos-empresa'), 'timeout'); // se puede poner click en lugar de timeout para activar la transición con click
 *	sliderManager.init();
 *  
 * Html de ejemplo sin textos:
 *
 *<div id="fotos-empresa">
 *	<img class="active" src="img/unaImagen.jpg"  />
 *	<img src="img/otraImagen.jpg"  />
 *</div>
 *
 * Html de ejemplo con textos:
 *
 *<div id="fotos-empresa">
 *	<img class="active" src="img/unaImagen.jpg"  />
 *	<input type="hidden" value="texto asociado con imagen anterior">
 *	<img src="img/otraImagen.jpg"  />
 *	<input type="hidden" value="texto asociado con imagen anterior">
 *</div>
 *<div class="slide-texto" ></div>
 *
*/
function SliderManager($elementos, tipoTransicion) {
	this.elementos = $elementos;
	this.trigger = tipoTransicion;
}
SliderManager.prototype = {
	init: function() {
		var transicion = this.trigger;
		this.elementos.each(function(index) {
			var slider = new Slider($(this), transicion);
			slider.init();
		});
	}
};
function Slider($divContenedor, tipoTransicion) {
	this.defaultTimeoutMilis = 3000;
	this.currentSlide = 0;
	this.timeoutSlides = 0;
	this.txtElem = null;
	this.currentImagenesSlide = new Array();
	this.divContenedor = $divContenedor;
	this.trigger = tipoTransicion;
}
Slider.prototype = {
	init: function() {
		var theSlider = this;
		this.currentImagenesSlide = this.divContenedor.find('img');
		this.txtElem = this.divContenedor.siblings('.slide-texto');
		if (this.trigger == 'timeout') {
			this.currentSlide = 0;
			setTimeout(function () {
				doSliderTimeout(theSlider);
			}, this.defaultTimeoutMilis);
		} else if (this.trigger == 'click') {
			this.currentImagenesSlide.each(function(idx) {
				$(this).click(function() {
					if (theSlider.timeoutSlides) {
						clearTimeout(theSlider.timeoutSlides);
					}
					theSlider.currentSlide = idx;
					theSlider.doSlideSwitch();
				});
			});
		}

	},
	doSlide: function() {
		var theSlider = this;
		if (this.currentSlide < this.currentImagenesSlide.length) {
			this.doSlideSwitch();
			this.currentSlide++;
			this.timeoutSlides = setTimeout(function () {
				doSliderTimeout(theSlider);
			}, this.defaultTimeoutMilis);
		} else {
			if (this.timeoutSlides) {
				clearTimeout(this.timeoutSlides);
				this.currentSlide = 0;
			}
		}
	},
	doSlideSwitch: function() {
		var txt = '';
		var $active = this.divContenedor.find('img.active');
		if ( $active.length == 0 ) $active = this.divContenedor.find('img:last');
		var $nextImg =  $active.next();
		if ($nextImg.length > 0 && $nextImg.get(0).tagName.toLowerCase() == 'input') {
			$nextImg =  $nextImg.next();
		}
		if ($nextImg.length == 0) {
			$nextImg = this.divContenedor.find('img:first');
		}
		this.animarSlide($active, $nextImg);
		if (this.txtElem.length > 0) {
			var $nextInput = $nextImg.next();
			if ($nextInput.length > 0 && $nextInput.get(0).tagName.toLowerCase() == 'input') {
				txt = $nextInput.val();
			}
			this.txtElem.animate({opacity: 0.0}, 500, function() {
				$(this).html(txt);
			})
			.animate({opacity: 1.0}, 500, function() {
			});
		}
	},
	animarSlide: function($active, $next) {
		$active.addClass('last-active');
		$next.css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, 1000, function() {
				$active.removeClass('active last-active');
			});
	}

};

function doSliderTimeout(theSlider) {
	theSlider.doSlide();
}

