var DIM_PRODUCT_THUMB = [89,66];
var DIM_PRODUCT_THUMB_COATING2D_IMAGES = [240,180];
//var DIM_PRODUCT_REV = [425,310];
var DIM_PRODUCT_REV = [504,378];
var DIM_PRODUCT_REV_PRESUPUESTO = [144,108];
var DIM_PRODUCT_REV_MISMUEBLES = [120,90];

var DIM_PRODUCT_REV_DOWNLOAD = [1024,768]; 
var DIM_TEXTURE_THUMB = [53,53];
var DIM_TEXTURE_THUMB_PARTS = [18,18];
var DIM_TEXTURE_ZOOM = [110,110];
var DIM_TEXTURE_ZOOM_DIALOG = [200,200];

var DIM_PRODUCT_REV_ZOOM_L1 = [536,402]; //inicial
var DIM_PRODUCT_REV_ZOOM_L2 = [736,552];
var DIM_PRODUCT_REV_ZOOM_L3 = [800,600];
var DIM_PRODUCT_REV_ZOOM_L4 = [1024,768];
var DIM_REFERENCE_DIALOG = [104,104];

var numTexturesPerPage = 15;
var widthScroll = 0;

/* contenedor de modelos = divImageScrollerContainer */
/* imagen thumbnail = divImageScrollerImage */

/* contenedor de categorias = divCoatingAppletCategories */
/* contenedor de texturas = divCoatingAppletTextures */
/* contenedor de paginacion = divCoatingAppletPagination */
/* contenedor de imagenes revestivles = divImagenesRevestiblesProducto */

var inputModeRev = "LOCAL";
var outputModeRev = "LOCAL";

var productIni = new Product();
var n_scroll=0;
 
var user = new User();

function ini() {

    var imgElement = document.getElementById("imageRev");
    imgElement.width = DIM_PRODUCT_REV[0];
    imgElement.height = DIM_PRODUCT_REV[1];

}

function changeCategory(categoria) {
    
    /* desmarcar la anterior categoria seleccionada
    buscar div de la categoria y cambiar className */
    if (selectedCategory != null) {
        var idDivCategoriaAnt = "Category_" + selectedCategory.nombre;
        var divElementAnt = document.getElementById(idDivCategoriaAnt);
        divElementAnt.className = "divCategory";
    }

    selectedCategory = categoria;

    /* marcar la nueva categoria seleccionada */
    var idDivCategoria = "Category_" + selectedCategory.nombre;
    var divElement = document.getElementById(idDivCategoria);
    divElement.className = "divCategoryOver";

   loadPaginationTextures(selectedCategory);
    loadPageTextures(1);
}

function loadProduct() {

    /* Selected Product */

    prLoadProduct();  

}

function prLoadProduct() {

    selectedTexture = null; 
    obtenerTexturas();

}

function unmarshallTextures(data) {

    /* recorrer dataXmlTextures y obtener texturas y categorias + añadir botones de categorias  */

    categories = new Categories();

    var texturas = data.getElementsByTagName("texturas")[0];
    var numTexturas = texturas.childNodes.length;

	for (i=0; i<numTexturas; i++)
	{
		textura = texturas.childNodes[i];

        var t = new Texture(); 
        t.codigo = textura.getElementsByTagName("codigo")[0].firstChild.nodeValue;
        t.fichero = textura.getElementsByTagName("imagen")[0].firstChild.nodeValue;
        t.categoria = textura.getElementsByTagName("categoria")[0].firstChild.nodeValue;
        t.fabricante = textura.getElementsByTagName("fabricante")[0].firstChild.nodeValue;
        t.ancho = textura.getElementsByTagName("ancho")[0].firstChild.nodeValue;
        t.alto = textura .getElementsByTagName("alto")[0].firstChild.nodeValue;
        t.precioReftelacab = textura.getElementsByTagName("precioReftelacab")[0].firstChild.nodeValue;
        if (t.categoria == "TELA")
        {
            t.serie = textura.getElementsByTagName("serie")[0].firstChild.nodeValue;
            t.peso = textura.getElementsByTagName("peso")[0].firstChild.nodeValue;

            t.lavado = textura.getElementsByTagName("lavado")[0].firstChild.nodeValue;
            t.lejia = textura.getElementsByTagName("lejia")[0].firstChild.nodeValue;
            t.secadora = textura.getElementsByTagName("secadora")[0].firstChild.nodeValue;
            t.lavadoseco = textura.getElementsByTagName("lavadoseco")[0].firstChild.nodeValue;
            t.planchado = textura.getElementsByTagName("planchado")[0].firstChild.nodeValue;
            t.composicion = textura.getElementsByTagName("composicion")[0].firstChild.nodeValue;
        }
        else if (t.categoria == "ACABADO")
        {
            t.incremento = textura.getElementsByTagName("incremento")[0].firstChild.nodeValue;
            t.tipoacabado = textura.getElementsByTagName("tipoacabado")[0].firstChild.nodeValue;
        }

        var encontrado = false;

        var cats = categories.categorias;
        var n_cats = cats.length;

        for (j=0; j<cats.length; j++)
        {
            if (cats[j].nombre == t.categoria)
            {
                // categoria ya introducida en categories -> introducir textura en dicha categoria
                encontrado = true;
                var n_tex = cats[j].texturas.length;
                cats[j].texturas[n_tex] = t;
                break;
            }
        }
        
        if (!encontrado)
        {
            // crear categoria -> introducir textura en dicha categoria */
            var ncat = new Category(t.categoria);
            ncat.texturas[0] = t;

            cats[n_cats] = ncat;
        }
	}

    if (categories.categorias.length == 1)
        selectedCategory = categories.categorias[0];

    for (i=0; i<categories.categorias.length; i++)
        addCategoryButton(categories.categorias[i]);


    //crear 1 texturesCategory por categoria
}

function obtenerTexturas() {

    var listaReferenciasEnEscena = "";
    var cont = selectedProduct.imagenSeleccionada.referenciasEnEscena.length;

    aux = selectedProduct.imagenSeleccionada;

    for (r=0; r<cont; r++) {
        var aux2 = aux.referenciasEnEscena[r];
        listaReferenciasEnEscena = listaReferenciasEnEscena + aux2 + ",";
    }

    var url = urlServ + "ObtenerTexturas" +
                        "?fabricante=" + escape(selectedProduct.fabricante) +
                        "&producto=" + encodeURIComponent(selectedProduct.nombre) +
                        "&referenciasEnEscena=" + encodeURIComponent(listaReferenciasEnEscena) +
                        "&imagen=" + escape(selectedProduct.imagenSeleccionada.fichero);

    new Ajax.Request(url, {
        method: 'post',
        onSuccess: function(transport) {
            prObtenerTexturas(transport.responseXML);
        },
        onFailure: function(transport) {
            alert('Error LOGIN');
            alert("\n\n" + transport.responseText);
        }
    });
}


function prObtenerTexturas(data) {

    clearDiv("divCoatingAppletCategories");
    clearDiv("divCoatingAppletPagination");
    clearDiv("divCoatingAppletTextures");

    unmarshallTextures(data);
    if (categories.categorias.length > 0)
    {
        var cat = categories.categorias[categories.categorias.length -1]
        //selectedCategory = cat;
        changeCategory(cat);
    }

    usemapCtp();
}


function addCategoryButton(categoria) {

    var containerElement = document.getElementById("divScrollCoatingAppletCategories");
  
    var divElement = document.createElement("div");     
    divElement.className = "divCategory";
    divElement.id = "Category_" + categoria.nombre;
    divElement.style.cursor = "pointer";
    divElement.title = "Texturas de la categoría " + categoria.nombre;

    Event.observe(divElement, 'click', function() {
        changeCategory(categoria);
    }, false);

//    if (isIE) {
//        divElement.attachEvent("onclick",
//            function(){
//                javascript:changeCategory(categoria)
//            });
//    }
//    else {
//        divElement.addEventListener("click",
//            function(){
//                javascript:changeCategory(categoria)
//            },false);
//    }

    newSpan = document.createElement("span");
    newText = document.createTextNode(categoria.nombre);
    newSpan.appendChild(newText);
    divElement.appendChild(newSpan);

    containerElement.appendChild(divElement);

}

function loadPaginationTextures(categoria) {

    clearDiv("divCoatingAppletPagination");

    //var numTexturas = dataXmlTextures.getElementsByTagName("texturas")[0].childNodes.length;

    var numTexturas = 0;
    for (i=0; i<categories.categorias.length; i++)
    {
        if (categories.categorias[i].nombre == categoria.nombre)
        {
            numTexturas = categories.categorias[i].texturas.length;
            break;
        }
    }

    var numPaginas = 0;

    if ((numTexturas % numTexturesPerPage) == 0)
        numPaginas = Math.floor(numTexturas / numTexturesPerPage)
    else
        numPaginas = Math.ceil(numTexturas / numTexturesPerPage);

    for (i=0; i<numPaginas; i++) {
        addTexturePage(i+1);
    }
}

function addTexturePage(np) {
    var containerElement = document.getElementById("divScrollCoatingAppletPagination");

    var divElement = document.createElement("div");
    divElement.className = "divPageTextures";
    divElement.style.cursor = "pointer";
    divElement.title = "Página " + np;

    newSpan = document.createElement("span");
    newText = document.createTextNode(np);
    newSpan.appendChild(newText);
    divElement.appendChild(newSpan);

    Event.observe(divElement, 'click', function() {
        loadPageTextures(np);
    }, false);

//    if (isIE) {
//        divElement.attachEvent("onclick",
//            function(){
//                javascript:loadPageTextures(np);
//            });
//    }
//    else {
//        divElement.addEventListener("click",
//            function(){
//                javascript:loadPageTextures(np);
//            },false);
//    }

    containerElement.appendChild(divElement);

}

function loadPageTextures(np) {

    clearDiv("divCoatingAppletTextures");

    var numTexturas = 0;
    
    for (i=0; i<categories.categorias.length; i++)
        if (categories.categorias[i].nombre == selectedCategory.nombre)
        {
            numTexturas = categories.categorias[i].texturas.length;
            break;
        }

    /* cargar 'numTexturesPerPage' texturas */
    var i1 = (numTexturesPerPage * np) - numTexturesPerPage;
    var i2 = i1 + numTexturesPerPage - 1;


    /* obtener texturas de la categoria selectedCategory*/
    var firstSelected = false;
    for (j=0; j<categories.categorias.length; j++)
    {
        if (categories.categorias[j].nombre == selectedCategory.nombre)
        {
            for (i=i1; i<=i2; i++)
            {
                if (i < numTexturas)
                {
                    var auxTextura = categories.categorias[j].texturas[i];
                    if (!firstSelected)
                    {
                        selectedTexture = auxTextura;
                        firstSelected = true;
                    }

                    addTexture(auxTextura);
                }
            }
            break;
        }
    }

}

function addTexture(textura) {
    
    var containerElement = document.getElementById("divScrollCoatingAppletTextures");

    var divElement = document.createElement("div")
    divElement.id = "Texture_" + textura.codigo;
    divElement.className = "divTextureImage";
    divElement.style.cursor = "pointer";

    Event.observe(divElement, 'click', function() {
        selectTexture(textura);
    }, false);

//    if (isIE)  {
//        divElement.attachEvent("onclick",
//            function(){
//                javascript:selectTexture(textura)
//            });
//    }
//
//    else {
//        divElement.addEventListener("click",
//            function(){
//                javascript:selectTexture(textura)
//            },false);
//    }

    var imgElementMini = document.createElement("img");  

    imgElementMini.src = "IMG/ajax-loader_" + DIM_TEXTURE_THUMB[0] + "x" + DIM_TEXTURE_THUMB[1] + ".gif";
    imgElementMini.id = 'Texture_IMG_MINI_' + textura.codigo;

    if (textura.categoria == 'TELA')
    {
        imgElementMini.title = "Código: " + textura.codigo + " Serie: " + textura.serie;
    }
    else if (textura.categoria == 'ACABADO')
    {
        imgElementMini.title = textura.codigo;
    }

    imgElementMini.setAttribute('border', 0);

    divElement.appendChild(imgElementMini);

    containerElement.appendChild(divElement);
    containerElement.appendChild(divElement);

    imgElementMini.src = urlServ + "RecuperarImagen" + 
                        "?modo=thumbnail" +
                        "&ficheroImagen=" + escape(textura.fichero) +
                        "&fabricante=" + escape(textura.fabricante) +
                        "&dim=" + DIM_TEXTURE_THUMB[0] + "," + DIM_TEXTURE_THUMB[1];


    /* mantener aspect ratio */
    ancho = DIM_TEXTURE_THUMB[0];
    alto = DIM_TEXTURE_THUMB[1];

    var ratio = imgElementMini.height/imgElementMini.width;

    if (ratio > 0.7) //alargada
        ancho = alto/ratio;
    else if (ratio < 0.7) //apaisada
        alto = ancho * ratio;

    imgElementMini.width = ancho;
    imgElementMini.height = alto;

}

function showTooltipTextureZoom(idDivTooltip, idDivAsoc, textura) {

//    var imgElement = document.getElementById("imgTooltipTexture");
//    imgElement.src = urlServ + "RecuperarImagen" +
//                            "?modo=thumbnail" +
//                            "&ficheroImagen=" + escape(textura.fichero) +
//                            "&fabricante=" + escape(textura.fabricante) +
//                            "&dim=" + DIM_TEXTURE_ZOOM[0] + "," + DIM_TEXTURE_ZOOM[1];
//
//
// 	var w, h, l, t;
//	w = 110;
//	h = 110;
//    var divAsocElement = document.getElementById(idDivAsoc);
//	l = getX_Element(divAsocElement);
//	t = getY_Element(divAsocElement) + DIM_TEXTURE_THUMB[1] + 4 ;
//
//    displayFloatingDiv(idDivTooltip, '', w, h, l, t);

    

}


function hideTooltipTextureZoom(idDivTooltip)  {
    hiddenFloatingDiv(idDivTooltip);
}

function selectTexture(textura) {
    /* desmarcar la anterior textura seleccionada
    buscar div de la textura y cambiar className */
    var idDivTexturaAnt = "Texture_" + selectedTexture.codigo;
    var divElementAnt = document.getElementById(idDivTexturaAnt);
    divElementAnt.className = "divTextureImage";

    selectedTexture = textura;

    /* marcar la nueva textura seleccionada */
    var idDivTextura = "Texture_" + selectedTexture.codigo;
    var divElement = document.getElementById(idDivTextura);
    divElement.className = "divTextureImageOver";

    //showHelp(3);
}

/*
 * usuario
 * pwd
 * imagenBase
 * imagenTextura
 * ctp
 * parte            [referencia(ocurrencia)(NumZona)(IdZona)]
 * dimensionesTex   [ancho, alto]
 * dimensionesRev   [ancho, alto]
 * inputMode        [LOCAL | URL | STREAM]
 * outputMode       [LOCAL | URL | STREAM]
*/
function vestirParte(parte) {

    /*
     * Comprobar parte-textur a
     */
    var textura_aplicable = true;
    /* [referencia(ocurrencia)(numzona)(idzona)] */

    textura_aplicable = validar_textura_aplicable(parte);

    if (textura_aplicable)
    {
        loadDialog('dialog_coating2D_wait', null) ;
        var imgElement = document.getElementById("imageRev");
        imgElement.onload = prVestirParte;

        var auxImagen = selectedProduct.imagenSeleccionada;

        var imagenBase = auxImagen.fichero;
        var ctp = auxImagen.escena;
        var dimensionesTex = selectedTexture.ancho + "," + selectedTexture.alto;
        var dimensionesRev = DIM_PRODUCT_REV[0] + "," + DIM_PRODUCT_REV[1];

        imgElement.src = urlServ + "VestirServ" +
            "?usuario=" + "" +
            "&pwd=" + "" +

            "&imagenBase=" + escape(imagenBase) +
            "&fabricante=" + escape(selectedProduct.fabricante) +
            "&codigoTextura=" + escape(selectedTexture.codigo) +
            "&imagenTextura=" + escape(selectedTexture.fichero) +
            "&ctp=" + escape(ctp)  +

            "&parte=" + escape(parte)  + //encodeURIComponent
            "&dimensionesTex=" + dimensionesTex +
            "&dimensionesRev=" + dimensionesRev +

            "&inputMode=" + inputModeRev +
            "&outputMode=" + outputModeRev +

            "&param=" + Math.floor(Math.random()*111)
    }
    else
    {
        if (selectedPart != null) {
            aux_seriestela = "" ;
            aux_tiposacabado = "" ;

            for (i=0; i<selectedPart.seriestela.length; i++) {
                aux_seriestela += selectedPart.seriestela[i] + " ";
            }
            for (i=0; i<selectedPart.tiposacabado.length; i++) {
                aux_tiposacabado += selectedPart.tiposacabado[i] + " ";
            }

            if (aux_seriestela == "") {
                alert("La parte seleccionada solo admite Acabados de tipo " + aux_tiposacabado);
            }
            else if (aux_tiposacabado == "") {
                alert("La parte seleccionada solo admite Telas.\n ");
            }
        }
    }
}

function prVestirParte() {
     var imgElement = document.getElementById("imageRev");

    //obtenerArbolElementos("ini");
    //hideDialog("dialogRevWait")
    hideDialog();

    imgElement.onload = null;

    getConfigurationTree("coating2D");

}

function zoomImageRev(level) {

    var pagina_zoom = "";

    switch (level) {
        case 1:
            pagina_zoom = "dialog_coating2D_zoom_l1";
            dimensionesRev = DIM_PRODUCT_REV_ZOOM_L1;
            break;
        case 2:
            pagina_zoom = "dialog_coating2D_zoom_l2";
            dimensionesRev = DIM_PRODUCT_REV_ZOOM_L2;
            break;
        case 3:
            pagina_zoom = "dialog_coating2D_zoom_l3";
            dimensionesRev = DIM_PRODUCT_REV_ZOOM_L3;
            break;
        case 4:
            pagina_zoom = "dialog_coating2D_zoom_l4";
            dimensionesRev = DIM_PRODUCT_REV_ZOOM_L4;
            break;
        default:
            break;

    }

    /* comprobar dimensiones pantalla */
    var client_area_min = false;
    var client_height = document.body.clientHeight;
    var client_width = document.body.clientWidth;
    
    if ((client_width > dimensionesRev[0] + 20) && (client_height > dimensionesRev[1] + 10))
        client_area_min = true;

    if (selectedProduct != null && (client_area_min))
    {
          loadDialog(pagina_zoom, null);
    } else if (!client_area_min) {
        alert("El área de trabajo de su navegador no es lo suficientemente grande para mostrar\n" +
                "la imagen al tamaño seleccionado. \n" +
                "Por favor, maximice su navegador y/o ajuste su resolución de pantalla para visualizar la imagen ampliada.\n");
    }
      
}

function prZoomImageRev() {
    var imgElement = document.getElementById("imageRevZoom");

    imgElement.onload = function() {

        var imgElement = document.getElementById("imageRevZoom") ;
        imgElement.onload = null;
    };

    imgElement.src = urlServ + "RecuperarImagenGenerada"  +
        "?action=stream" +
        "&usuario=" + "" +
        "&pwd=" + "" +

        "&producto=" + escape(selectedProduct.nombre) +
        "&fabricante=" + escape(selectedProduct.fabricante) +
        "&imagen=" + escape(selectedProduct.imagenSeleccionada.fichero) +
        "&escena=" + escape(selectedProduct.imagenSeleccionada.escena) +

        "&dimensionesRev=" + dimensionesRev[0] + "," + dimensionesRev[1] +

        "&inputMode=" + inputModeRev +
        "&outputMode=" + outputModeRev +

        "&param=" + Math.floor(Math.random()*111)


    
}

function getConfigurationTree(section) {

    var escena = selectedProduct.imagenSeleccionada.escena;
    var imagenBase = selectedProduct.imagenSeleccionada.fichero;
    var fabricante = selectedProduct.fabricante;

    var url = urlServ + "ConfiguracionEscena";

    new Ajax.Request(url, {
        method: 'post',
        parameters: {
            action: "obtenerTree",
            escena: escena,
            imagenBase: imagenBase,
            fabricante: fabricante
        },
        onSuccess: function(transport) {
            prGetConfigurationTree(transport.responseXML, section);
        },
        onFailure: function(transport) {
            alert('Error GETCONFIGURATIONTREE');
            alert("\n\n" + transport.responseText);
        }
    });
}

function prGetConfigurationTree(data, section) {

    clearDiv("divCoatingAppletImageParts"); 
   
    var configuracionEscena = data.getElementsByTagName("configuracion")[0];
    
    for (i=0; i < configuracionEscena.childNodes.length; i++)
    {
        var referencia = configuracionEscena.childNodes[i] ;
        addReferenciaParte(referencia);
    }

    /* ocultar flechas si no son necesarias  */
    //divScrollCoatingAppletImageParts
   
    if (configuracionEscena.childNodes.length > 0)
    {
        
    }

    if (section == "coating2D_parts_presupuesto")
    {
        document.getElementById("divPresupuesto_IMG_coating2D").src =
                urlServ + "RecuperarImagenGenerada" +
                "?action=stream" +

                "&usuario=" + "" +
                "&pwd=" +  "" +

                "&producto=" + escape(selectedProduct.nombre) +
                "&fabricante=" + escape(selectedProduct.fabricante) +
                "&imagen=" + escape(selectedProduct.imagenSeleccionada.fichero) +
                "&escena=" + escape(selectedProduct.imagenSeleccionada.escena) +

                "&dimensionesRev=" + DIM_PRODUCT_REV_PRESUPUESTO[0] + "," + DIM_PRODUCT_REV_PRESUPUESTO[1] +

                "&inputMode=" + inputModeRev +
                "&outputMode=" + outputModeRev +

                "&param=" + Math.floor(Math.random()*111)
    }
} 

function addReferenciaParte(referencia) {

    codigoReferencia = referencia.getElementsByTagName("codigoReferencia")[0].firstChild.nodeValue;
    ocurrencia = referencia.getElementsByTagName("ocurrencia")[0].firstChild.nodeValue;  

    var divScrollCoatingAppletImageParts = document.getElementById("divScrollCoatingAppletImageParts");

    /* divReferenciasPartes_referencia*/
    var divReferenciasPartes_referencia = document.createElement("div");
    divReferenciasPartes_referencia.className = "divCoating2D_parts_referencia";

    /* nombre referencia + ocurrencia */
    var divReferenciasPartes_referencia_ocurrencia = document.createElement("div");
    divReferenciasPartes_referencia_ocurrencia.className = "divCoating2D_parts_nombre_referencia_ocurrencia";

        newSpan1 = document.createElement("span") ;
        newText1 = document.createTextNode( "Referencia ") ;
        newSpan1.appendChild(newText1);
        newSpan1.className = "divCoating2D_parts_texto_referencia";

        newSpan = document.createElement("span");
        newText = document.createTextNode(codigoReferencia);
        newSpan.appendChild(newText) ;
        newSpan.className = "divCoating2D_parts_texto_nombre_referencia";

//        newSpan2 = document.createElement("span");
//        newText2 = document.createTextNode( " (Ocurrencia: " + ocurrencia + ")");
//        newSpan2.appendChild(newText2);
//        newSpan2.className = "divCoating2D_parts_texto_ocurrencia";

        divReferenciasPartes_referencia_ocurrencia.appendChild(newSpan1);
        divReferenciasPartes_referencia_ocurrencia.appendChild(newSpan);
//        divReferenciasPartes_referencia_ocurrencia.appendChild(newSpan2);

    divReferenciasPartes_referencia.appendChild(divReferenciasPartes_referencia_ocurrencia);

    var partes = referencia.getElementsByTagName("partes")[0];
    for (j=0; j<partes.childNodes.length; j++)
      {
        parte = partes.childNodes[j];
        id = parte.getElementsByTagName("id")[0].firstChild.nodeValue;
        nombre = parte.getElementsByTagName("nombre")[0].firstChild.nodeValue;
        numero = parte.getElementsByTagName("numero")[0].firstChild.nodeValue; 

        textura = parte.getElementsByTagName("textura")[0];
        codigoTextura = textura.getElementsByTagName("codigoTextura")[0].firstChild.nodeValue;
        fabricanteTextura = textura.getElementsByTagName("fabricanteTextura")[0].firstChild.nodeValue;
        imagenTextura = textura.getElementsByTagName("imagenTextura")[0].firstChild.nodeValue;

        if (codigoTextura == "default") codigoTextura = "Textura No Especificada";

        /* divReferenciasPartes_parte_textura */
        var divReferenciasPartes_parte_textura = document.createElement("div");
        divReferenciasPartes_parte_textura.className = "divCoating2D_parts_parte";
            var div1 = document.createElement("div");
            div1.className = "divCoating2D_parts_nombre_parte";
            newSpan = document.createElement("span");
            newText = document.createTextNode(id);
            newSpan.appendChild(newText);
            div1.appendChild(newSpan);
            divReferenciasPartes_parte_textura.appendChild(div1);

            var div2 = document.createElement("div");
            div2.className = "divCoating2D_parts_textura";
            divReferenciasPartes_parte_textura.appendChild(div2);

            var aux_texture = new Texture();
            aux_texture.codigo = codigoTextura;
            aux_texture.fichero = imagenTextura;
            aux_texture.fabricante = fabricanteTextura;

            var div3 = generateTexture_parts(codigoTextura, imagenTextura, fabricanteTextura, aux_texture) ;
            /* obtener objeto de textura */
            aux_textura = null;
            for (k=0; k<categories.categorias.length; k++){
                for (l=0; l<categories.categorias[k].texturas.length; l++) {
                    if ((categories.categorias[k].texturas[l].fichero == imagenTextura) && (categories.categorias[k].texturas[l].fabricante == fabricanteTextura))
                    {
                        aux_textura =categories.categorias[k].texturas[l] ;
                        break;
                    }
                }
            }

             var params = new Array();
            params[0] = aux_textura ;

            div3.appendChild(newLink);

            div2.appendChild(div3) ;

            var div4 = document.createElement("div");
            div4.className = "divCoating2D_parts_nombre_textura";
            newSpan = document.createElement("span");
            newText = document.createTextNode(codigoTextura);
            newSpan.appendChild(newText);
            div4.appendChild(newSpan);  
            div2.appendChild(div4);

        divReferenciasPartes_referencia.appendChild(divReferenciasPartes_parte_textura);
    }

    divScrollCoatingAppletImageParts.appendChild(divReferenciasPartes_referencia) ;

}

function generateTexture_parts(codigoTextura, imagenTextura, fabricanteTextura, textura) {

	var div3 = document.createElement("div")
	div3.className = "divCoating2D_parts_imagen_textura";
	div3.title = "Pinche para ver la imagen de textura ampliada.";
    newLink = document.createElement("a");
	newImg = document.createElement("img");
    newImg.border = "0" ;
	if (imagenTextura != "default"){
	    newImg.src =  urlServ + "RecuperarImagen" +
	            "?modo=thumbnail" +
	            "&ficheroImagen=" + escape(imagenTextura) +
	            "&fabricante=" + escape(fabricanteTextura) +
	            "&dim=" + DIM_TEXTURE_THUMB_PARTS[0] + "," + DIM_TEXTURE_THUMB_PARTS[1] ;

        var enlace = urlServ + "RecuperarImagen" +
	            "?modo=original" +
	            "&ficheroImagen=" + escape(imagenTextura) +
	            "&fabricante=" + escape(fabricanteTextura) +
	            "&dim=" + DIM_TEXTURE_THUMB_PARTS[0] + "," + DIM_TEXTURE_THUMB_PARTS[1] ;


        newLink.href = enlace;
        newLink.rel = "lightbox";
        //newLink.rev = "width: 677px; height: 600px; scrolling: no;";

        newLink.appendChild(newImg);
        
        Event.observe(div3, 'mouseover', function() {
            //alert(textura.codigo);
            showTooltipTextureZoom("divTooltipTexture", "Texture_" + textura.codigo, textura);
        }, false);

        Event.observe(div3, 'mouseout', function() {
            hideTooltipTextureZoom("divTooltipTexture");
        }, false);
    }
	else
	    newImg.src = "IMG/na_" + DIM_TEXTURE_THUMB_PARTS[0] + "x" + DIM_TEXTURE_THUMB_PARTS[1] + ".png";
    return div3;

}

function togglein( param) {
  alert(param);
}

function guardarConfig(from) {

    if (user.username == "circulo") {
        var mensaje = "Para guardar sus configuraciones debe ser usuario registrado.\n" +
                    "Pulse 'Aceptar' para acceder al registro o 'Cancelar' para continuar. \n ";

        if (confirm(mensaje)) {
            navigate("acceder",null, false)  ;
        }
    }
    else {
        var url = urlServ + "ConfiguracionEscena";
        new Ajax.Request(url, {
            method: 'post',
            parameters: {
                action: "guardar",
                escena: selectedProduct.imagenSeleccionada.escena,
                imagenBase: selectedProduct.imagenSeleccionada.fichero,
                modelo: selectedProduct.nombre,
                fabricante: selectedProduct.fabricante
            },
            onSuccess: function(transport) {
                prGuardarConfig(transport.responseXML, from);
            },
            onFailure: function(transport) {
                alert('Error GUARDARCONFIG');
                alert("\n\n" + transport.responseText);
            }
        });
        
    }
}


function prGuardarConfig(data, from) {

    var msg = data.getElementsByTagName("msg")[0].firstChild.nodeValue;

    if (msg != 0)
    {
        alert("Se ha producido un error al intentar guardar su configuraci\u00f3n. \n" +
                    "Por favor, int\u00e9ntelo de nuevo. Si el problema persiste,\n" +
                    "contacte con su administrador.\n");
    }
    else
    {
        alert("La configuraci\u00f3n se ha agregado correctamente a su secci\u00f3n 'Mis muebles'\n");
        if (from == "coating2D" )
        {
            navigate("presupuesto", null, false);
        }
    }

}

function descargarImagen() {

    //loadDialog('dialog_coating2D_wait', null) ;

    var url = urlServ + "RecuperarImagenGenerada" +
        "?action=download" +
        "&usuario=" + "" +
        "&pwd=" + ""  +

        "&producto=" + escape(selectedProduct.nombre) +
        "&fabricante=" + escape(selectedProduct.fabricante) +
        "&imagen=" + escape(selectedProduct.imagenSeleccionada.fichero) +
        "&escena=" + escape(selectedProduct.imagenSeleccionada.escena) +

        "&dimensionesRev=" + DIM_PRODUCT_REV_DOWNLOAD[0] + "," + DIM_PRODUCT_REV_DOWNLOAD[1] +

        "&inputMode=" + inputModeRev +
        "&outputMode=" + outputModeRev +

        "&param=" + Math.floor(Math.random()*111)

//    new Ajax.Request(url, {
//        method: 'get',
//        //asynchronous: 'false',
//        //contentType: 'application/x-download',
//        //contentType: 'image/jpeg',
//        onComplete: function(transport) {
//            prDescargarImagen(transport.responseBody) ;
//        },
//        onFailure: function(transport) {
//            alert('Error descargarImagen');
//            alert("\n\n" + transport.responseText) ;
//        }
//    });

    document.location.href = url;

}

function prDescargarImagen(data )  {
//    var aux = data.getAllResponseHeaders();
//
//    document.location.href = data.prototype;
//    hideDialog();
//
//    var msg = data.getElementsByTagName("msg")[0].firstChild.nodeValue;
//
//    if (msg != 0)
//    {
//        alert("Se ha producido un error al intentar guardar su configuraci\u00f3n. \n" +
//                    "Por favor, int\u00e9ntelo de nuevo. Si el problema persiste,\n" +
//                    "contacte con su administrador.\n");
//    }
//    else
//    {
//        var value = usuario.getElementsByTagName("value")[0].firstChild.nodeValue ;
//    }

}

function imprimirImagen() {

    var url = urlServ + "RecuperarImagenGenerada" +
        "?action=link" +
        "&usuario=" + "" +
        "&pwd=" + ""  +

        "&producto=" + escape(selectedProduct.nombre) +
        "&fabricante=" + escape(selectedProduct.fabricante) +
        "&imagen=" + escape(selectedProduct.imagenSeleccionada.fichero) +
        "&escena=" + escape(selectedProduct.imagenSeleccionada.escena) +

        "&dimensionesRev=" + DIM_PRODUCT_REV_DOWNLOAD[0] + "," + DIM_PRODUCT_REV_DOWNLOAD[1] +

        "&inputMode=" + inputModeRev +
        "&outputMode=" + outputModeRev  +

        "&param=" + Math.floor(Math.random()*111)

    var pw = window.open(url, "_new");
    pw.onload=function(){
        pw.print() ;
    }
}

function prImprimirImagen(pw) {
    pw.print();
}

