// JavaScript Document

jQuery.noConflict ();

var anchoStage;
var altoStage;
var anchoImagen = 1280;
var altoImagen = 720;
var imagenActual = 99;
var imagenesTotal = 11;
var vel = 600;

jQuery (document).ready (function () {
	imagenActual = 0;
	
	for (var i=0; i<imagenesTotal; i++) {
		var imagen = '<img src="media/bg_'+i+'.jpg" />';
		
		jQuery ('#fondo').append (imagen);
	}
	
	jQuery ('#works')
		.find ('.text').each (function (i) {
			jQuery (this)
				.hover (
					function () {
						activarLink (i);
					},
					function () {
						desactivarLink (i);
					});
		});
		
	jQuery (window).resize (function () {
		redimensionarImagenes ();
	});
	
	redimensionarImagenes ();
});

function activarLink (i) {
	cambiarImagen (i);
	
	jQuery ('#trama') 
		.stop().fadeTo (vel, 1);
	
	jQuery ('#logo')
		.stop().animate ({backgroundPosition: '0 -82px'}, vel);
	
	jQuery ('.text')
		.eq (i)
			.addClass ('text_hover');
};

function desactivarLink (i) {
	jQuery ('#fondo img')
		.eq (i)
			.stop().fadeTo (vel, 0);
			
	jQuery ('#trama') 
		.stop().fadeTo (vel, 0);
	
	jQuery ('#logo')
		.stop().animate ({backgroundPosition: '0 0'}, vel);
	
	jQuery ('.text')
		.eq (i)
			.removeClass ('text_hover');
};

function cambiarImagen (num) {
	jQuery ('#fondo img')
		.eq (imagenActual)
			.stop().fadeTo (vel, 0)
		.end()
		.eq (num)
			.stop().fadeTo (vel, 1)
		.end();
	
	imagenActual = num;
};

function redimensionarImagenes () {
	anchoStage = jQuery (window).width();
	altoStage = jQuery (window).height();
	
	var escX = anchoStage / anchoImagen;
	var escY = altoStage / altoImagen;
	
	var escala = (escX > escY) ? escX : escY;
	var ancho = anchoImagen * escala;
	var alto = altoImagen * escala;
	var posY = 0;
	var posX = 0;
	
	if (alto > altoStage) {
		posY = (altoStage - alto) / 2;
	}
	
	if (ancho > anchoStage) {
		posX = (anchoStage - ancho) / 2;
	}
	
	jQuery ('#fondo img').attr ({ 'width': ancho, 'height': alto});	
	jQuery ('#fondo img').css ({ top: posY, left: posX });
};
