window.onload = init;
var d=document;
var thread=null;


var imagenes = new Array(); //---- Tengo almacenado cada una de las imagenes
var imageDimensions = new Array();//---- Dimension de cada una de las imagenes(inicialmente 32x32)
var PosInicialImagenes = new Array(); //--- Poscion de la imagen en la matriz de imagnes=posicion inicial
var imageCoordinates = new Array(); //--- coordenadas de las imagenes
var TrayectoriaImagenes = new Array();//---- Trayectoria que sigue la imagen para llegara a su destino 
var incHincWporStep = new Array();//--- Guarda para cada instante de la trayectoria cuanto ha de ir creciendo o decreciendo
                                //--- la imagen en anchura y altuta 				
var currentOpacity = new Array();//---- determina la opacidad para cada una de las imagenes 
var animationIndex = new Array();//---- indica que imagen esta animada y cual no


var activeImage=-1;//----- Imagen activa, es decir la que se ve en grande, inicialmente no hay ninguna--> -1 
var prevImage=-1; //----- Hemos activado una imagen, y una ya se estaba visuzalizsndo y ha de volver a su
                  //----- lugar en la matriz, esta es la prevImage
 

var useOpacity=1; 	
var iSpeed=6;				
var isAnimated=0;				

//---------------------------------
//---- CON ESTAS VARIABLES GENERAREMOS UNA MATRIZ
//---- DE IMAGENES, las que se ven en pequeño
var NUM_IMAGENES=11;
var NUM_IMAGS_POR_FILA=3;			
var TAM_IMG_PEQUE=32;
var SEPARACION_IMGS=5;  
//-----------------------------------
//---- IMAGEN EN GRANDE--------------
var ANCHURA_IMG=226;		
var ALTURA_IMG=164;		
//-----------------------------------			
//---- ME DA EL PUNTO A DONDE SE HA DE TRASLADAR LA IMAGEN(esquina superior izquierda)
var DEST_Y=184;
var DEST_X=265;

var DEFAULT_CAPTION=""
/************************************************************************************************************************/
/*********************INICIALIZO TODOS LOS ARRAYS NECESARIOS PARA LA ANIMACION*******************************************/
/************************************************************************************************************************/
/************************************************************************************************************************/
function init() {
	if(!document.getElementById)return;	
	inicializaMatrizImagenes();			
	inicializaVectoresDesplazamientosImagenes();			
	cambiosTamPorStep();			
}

function inicializaMatrizImagenes() {
	x=0; y=0; i=0; z=0;
	// set the default caption up
	//d.getElementById("caption").innerHTML = DEFAULT_CAPTION;
	// loop over how many images we have to deal with
	while(i<NUM_IMAGENES) {
		// Nos creamos un vector imagenes  que contiene todas las imágenes
		//--- Las imagnes se nuemeran image0 image1  ...... imageN  (siendo N=NUM_IMAGENES)
		if(!imagenes[i])imagenes[i]=d.getElementById("m"+i);

		// --- Se iarn colocando las imagnes primero por filas(hasta 
		//imagenes[i].style.left = x + "px";
		//imagenes[i].style.top = y + "px";
         x=d.getElementById("m"+i).style.left;
         y=d.getElementById("m"+i).style.top;
		//---- SELECCION AL CLIKEAR LA IMAGEN--------------------
		imagenes[i].xid=i;
		imagenes[i].onMouseOver=function(){animate(this.xid)}
        //--------------------------------------------------------   
		// Almaceno la posición inicial de la imagen
		//-- q corresponde a la esquina superior izquierda
		if(!PosInicialImagenes[i])PosInicialImagenes[i]=new Array(x,y);

		// Incremento la x para la siguiente coordena
		x+=TAM_IMG_PEQUE+SEPARACION_IMGS;

		//Coordenada de la imagen
		imageCoordinates[i]=new Array(x,y);

		// Dimensiones iniciales de la imagen
		imageDimensions[i] = new Array(32,32);

		// Opacidad de la imagen al 50%. 50 explorer  .5 Mozilla
		currentOpacity[i]=document.all?50:.5;
	
		// pongo a 0 las animaciones de cada una de las imágenes
		animationIndex[i]=0;

		// Compruebo si ya he rellenado la fila. Si es asi paso a lasiguiente fila
		z++;
		if(z>=NUM_IMAGS_POR_FILA) {
			x=0; z=0;
			y+=TAM_IMG_PEQUE+SEPARACION_IMGS;
		}
		i++;
	}
}

function inicializaVectoresDesplazamientosImagenes() {
	// Inicializa el vector desplazamiento , que guia la trayectoria de cada una de las imagenes
	for(i=0;i<PosInicialImagenes.length;i++)TrayectoriaImagenes[i] = plotCourse(DEST_X,DEST_Y,PosInicialImagenes[i][0],PosInicialImagenes[i][1]);
}

function cambiosTamPorStep() {
	// initialize the step increments for the width and height changes.
	for(i=0;i<TrayectoriaImagenes.length;i++) {
		wStep = Math.round(TrayectoriaImagenes[i].length/iSpeed);
		wStep = Math.round(ANCHURA_IMG/wStep);
		hStep = Math.round(TrayectoriaImagenes[i].length/iSpeed);
		hStep = Math.round(ALTURA_IMG/hStep);
	
		incHincWporStep[i]=new Array(wStep,hStep);
	}
}
/************************************************************************************************************************/
/************************************************************************************************************************/
/************************************************************************************************************************/
/************************************************************************************************************************/
//--- Lanzar el hilo de animación (thread)
function animate(index) {
	//--- Si ya hay un thread lanzado ya no lanza otro
	if(thread)return;

	if(activeImage==-1)prevImage=-1;
	//---- PULSO SOBRE LA IMAGEN MOSTRADA EN GRAMDE
	if(index==activeImage) {
		prevImage=activeImage;
		imagenes[activeImage].style.zIndex=100; 
		activeImage=-1;	
	} else {
		//---- PULSO UNA IMAGEN NUEVA A LA ACTIVA
		if(activeImage>-1)prevImage=activeImage;
		activeImage=index;
		imagenes[activeImage].style.zIndex=100;//--- La imagen activa va por encima
		if(prevImage>-1)imagenes[prevImage].style.zIndex=1;//---- Y la que retiro va por debajo
	}
     //---- prevImage:   Imagen que retiro
	 //---- activeImage: Imagne que muestro 
	
	//--- Lanzo el thread
	thread = setInterval("MostrarImagen()",NUM_IMAGENES);//--- Llamando a MostrarImagen()
}

function setImagePosition(index) {
	// set the positions and width of the images. These can fall out of range, hence the try/catch statement
	try {
		imagenes[index].style.top = TrayectoriaImagenes[index][animationIndex[index]][1]+"px";
		imagenes[index].style.left = TrayectoriaImagenes[index][animationIndex[index]][0]+"px";
		imagenes[index].style.width=imageDimensions[index][0]+"px";
		imagenes[index].style.height=imageDimensions[index][1]+"px";
	} catch(err) { }
}

function setImageOpacity(index) {
	// set the opacity of the object. Once for Gecko, once for Safari and once for MSIE.
	if(!useOpacity)return;
	imagenes[index].style.filter="alpha(opacity=" + currentOpacity[activeImage] + ")";
	imagenes[index].style.MozOpacity=currentOpacity[activeImage];
	imagenes[index].style.opacity=currentOpacity[activeImage];
}

//------------------------------------------------------------------------------------------------------------
//--------------  MostrarImagen: Muestra la activa y retira la previa
function MostrarImagen() {
    //--- HE SELECCIONADO UNA NUEVA IMAGEN 
 	if(activeImage>-1) {
		// set up its width,height,top and left
		setImagePosition(activeImage);
		// set up its opacity
		currentOpacity[activeImage]+=d.all?5:.05;
		setImageOpacity(activeImage);
		// if its width is less than 250, increase it. likewise with its height
		if(imageDimensions[activeImage][0]<ANCHURA_IMG)imageDimensions[activeImage][0]+= incHincWporStep[activeImage][0];
		if(imageDimensions[activeImage][1]<ALTURA_IMG)imageDimensions[activeImage][1]+= incHincWporStep[activeImage][1];
		//---- incremento el pado de animación
		animationIndex[activeImage]+=iSpeed;
	}

	// do the same as above for images returning to thumbnail size, only decrementing values this time
	if(prevImage>-1) {
		setImagePosition(prevImage);
		currentOpacity[prevImage]-=d.all?5:.05;
		setImageOpacity(prevImage);
		if(imageDimensions[prevImage][0]>32)imageDimensions[prevImage][0]-=incHincWporStep[prevImage][0];
		if(imageDimensions[prevImage][1]>32)imageDimensions[prevImage][1]-=incHincWporStep[prevImage][1];
		animationIndex[prevImage]-=iSpeed;
	}

	// has our animation finished?
	if(isFinished()) {
		// if activeImage is -1, we have no enlarged image. reset the animation index and put the default caption back in.
		if(activeImage==-1) {
			d.getElementById("caption").innerHTML = DEFAULT_CAPTION;
			animationIndex[prevImage]=0;
		}
		// we've got an active image.
		if(activeImage>-1) {
			// set the animation index to the length of TrayectoriaImagenes so we can start at the end of that array 
			// for when this image becomes a thumbnail again
			animationIndex[activeImage] = TrayectoriaImagenes[activeImage].length;
			// set the final top,left,width and height of the image, just in case they're off
			imagenes[activeImage].style.top=DEST_Y+"px";
			imagenes[activeImage].style.left=DEST_X+"px";
			imagenes[activeImage].style.width=ANCHURA_IMG+"px";
			imagenes[activeImage].style.height=ALTURA_IMG+"px";
			// set up the final opacity of the image if useOpacity is true
			if(useOpacity) {
				imagenes[activeImage].style.MozOpacity=.99;
				imagenes[activeImage].style.filter="alpha(opacity=100)";
				imagenes[activeImage].style.opacity=1.0;
			}
			//d.getElementById("caption").innerHTML = imagenes[activeImage].title;
		} 
		// do the same for the thumbnail image.
		if(prevImage>-1) {
			animationIndex[prevImage]=0;
			imagenes[prevImage].style.top = PosInicialImagenes[prevImage][1]+"px";
			imagenes[prevImage].style.left = PosInicialImagenes[prevImage][0]+"px";
			imagenes[prevImage].style.width="104px";
			imagenes[prevImage].style.height="68px";
			if(useOpacity) {
				imagenes[prevImage].style.MozOpacity=.5;
				imagenes[prevImage].style.filter="alpha(opacity=50)";
				imagenes[prevImage].style.opacity=.5;
			}
		}
		// Para la animación del thread
		clearInterval(thread);
		thread=null;
	}
}

// checks to see if the thumbnail and enlarged image are at their final positions
// by checking the animationIndex value against the length of the images TrayectoriaImagenes array.
function isFinished() {
	if(activeImage>-1 && prevImage>-1)if(animationIndex[activeImage]>=TrayectoriaImagenes[activeImage].length && animationIndex[prevImage]<=0) return true;
	if(activeImage>-1 && prevImage==-1) if(animationIndex[activeImage]>=TrayectoriaImagenes[activeImage].length)return true;
	if(activeImage==-1 && prevImage>-1) if(animationIndex[prevImage]<=0)return true;
	return false;
}

// this function simply resets the opacity of the objects when the check box is clicked.
function disableOpacity(bool) {
	if(bool) {
		useOpacity=0;
		for(i=0;i<imagenes.length;i++) {
			imagenes[i].style.MozOpacity=1.0;
			imagenes[i].style.opacity=1.0;
			imagenes[i].style.filter="alpha(opacity=100)";
		}
	} else {
		location.reload();
	}
}
//Calcula la trayectoria para ir de un punto a otro
//--- (fX,fY): destino
//---  (oX,oY):origen  
function plotCourse(fX,fY,oX,oY) {

	dx = Math.abs(fX-oX);
	dy = Math.abs(fY-oY);
	max = dx > dy ? dx : dy;
	x_inc = dx / max;
	y_inc = dy / max;

	Xp = oX
	Yp = oY;

	path = new Array();
	pathCount = 0;

	if(fX>oX && fY > oY) {
		if(oX<fX && oY<fY) {
			while (Xp < fX) {
				nextX = Math.round(Xp);
				nextY = Math.round(Yp);
				path[pathCount] = new Array(nextX,nextY);
				pathCount++;
				Xp += x_inc;
				Yp += y_inc;
			}
		} else {
			while (Xp > fX) {
				nextX = Math.round(Xp);
				nextY = Math.round(Yp);
				path[pathCount] = new Array(nextX,nextY);
				pathCount++;
				Xp -= x_inc;
				Yp += y_inc;
			}		
		}	
	} else {
		if(oX<fX && oY>fY) {
			while (Xp < fX) {
				nextX = Math.round(Xp);
				nextY = Math.round(Yp);
				path[pathCount] = new Array(nextX,nextY);
				pathCount++;
				Xp += x_inc;
				Yp -= y_inc;
			}
		} else {
			while (Xp > fX) {
				nextX = Math.round(Xp);
				nextY = Math.round(Yp);
				path[pathCount] = new Array(nextX,nextY);
				pathCount++;
				Xp -= x_inc;
				Yp -= y_inc;
			}
		}
	}
	return path;
}

