var DIM_IMAGEN_FICHA_THUMB = [104,104];
var NUM_ITEMS_PER_PAGE = 9;  

var catalogo_exclusivo = 0;

var ambients = new Ambients();

var selectedFamily = null;
var selectedStyle =null;
var selectedAmbient = null;
var selectedProduct = null;

var selectedPage = 1;
var selectedNElem = null;
var selectedPaginationSection = null;
var selectedSection = null;

var ref_parts_textures = new Ref_parts_textures();

function cargar_catalogo_exclusivo() {
    catalogo_exclusivo = 1;
    navigate('espacios', null, false);
}

function cargar_catalogo_general() {
//    alert("Todavía no se encuentran disponibles los productos del Catálogo General.\n Disculpe las molestias.");
    catalogo_exclusivo = 0;
    navigate('espacios', null, false);
}

function unmarshallProducts(data) {

    products = new  Products();

    var productos = data.getElementsByTagName("productos")[0];
    var numProductos = productos.childNodes.length;

    for (i=0; i<numProductos; i++)
    {
        var producto = productos.getElementsByTagName("producto")[i];
        var fabricante = producto.getElementsByTagName("fabricante")[0].firstChild.nodeValue;
        var nombre = producto.getElementsByTagName("nombre")[0].firstChild.nodeValue ;
        var exclusivo = producto.getElementsByTagName("exclusivo")[0].firstChild.nodeValue;
        var destino = producto.getElementsByTagName("destino")[0];
        var nombreDestino = destino.getElementsByTagName("nombre")[0].firstChild.nodeValue;
        var imagenDestino = destino.getElementsByTagName("imagen")[0].firstChild.nodeValue;

        var prod = new Product(nombre, fabricante);
        prod.exclusivo = exclusivo;
        prod.nombreDestino = nombreDestino;
        prod.imagenDestino = imagenDestino;

        /**********************/
        /* CARGAR REFERENCIAS */
        /**********************/
        var referencias = producto.getElementsByTagName("referencias")[0];
        for (j=0; j<referencias.childNodes.length; j++)
        {
            var referencia = referencias.getElementsByTagName("referencia")[j];
            var codigo = referencia.getElementsByTagName("codigoReferencia")[0].firstChild.nodeValue;
            var tipo = referencia.getElementsByTagName("tipo")[0];
            var nombreTipo = tipo.getElementsByTagName("nombre")[0].firstChild.nodeValue;
            var imagenTipo = tipo.getElementsByTagName("imagen")[0].firstChild.nodeValue;
            var grafico = referencia.getElementsByTagName("grafico")[0].firstChild.nodeValue;
            var descripcion = referencia.getElementsByTagName("descripcion")[0].firstChild.nodeValue;
            var ancho = referencia.getElementsByTagName("ancho")[0].firstChild.nodeValue;
            var fondo = referencia.getElementsByTagName("fondo")[0].firstChild.nodeValue;
            var alto = referencia.getElementsByTagName("alto")[0].firstChild.nodeValue;
            var precio = referencia.getElementsByTagName("precio")[0].firstChild.nodeValue;
            var nombreEstilo = referencia.getElementsByTagName("estilo")[0].firstChild.nodeValue;

            var ref = new Reference();
            ref.codigo = codigo;
            ref.nombreTipo = nombreTipo;
            ref.imagenTipo = imagenTipo;
            ref.grafico = grafico;
            ref.descripcion = descripcion;
            ref.ancho = ancho;
            ref.fondo = fondo;
            ref.alto = alto;
            ref.precio = precio;
            ref.nombreEstilo = nombreEstilo;

            prod.referencias[j] = ref;
        }


        /*******************/
        /* CARGAR IMAGENES */
        /*******************/
        var imagenes = producto.getElementsByTagName("imagenes")[0];
        for (j=0; j<imagenes.childNodes.length; j++)
        {
            var fichero = producto.getElementsByTagName("fichero")[j].firstChild.nodeValue;
            var escena = producto.getElementsByTagName("escena")[j].firstChild.nodeValue;
            var notas = producto.getElementsByTagName("notas")[j].firstChild.nodeValue;

            var imag = new Imagen();
            imag.fichero = fichero;
            imag.escena = escena;
            imag.notas = notas;

            prod.numImagenSeleccionada = 0;
            prod.imagenSeleccionada = prod.imagenes[0];

            var referenciasEnEscena = imagenes.getElementsByTagName("referenciasEnEscena")[0];
            for (k=0; k<referenciasEnEscena.childNodes.length; k++)
            {
                var referenciaEnEscena = referenciasEnEscena.getElementsByTagName("referenciaEnEscena")[k].firstChild.nodeValue;
                imag.referenciasEnEscena[k] = referenciaEnEscena;
            }

            if (!escena == "")
            {
                imag.revestible = true;
            }

            /* si no esta asociada */
            var flag = false;
            for (l=0; l<prod.imagenes.length; l++)
            {
                if (prod.imagenes[l].fichero == fichero)
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
                prod.imagenes[j] = imag;
        }

        //if (producto_exclusivo == 0)
         products.productos[i] = prod;
    }
    
}

function obtenerProductos() {

    var url = urlServ + "ObtenerProductos";
    new Ajax.Request(url, {
        method: 'post',
        /*encoding: 'UTF-8',*/
		/*parameters: {
        },*/
        onSuccess: function(transport) {
            prObtenerProductos(transport.responseXML);
        },
        onFailure: function(transport) {
            alert('Error OBTENERPRODUCTOS');
            alert("\n\n" + transport.responseText);
        }
    });
}

/*
 * fabricante
 * nombre
 * imagen
*/
function prObtenerProductos(data){
    unmarshallProducts(data);
    enableTopmenu() ;


    if ((selectedProduct == null))
        navigate("inicio", null, false);
    else
        if (user.username != "circulo")
            navigate("coating2D", null, false);
}

/*********************************************************************/
/********************* CARGA DE ITEMS ESPACIO ************************/
/*********************************************************************/

function generarEspacios_Estilo() {   //construye ambients:
    
    ambients = new Ambients ;

    selectedSection = "ESPACIO";
    selectedPaginationSection = "ESPACIO";

    for (i=0; i<products.productos.length; i++)
    {
        var producto = products.productos[i];

        if (
            (catalogo_exclusivo == 0 && producto.exclusivo == 0)  ||
            (catalogo_exclusivo == 1 && producto.exclusivo == 1)
        )

        {

            var flag = false ;
            for (j=0; j<ambients.ambientes.length; j++)
            {
                if (ambients.ambientes[j].nombre == producto.nombreDestino)
                {
                    flag = true ;

                        /*ambients.ambientes[j].productos[ambients.ambientes[j].productos.length] = producto;*/
                        /* OBTENER FAMILIAS Q TIENE EL PRODUCTO Y AGREGAR EL PRODUCTO A ESAS FAMILIAS (EN ESTE EAPACI) */
                        /*estamos en ambiente [ambients.ambientes[j]]
                        los tipos  son: */

                        for (it=0; it<producto.referencias.length; it++)
                        {
                            var referencia = producto.referencias[it];
                            var nombre_estilo = referencia.nombreEstilo;

                            var isEstilo = false;
                            for (ifa=0; ifa<ambients.ambientes[j].estilos.length; ifa++)
                            {
                                /* si ya esta creada la familia -> agregar el producto */
                                if (referencia.nombreEstilo == ambients.ambientes[j].estilos[ifa].nombre)
                                {
                                    isEstilo = true;
                                     break;
                                }
                            }

                            if (isEstilo) //la familia ya estaba creada -> agregar el producto a esta familia del espacio
                            {

                                // si no esta el pruducto en dicha familia
                                var isProductInStyle = false;
                                for (ipfa=0; ipfa<ambients.ambientes[j].estilos[ifa].productos.length; ipfa++)
                                {
                                    var producto_aux = ambients.ambientes[j].estilos[ifa].productos[ipfa];
                                    if ( producto_aux.nombre == producto.nombre && producto_aux.fabricante == producto.fabricante )
                                    {
                                        isProductInStyle = true;
                                        break;
                                    }
                                }
                                if ( !isProductInStyle)
                                {
                                    var n_prod = ambients.ambientes[j].estilos[ifa].productos.length;
                                    ambients.ambientes[j].estilos[ifa].productos[n_prod] = producto ;
                                }

                            }
                            else //la familia no estaba creada -> crear la familia y agregar el producto a esta familia del espacio
                            {
                                var estilo = new Style(nombre_estilo);
                                estilo.fichero =  normalize(nombre_estilo) + ".jpg";

                                estilo.productos[0] = producto;
                                ambients.ambientes[j].estilos[ambients.ambientes[j].estilos.length] = estilo ;
                            }
                        }
    //                }
                    /*****************************************************************/

                    break
                }
            }

            if (!flag)  //AMBIENTE NO ENCONTRADO
            {
                var ambiente = new Ambient(producto.nombreDestino);
                ambiente.fichero = producto.imagenDestino;

                    /* -------------------------------------------------- */
                    /* ambients.ambientes[j].productos[ambients.ambientes[j].productos.length] = producto;*/
                    /* OBTENER FAMILIAS Q TIENE EL PRODUCTO Y AGREGAR EL PRODUCTO A ESAS FAMILIAS (EN ESTE EAPACI) */
                    /*estamos en ambiente NUEVO */

                    for (it=0; it<producto.referencias.length; it++)
                    {
                        referencia = producto.referencias[it];
                        nombre_estilo = referencia.nombreEstilo;

                        isEstilo = false;  //comprobar si familia esta
                        for (var ifa=0; ifa<ambiente.estilos.length; ifa++)
                        {
                            /* si ya esta creada la familia -> agregar el producto */
                            if (referencia.nombreEstilo == ambiente.estilos[ifa].nombre)
                            {
                                isEstilo = true;
                                break;
                            }
                        }

                        if (isEstilo) //la familia ya estaba creada -> agregar el producto a esta familia del espacio
                        {
                            break;
                            n_prod = ambiente.estilos[ifa].productos.length;
                            ambiente.estilos[ifa].productos[n_prod] = producto;
                        }
                        else //la familia no estaba creada -> crear la familiay agregar el producto a esta familia del espacio
                        {
                            estilo = new Style(nombre_estilo);
                            estilo.fichero =  normalize(nombre_estilo) + ".jpg";

                            estilo.productos[0] = producto ;
                            ambiente.estilos[ambiente.estilos.length] = estilo;
                        }
                    }
                    /* ------------------------------------------------- -----*/

                ambients.ambientes[ambients.ambientes.length] = ambiente;
            }

        } // CONDICION EXCLUSIVO

    }
    var nElem = ambients.ambientes.length;

    loadPagination("ESPACIO", nElem);
}

function generarEspacios_Familia() {   //construye ambients:

    ambients = new Ambients ;

    selectedSection = "ESPACIO";
    selectedPaginationSection = "ESPACIO";

    for (i=0; i<products.productos.length; i++)
    {
        var producto = products.productos[i];

        if (
            (catalogo_exclusivo == 0 && producto.exclusivo == 0) ||
            (catalogo_exclusivo == 1 && producto.exclusivo == 1)
        )

        {

            var flag = false ;
            for (j=0; j<ambients.ambientes.length; j++)
            {
                if (ambients.ambientes[j].nombre == producto.nombreDestino)
                {
                    flag = true ;

                        /*ambients.ambientes[j].productos[ambients.ambientes[j].productos.length] = producto;*/
                        /* OBTENER FAMILIAS Q TIENE EL PRODUCTO Y AGREGAR EL PRODUCTO A ESAS FAMILIAS (EN ESTE EAPACI) */
                        /*estamos en ambiente [ambients.ambientes[j]]
                        los tipos  son: */

                        for (it=0; it<producto.referencias.length; it++)
                        {
                            var referencia = producto.referencias[it];
                            var tipo = referencia.nombreTipo;

                            var isFamilia = false;
                            for (ifa=0; ifa<ambients.ambientes[j].familias.length; ifa++)
                            {
                                /* si ya esta creada la familia -> agregar el producto */
                                if (referencia.nombreTipo == ambients.ambientes[j].familias[ifa].nombre)
                                {
                                    isFamilia = true;
                                     break;
                                }
                            }

                            if (isFamilia) //la familia ya estaba creada -> agregar el producto a esta familia del espacio
                            {

                                // si no esta el pruducto en dicha familia
                                var isProductInFamily = false;
                                for (ipfa=0; ipfa<ambients.ambientes[j].familias[ifa].productos.length; ipfa++)
                                {
                                    var producto_aux = ambients.ambientes[j].familias[ifa].productos[ipfa];
                                    if ( producto_aux.nombre == producto.nombre && producto_aux.fabricante == producto.fabricante )
                                    {
                                        isProductInFamily = true;
                                        break;
                                    }
                                }
                                if ( !isProductInFamily)
                                {
                                    var n_prod = ambients.ambientes[j].familias[ifa].productos.length;
                                    ambients.ambientes[j].familias[ifa].productos[n_prod] = producto ;
                                }

                            }
                            else //la familia no estaba creada -> crear la familia y agregar el producto a esta familia del espacio
                            {
                                var familia = new Family(tipo);
                                    familia.fichero = referencia.imagenTipo ;

                                familia.productos[0] = producto;
                                ambients.ambientes[j].familias[ambients.ambientes[j].familias.length] = familia ;
                            }
                        }
    //                }
                    /*****************************************************************/

                    break
                }
            }

            if (!flag)  //AMBIENTE NO ENCONTRADO
            {
                var ambiente = new Ambient(producto.nombreDestino);
                ambiente.fichero = producto.imagenDestino;

                    /* -------------------------------------------------- */
                    /* ambients.ambientes[j].productos[ambients.ambientes[j].productos.length] = producto;*/
                    /* OBTENER FAMILIAS Q TIENE EL PRODUCTO Y AGREGAR EL PRODUCTO A ESAS FAMILIAS (EN ESTE EAPACI) */
                    /*estamos en ambiente NUEVO */

                    for (it=0; it<producto.referencias.length; it++)
                    {
                        referencia = producto.referencias[it];
                        tipo = referencia.nombreTipo;

                        isFamilia = false;  //comprobar si familia esta
                        for (var ifa=0; ifa<ambiente.familias.length; ifa++)
                        {
                            /* si ya esta creada la familia -> agregar el producto */
                            if (referencia.nombreTipo == ambiente.familias[ifa].nombre)
                            {
                                isFamilia = true;
                                 break;
                            }
                        }

                        if (isFamilia) //la familia ya estaba creada -> agregar el producto a esta familia del espacio
                        {
                            n_prod = ambiente.familias[ifa].productos.length;
                            ambiente.familias[ifa].productos[n_prod] = producto;
                        }
                        else //la familia no estaba creada -> crear la familiay agregar el producto a esta familia del espacio
                        {
                            familia = new Family(tipo);
                            familia.fichero = referencia.imagenTipo;

                            familia.productos[0] = producto ;
                            ambiente.familias[ambiente.familias.length] = familia;
                        }
                    }
                    /* ------------------------------------------------------*/

                ambients.ambientes[ambients.ambientes.length] = ambiente;
            }

        } // CONDICION EXCLUSIVO

    }
    var nElem = ambients.ambientes.length;

    loadPagination("ESPACIO", nElem);
}

function addItemEspacio(ambiente)  {

    var containerElement = document.getElementById("scroll_fichas");

    var div_ficha = document.createElement("div");   //contenedor
    div_ficha.id = "Ambient_" + ambiente.nombre;
    div_ficha.className = "ficha";

    var div_imagen_ficha = document.createElement("div");
    div_imagen_ficha.className = "imagen_ficha";

    var div_texto_ficha = document.createElement("div");
    div_texto_ficha.className = "texto_ficha";
    newSpan = document.createElement("span");
    newText = document.createTextNode(ambiente.nombre);
    newSpan.appendChild(newText);
    div_texto_ficha.appendChild(newSpan);


    div_ficha.appendChild(div_imagen_ficha);
    div_ficha.appendChild(div_texto_ficha);

    containerElement.appendChild(div_ficha);

//    Event.observe(div_ficha, 'mouseover', function() {
//        div_ficha.classname = "ficha_over";
//    }, false);

    Event.observe(div_ficha, 'click', function() {
        //mostrarEstilos(ambiente);
        navigate("mostrar_estilos", ambiente, false);
    }, false);

    var imgElement = document.createElement("img");

    imgElement.src = "IMG/ajax-loader_" + DIM_IMAGEN_FICHA_THUMB[0] + "x" + DIM_IMAGEN_FICHA_THUMB[1] + ".gif";
    imgElement.id = 'Ambient_IMG_' + ambiente.nombre;
    imgElement.setAttribute('border', 0);

    div_imagen_ficha.appendChild(imgElement);

    if (catalogo_exclusivo == 1)
        fichero_ico = "exclusivos-"  + ambiente.fichero;
    else
        fichero_ico = ambiente.fichero;

    imgElement.src = urlServ + "RecuperarImagen" +
                        "?modo=ico" +
                        "&type=espacio" +
                        "&ficheroImagen=" + escape(fichero_ico) +
                        "&dim=" + DIM_IMAGEN_FICHA_THUMB[0] + "," + DIM_IMAGEN_FICHA_THUMB[1] ;

    /* mantener aspect ratio */
    ancho = DIM_IMAGEN_FICHA_THUMB[0];
    alto = DIM_IMAGEN_FICHA_THUMB[1];

    var ratio = imgElement.height/imgElement.width;
    if (ratio > 0.7) //alargada
        ancho = alto/ratio;
    else if (ratio < 0.7) //apaisa
        alto = ancho * ratio;

    imgElement.width = ancho;
    imgElement.height = alto;
}

/*********************************************************************/ 
/********************* CARGA DE ITEMS FAMILIA ************************/
/********************************************************* ************/

function mostrarFamilias(ambiente) {

    selectedAmbient = ambiente;
    var nElem = selectedAmbient.familias.length ;
    loadPagination("FAMILIA", nElem);
     
}

function addItemFamilia(familia) {

    var containerElement = document.getElementById("scroll_fichas"); 

    var div_ficha = document.createElement("div");   //contenedor
    div_ficha.id = "Family_" + familia.nombre;
    div_ficha.className = "ficha";

    var div_imagen_ficha = document.createElement("div");
    div_imagen_ficha.className = "imagen_ficha";

    var div_texto_ficha = document.createElement("div");
    div_texto_ficha.className = "texto_ficha";
    newSpan = document.createElement("span");
    newText = document.createTextNode(familia.nombre);
    newSpan.appendChild(newText);
    div_texto_ficha.appendChild(newSpan);


    div_ficha.appendChild(div_imagen_ficha);
    div_ficha.appendChild(div_texto_ficha);

    containerElement.appendChild(div_ficha);

    Event.observe(div_ficha, 'click', function() {
        //mostrarProductos(familia);
        navigate("mostrar_productos", familia, false);
    }, false) ;

    var imgElement = document.createElement("img");

    imgElement.src = "IMG/ajax-loader_" + DIM_IMAGEN_FICHA_THUMB[0] + "x" + DIM_IMAGEN_FICHA_THUMB[1] + ".gif";
    imgElement.id = 'Family_IMG_' + familia.nombre;
    imgElement.setAttribute('border', 0); 

    div_imagen_ficha.appendChild(imgElement);

    imgElement.src = urlServ + "RecuperarImagen" +
                        "?modo=ico" +
                        "&ficheroImagen=" + escape(familia.fichero) +
                        "&dim=" + DIM_IMAGEN_FICHA_THUMB[0] + "," + DIM_IMAGEN_FICHA_THUMB[1];

    /* mantener aspect ratio */
    ancho = DIM_IMAGEN_FICHA_THUMB[0];
    alto = DIM_IMAGEN_FICHA_THUMB[1];

    var ratio = imgElement.height/imgElement.width;
    if (ratio > 0.7) //alargada 
        ancho = alto/ratio;
    else if (ratio < 0.7) //apaisada
        alto = ancho * ratio;

    imgElement.width = ancho;
    imgElement.height = alto;
}

/*********************************************************************/
/********************* CARGA DE ITEMS ESTILO ************************/
/********************************************************* ************/

function mostrarEstilos (ambiente)  {

    document.getElementById("IMG_bodybar").src = "IMG/bodybar_estilo.png";

    selectedAmbient = ambiente;
    var nElem = selectedAmbient.estilos.length;
    loadPagination("ESTILO", nElem);

    // Si solo hay 1 estilo -> Cargar directamente s productos del espacio
    if (nElem == 1) {
        //eliminar el ultimo paso de navegación
        navigation.pantallas[navigation.pos] = null;
        navigation.pos--;

        navigate("mostrar_productos", selectedAmbient.estilos[0], false);
    }

}

function addItemEstilo(estilo) {

    var containerElement = document.getElementById("scroll_fichas");

    var div_ficha = document.createElement("div");   //contenedor
    div_ficha.id = "Style_" + estilo.nombre;
    div_ficha.className = "ficha";

    var div_imagen_ficha = document.createElement("div");
    div_imagen_ficha.className = "imagen_ficha";

    var div_texto_ficha = document.createElement("div");
    div_texto_ficha.className = "texto_ficha";
    newSpan = document.createElement("span");
    newText = document.createTextNode(estilo.nombre);
    newSpan.appendChild(newText) ;
    div_texto_ficha.appendChild(newSpan) ;

    div_ficha.appendChild(div_imagen_ficha);
    div_ficha.appendChild(div_texto_ficha);

    containerElement.appendChild(div_ficha);

    Event.observe(div_ficha, 'click', function() {
        //mostrarProductos(estilo);
        navigate("mostrar_productos", estilo, false);
    }, false);

    var imgElement = document.createElement("img");

    imgElement.src = "IMG/ajax-loader_" + DIM_IMAGEN_FICHA_THUMB[0] + "x" + DIM_IMAGEN_FICHA_THUMB[1] + ".gif";
    imgElement.id = 'Style_IMG_' + estilo.nombre;
    imgElement.setAttribute('border', 0);

    div_imagen_ficha.appendChild(imgElement);

    aux  = estilo.nombre + "-" + selectedAmbient.nombre + ".jpg";
    fichero_imagen = normalize_icon(aux);

    imgElement.src = urlServ + "RecuperarImagen"  +
                        "?modo=ico" +
                        "&type=estilo"+
                        "&ficheroImagen=" + escape(fichero_imagen)+
                        "&dim=" + DIM_IMAGEN_FICHA_THUMB[0] + "," + DIM_IMAGEN_FICHA_THUMB[1];

    /* mantener aspect ratio   */
    ancho = DIM_IMAGEN_FICHA_THUMB[0];
    alto = DIM_IMAGEN_FICHA_THUMB[1];

    var ratio = imgElement.height/imgElement.width;
    if (ratio > 0.7) //alargada
        ancho = alto/ratio;
    else if (ratio < 0.7) //apaisada
        alto = ancho * ratio;

    imgElement.width = ancho;
    imgElement.height = alto;
}

function loadPagination(section, nElem) {
    selectedNElem = nElem;

    var nPaginas = 0;

    if ((nElem % NUM_ITEMS_PER_PAGE) == 0)
        nPaginas = Math.floor(nElem / NUM_ITEMS_PER_PAGE)
    else
        nPaginas = Math.ceil(nElem / NUM_ITEMS_PER_PAGE);

    if (nPaginas > 0)
        loadPage(1, nElem, section);
}

function loadPage(np, nElem, section) {

    /* Habilita / Deshabilita botones de paginación */
    var first_page = 1;
    var last_page = Math.ceil(nElem / NUM_ITEMS_PER_PAGE) ;

    if (selectedPage == first_page) {
        document.getElementById("img_pagination_prev").src = "IMG/button_previous_off.png";
        document.getElementById("pagination_prev").style.cursor = "default";
    }
    else
    {
        document.getElementById("img_pagination_prev").src = "IMG/button_previous.png";
        document.getElementById("pagination_prev").style.cursor = "pointer";
    }

    if (selectedPage == last_page) {
        document.getElementById("img_pagination_next").src = "IMG/button_next_off.png";
        document.getElementById("pagination_next").style.cursor = "default";
    }
    else
    {
        document.getElementById("img_pagination_next").src = "IMG/button_next.png"  ;
        document.getElementById("pagination_next").style.cursor = "pointer";
    }


    var in1 = (NUM_ITEMS_PER_PAGE * (np-1)) + 1 ;
    var in2 = in1 + NUM_ITEMS_PER_PAGE - 1; 
    if (nElem < in2)
        in2 = nElem;
    
    selectedPage = np;
    var pagination_text = "";

    switch (section) {
        case "FAMILIA":
            pagination_text = "Mostrando " + in1 + " al " + in2 + " de " + nElem + " familias";
            break;
        case "ESTILO":
            pagination_text = "Mostrando " + in1 + " al " + in2 + " de " + nElem + " estilos";
            break;
        case "ESPACIO":
            pagination_text = "Mostrando " + in1 + " al " + in2 + " de " + nElem + " espacios";
            break;
        case "PRODUCTO":
            pagination_text = "Mostrando " + in1 + " al " + in2 + " de " + nElem + " productos";
            break;
        default:
            break;
    }


    document.getElementById("pagination_text").innerHTML = pagination_text ;

    clearDiv("contenedor_fichas");

    /* cargar 'NUM_ITEMS_PER_PAGE' items*/ 
    var i1 = (NUM_ITEMS_PER_PAGE * np) - NUM_ITEMS_PER_PAGE;
    var i2 = i1 + NUM_ITEMS_PER_PAGE - 1;

    for (i=i1; i<=i2; i++)
    {
        if (i < nElem)
        {
            var elem = null;
            if (section == "FAMILIA" )
            {
                elem = selectedAmbient.familias[i];
                addItemFamilia(elem);
            }  else if (section == "ESTILO")
            {
                 elem = selectedAmbient.estilos[i] ;
                 addItemEstilo(elem);
            }
            else if (section == "ESPACIO")
            {
                 elem = ambients.ambientes[i];
                 addItemEspacio(elem);
            } else if (section == "PRODUCTO")
            {
                elem = selectedStyle.productos[i]  ;
                addItemProducto(elem, selectedStyle.nombre);
            }
        }
    }

}

//}

/*********************************************************************/
/********************* CARGA DE ITEMS PRODUCTO ***********************/
/*********************************************************************/

function mostrarProductos(estilo) {
    document.getElementById("IMG_bodybar").src = "IMG/bodybar_product.png";
    actualizar_instrucciones("PRODUCTO");
    selectedPaginationSection = "PRODUCTO";

    selectedStyle = estilo;
    nElem = selectedStyle.productos.length;
    loadPagination("PRODUCTO", nElem);
}

function addItemProducto(producto, estilo) {

    var containerElement = document.getElementById("scroll_fichas");

    var div_ficha = document.createElement("div");   //contenedor
    div_ficha.id = "Product_" + producto.nombre;
    div_ficha.className = "ficha";

    var div_imagen_ficha = document.createElement("div");
    div_imagen_ficha.className = "imagen_ficha";

    var div_texto_ficha = document.createElement("div");
    div_texto_ficha.className = "texto_ficha";
    newSpan = document.createElement("span");
    newText = document.createTextNode(producto.nombre);
    newSpan.appendChild(newText);
    div_texto_ficha.appendChild(newSpan);

    div_ficha.appendChild(div_imagen_ficha);
    div_ficha.appendChild(div_texto_ficha);

    Event.observe(div_ficha, 'click', function() {
        //loadProducto(producto) ;
        navigate("load_producto", producto, false);
    }, false);

    var imgElement = document.createElement("img");
    imgElement.src = "IMG/ajax-loader_" + DIM_IMAGEN_FICHA_THUMB[0] + "x" + DIM_IMAGEN_FICHA_THUMB[1] + ".gif";
    imgElement.id = 'Product_IMG_' + producto.nombre;
    imgElement.title = "Producto: " + producto.nombre;
    imgElement.setAttribute('border', 0);
    div_imagen_ficha.appendChild(imgElement);

    /* SELECCIONAR LA IMAGEN DE LA FICHA SEGUN SI REVESTIBLE / FAMILIA / 0 */
    /* recorrer imagenes del producto */
    /* para cada 1 si es es revestible se recorren las referencias en la escena obteniendo el tipo de cada 1*/
    /*si == familia se elije esa imagen para mostrar en la ficha */
    producto.numImagenSeleccionada = 0;
    producto.imagenSeleccionada = null;
    if (estilo != null)
    {
        var encontrada = false;
        for (ip=0; ip<producto.imagenes.length; ip++)
        {
            var imagen = producto.imagenes[ip];
    
            for (re=0; re<imagen.referenciasEnEscena.length; re++)
            {
                var ref_en_escena = imagen.referenciasEnEscena[re];
                var estilo_ref_en_escena = null;
                /* obtener familia de ref_en_escena */
                for (r=0; r<producto.referencias.length; r++)
                {
                    var ref = producto.referencias[r];
                    if (ref.codigo == ref_en_escena)
                    {
                        estilo_ref_en_escena = ref.nombreEstilo;
                        break;
                    }
                }
                if (estilo_ref_en_escena == estilo)
                {
                    producto.numImagenSeleccionada = ip;
                    producto.imagenSeleccionada = producto.imagenes[0];
                    encontrada = true;
                    break;
                }
            }
            if (encontrada) break;
        }
        if (producto.imagenSeleccionada == null)
        {
            producto.numImagenSeleccionada = 0;
            //var aux_imagen = producto.imagenes[0];
            producto.imagenSeleccionada = producto.imagenes[0];
        }
    }
    else    //estamos en PRODUCTOS DE ESPACIO
     {
        producto.numImagenSeleccionada = 0;
        producto.imagenSeleccionada = producto.imagenes[0];
    }

    var imagenProducto = producto.imagenSeleccionada.fichero;

    imgElement.src = urlServ + "RecuperarImagen" +
                        "?modo=thumbnail" +
                        "&ficheroImagen=" + escape(imagenProducto) +
                        "&fabricante=" + producto.fabricante +
                        "&dim=" + DIM_IMAGEN_FICHA_THUMB[0] + "," + DIM_IMAGEN_FICHA_THUMB[1];

    /* mantener aspect ratio */
    ancho = DIM_IMAGEN_FICHA_THUMB[0];
    alto = DIM_IMAGEN_FICHA_THUMB[1];

    var ratio = imgElement.height/imgElement.width;
    if (ratio > 0.7) //alargada
        ancho = alto/ratio;
    else if (ratio < 0.7) //apaisa
        alto = ancho * ratio;

    imgElement.width = ancho;
    imgElement.height = alto;

//    div_ficha.style.display = "none";
    containerElement.appendChild(div_ficha);
//    Effect.toggle("Product_" + producto.nombre,"appear");
}

function loadProducto(producto) {
    
    selectedProduct = producto;

    selectedProduct.imagenSeleccionada = null;
    var numImagenesRevestibles = 0;
    for (i=0; i<selectedProduct.imagenes.length; i++)
    {
        if (producto.imagenes[i].revestible == true)
        {
            if (producto.imagenSeleccionada == null)
            {
                selectedProduct.numImagenSeleccionada = i;
                selectedProduct.imagenSeleccionada = producto.imagenes[i];
            }
            numImagenesRevestibles++;
        }
    }
    if (selectedProduct.imagenSeleccionada == null)
    {
        selectedProduct.numImagenSeleccionada = 0;
        selectedProduct.imagenSeleccionada = producto.imagenes[0];
    }

    //alert(selectedAmbient.nombre + " - " + selectedStyle.nombre + " - " + selectedProduct.nombre);


    if (numImagenesRevestibles == 0)
        alert("El modelo seleccionado no dispone de imagenes para revestir.");
    else if (numImagenesRevestibles > 1)  {
        var params = new Array();
        params[0] = selectedProduct.nombre;
        params[1] = selectedProduct.fabricante;
        loadDialog('dialog_coating2D_images', params) ;
    } else if (numImagenesRevestibles == 1) {
         navigate("coating2D", null, false);
    }

}


function loadImagenesRevestiblesProducto(nombre, fabricante) {

    //clearDiv("dialog_coating2D_images");

    /* buscar producto a partir nombre, fabricante */
    var productoS = null;
    for (i=0; i<products.productos.length; i++)
    {
        var producto = products.productos[i];

        if ((producto.fabricante == fabricante) && (producto.nombre == nombre))
        {
            productoS = producto;
            break;
        }
    }

    var revestible = false;
    for (j=0; j<productoS.imagenes.length; j++)
    {
        var imagen = productoS.imagenes[j].fichero;
        var rev = productoS.imagenes[j].revestible;

        addImagenRevestibleProducto(imagen, nombre, fabricante);
        if (rev)
            revestible = true;
    }

    if ((productoS.imagenes.length == 1) && (revestible))
        loadProduct(nombre, fabricante, imagen);
    else {}
        //showDialog("dialogCoatingImagesProduct");
        //loadDialog('dialog_coating2D', null)
}
/**/

function addImagenRevestibleProducto(imagen, nombre, fabricante) {

    var containerElement = document.getElementById("dialog_coating2D_images_scroll");
    var divElement = document.createElement("div");
    divElement.className = "dialog_coating2D_images_image";
    divElement.style.cursor = "pointer";

    Event.observe(divElement, 'click', function() {
        hideDialog("dialog_coating2D_images");
        navigate("coating2D", null, false);
        loadProduct(nombre, fabricante, imagen)
    }, false);

        var imgElement = document.createElement("img");
        imgElement.src = "IMG/ajax-loader_" + DIM_PRODUCT_THUMB_COATING2D_IMAGES[0] + "x" + DIM_PRODUCT_THUMB_COATING2D_IMAGES[1] + ".gif";
        imgElement.setAttribute('title', nombre + " " + imagen);
        imgElement.setAttribute('border', 1);
        divElement.appendChild(imgElement);
    containerElement.appendChild(divElement);


    imgElement.src = urlServ + "RecuperarImagen" +
                        "?modo=thumbnail" +
                        "&ficheroImagen=" + escape(imagen) +
                        "&fabricante=" + escape(fabricante) +
                        "&dim=" + DIM_PRODUCT_THUMB_COATING2D_IMAGES[0] + "," + DIM_PRODUCT_THUMB_COATING2D_IMAGES[1];

}

function loadPrevPage() {
    //alert("pagina actual =" + selectedPage);
    
    if (selectedPage - 1 > 0)
    {
        selectedPage--;
        loadPage(selectedPage, selectedNElem, selectedPaginationSection);
    }
}

function loadNextPage() {
    //alert("pagina actual =" + selectedPage);

    var nPaginas = Math.ceil(selectedNElem / NUM_ITEMS_PER_PAGE);
    if (selectedPage + 1 < nPaginas + 1)
    {
        selectedPage++;
        loadPage(selectedPage, selectedNElem, selectedPaginationSection);
    }
}
