
function Debug(sTexto)
{
	document.getElementById("tracer").innerHTML = document.getElementById("tracer").innerHTML + sTexto + "<br>";
}

var x_xmlDom = new Array;

var x_GaleriaCargada = new Array;

var x_creandoGaleria = false;

var x_cargando = false; // guardamos el estado actual del slide (si está en marcha o no)
var x_nTopHang = 0;     // guarda la posición del div que estamos moviendo para que compruebe que no está en un bucle

var x_nGalerias = 0;

function init(sXml,sObjGaleria)
{
	if (!x_creandoGaleria)
	{
		x_creandoGaleria = true;
		
		// ajustamos la galeria al width y height especificados
		//var objGaleria = document.getElementById("divGaleria");
		var objGaleria = document.getElementById(sObjGaleria);
		
		objGaleria.style.width = ((imgWidth + pixPadWidth) * galCols) + "px";
		objGaleria.style.height = ((imgHeight + pixPadHeight) * galRows) + "px";
		
		x_nGalerias = x_nGalerias + 1;
		// creamos el objeto XmlDom
		x_xmlDom[x_nGalerias]  = new XmlDom();
		
		x_GaleriaCargada[x_nGalerias] = false;
		//esta es la line original para que una vez cargado el XML ejecute una función en concreto
		//x_xmlDom[x_nGalerias].load("", sXml, x_xmlDomCompleted);
		//cuando termine que cargar el XML llamará a la función x_xmlDomCompleted, pero el problema
		//es que x_xmlDomCompleted es un parametro de la función load, y como ya es un parametro
		//no podemos volver a abrir un parentesis para crear un parametro dentro de la función x_xmlDomCompleted
		// ejemplo: esto NO funciona
		//				x_xmlDom[x_nGalerias].load("", sXml, x_xmlDomCompleted());
		//el simple hecho de que le pongamos () en la función.. hace que falle todo
		//por lo que la función a la que llamará despues de cargar el XML no puede tener parametros
		//la única forma de conseguir ponerle parametros a la función es poniendo lo siguiente
		//function() { nombre_funcion(parametros) }
		
		//x_xmlDom[x_nGalerias].load("", sXml, function() { x_xmlDomCompleted(x_nGalerias); });
		//x_xmlDom[x_nGalerias].load("", sXml, "function() { x_xmlDomCompleted(" + x_nGalerias + "); }");
		x_xmlDom[x_nGalerias].load("", sXml, "x_xmlDomCompleted(" + x_nGalerias + ");");
		
	}
	else
	{
		setTimeout('init("' + sXml + '","' + sObjGaleria + '")', 50);
		
	}
	
}

function x_xmlDomCompleted(nGaleria)
{
    cargaFotos(nGaleria);

	x_GaleriaCargada[nGaleria] = true;
	
	x_creandoGaleria = false;
	
}

// espera a que la galeria se halla cargado del todo y entonces lanza la función que queramos
function EsperaGaleria(sFuncion)
{
	var bGaleriasCargadas = true;
	for (i=1;i<=x_nGalerias;i++)
	{
		if (!x_GaleriaCargada[i]) bGaleriasCargadas = false;
	}
	if (bGaleriasCargadas)
		eval(sFuncion);
	else
		setTimeout("EsperaGaleria('" + sFuncion + "')", 50);
}

function cargaFotos(nGaleria)
{
	
    var nodes = x_xmlDom[nGaleria].object.documentElement.childNodes;
	
    var i;
    var objContenedor = document.getElementById("contImages" + nGaleria);
    var objDiv = document.getElementById("thumb" + nGaleria);
    var newDiv;
    var iContItem = 0;
	

    for (i=0;i<nodes.length;i++)
    {
        if (nodes[i].nodeName == "item")
        {
            iContItem = iContItem + 1;
            
            //clonamos el DIV
            newDiv = objDiv.cloneNode(true);
            
            newDiv.id = "DivImg_" + nGaleria + "_" + iContItem;
            
            //lo añadimos al final del div galeria
            objContenedor.appendChild(newDiv);

            //creamos la imagen
            CargaDiv (nodes[i], newDiv, iContItem);
        }
    }
}

function CargaDiv (xmlDoc, objDiv, nImage)
{
    var nodes = xmlDoc.childNodes;
    var i = 0;
    var texto = "";
    var sImagen = "";
    var sNombre = "";
    var sDireccion = "";
    var sPoblacion = "";
	var sAlt = "";
    
	for (i=0; i < nodes.length; i++)
    {
        //var fields = nodes(i).childNodes;
        var fields = nodes[i];
        
        //si es un elemento
        if (fields.nodeType == 1)
        {

            // si es ie el texto esta guardado en la propiedad text
            if (window.ActiveXObject)
                texto = fields.text;
                
            // sino el texto esta guardado en la propiedad textContent
            else
                texto = fields.textContent;

            
            switch(fields.nodeName)
            {
                case "nombre":
                    sNombre = texto;
                    break;
                    
                case "direccion":
                    sDireccion = texto;
                    break;
                    
                case "poblacion":
                    sPoblacion = texto;
                    break;
                    
                case "imagen":
                    sImagen = texto;
                    break;
                    
                case "thumb":
                    // sino hay contenido mete un espacio
                    if (texto == "")
                    {
                        objDiv.innerHTML = "";
                        objDiv.style.display = "none";
                    }
                    // añade el contenido al TD
                    else
                    {
						if (sNombre != "")
						{
							if (sAlt != "") sAlt = sAlt + " - ";
							sAlt = sAlt + sNombre;
						}
						if (sDireccion != "")
						{
							if (sAlt != "") sAlt = sAlt + " - ";
							sAlt = sAlt + sDireccion;
						}
						if (sPoblacion != "")
						{
							if (sAlt != "") sAlt = sAlt + " - ";
							sAlt = sAlt + sPoblacion;
						}
						
						//alert('<a href="' + sImagen + '" rel="lightbox" title="' + sAlt + '"><img alt="' + sAlt + '" title="' + sAlt + '" src="' + texto + '"></a>');
                        objDiv.innerHTML = '<a href="' + sImagen + '" rel="lightbox" title="' + sAlt + '"><img alt="' + sAlt + '" title="' + sAlt + '" src="' + texto + '" /></a>';
                        //objDiv.innerHTML = '<img alt="' + sAlt + '" title="' + sAlt + '" id="img' + nImage + '" src="' + texto + '">';
                        objDiv.style.display = "block";
                        objDiv.style.float = "left";
                    }
                    break;
            }
            
        }
    }
}

// he creado una funcion por si luego le añadimos más funcionalidad al subir
function Subir(nGaleria)
{
    MueveDiv('arriba',nGaleria);

}

// he creado una funcion por si luego le añadimos más funcionalidad al bajar
function Bajar(nGaleria)
{
    MueveDiv('abajo',nGaleria);
}

// esta función captura la posición actual del div y lanza el slide hacia arriba o hacia abajo
function MueveDiv(op,nGaleria)
{
    // capturamos los objetos (tanto la galeria como el contenedor)
    var objGaleria = document.getElementById("divGaleria" + nGaleria);
    var objContenedor = document.getElementById("contImages" + nGaleria);
    
    // capturamos su Top
    nContTop = parseInt(objContenedor.style.top);
    nGalTop = parseInt(objGaleria.style.top);

    // si es explorer
    if(objContenedor.offsetHeight)
    {
        nContHeight = objContenedor.offsetHeight;
        nGalHeight = objGaleria.offsetHeight;
    }
    // si es mozilla
    else if(objContenedor.style.pixelHeight)
    {
        nContHeight = objContenedor.style.pixelHeight;
        nGalHeight = objGaleria.style.pixelHeight;
    }

    // si es hacia arriba
    if (op == "arriba")
    {
        //si es menor el top del contenedor que el top del div galeria
        //y no está haciendo ya el slide
        if ((nContTop < nGalTop) && !x_cargando)
        {
            x_cargando = true;
            SlideMove(objContenedor.id, nContTop + (imgHeight + pixPadHeight));
        }
    
    } else {
    
        //si es mayor el top + height del contenedor que el top + height del div galeria
        if (((nContTop + nContHeight) > (nGalTop + nGalHeight)) && !x_cargando)
        {
            x_cargando = true;
            SlideMove(objContenedor.id, nContTop - (imgHeight + pixPadHeight));
        }
    }
    
}

// funcion recursiva que va moviendo el div contenedor
function SlideMove(sDiv, valor)
{
    var obj_div = document.getElementById(sDiv);
    
    // si es ie
    if (document.all)
        var nTop = obj_div.style.posTop;
    else
        var nTop = parseInt(obj_div.style.top);
    
    nTop = nTop + ((parseInt(valor) - nTop) / 5);
	
    // cambia el top del objeto con respecto a la deceleración
    
    if (document.all)
        obj_div.style.posTop = nTop;
    else
        obj_div.style.top = nTop.toString() + "px";

    // si la diferencia es menor de 5 px con respecto al valor final
    // pone directamente el valor final
    if ((Math.abs(parseInt(valor) - nTop) < 3) || (x_nTopHang == nTop))
    {
        if (document.all)
            obj_div.style.posTop = valor;
        else
            obj_div.style.top = valor.toString() + "px";
            
        x_cargando = false;
      
    } else {
        x_nTopHang = nTop;
        setTimeout("SlideMove('" + sDiv + "','" +  valor + "')", 20);
    }
}

