var timerAnimacion = null;
var timerDesvanecimiento = null;
var tiempoDesvanecimiento = 0;
var tiempoMaxDesvanecimiento = 3000;
var intervaloDesvanecimiento = 300;
var tiempoMaxAnimacion = 6000;
var tiempoAnimacion = 0;
var intervalo = 1000;
var articulosAnyadidos = 0;

function muestraMensaje(mensaje)
{
    var oMsg = document.getElementById("msgFlotante");
    if (!oMsg)
    {
        oMsg = document.createElement("div");
        oMsg.id = "msgFlotante";
        oMsg.style.position = "absolute";
        document.body.appendChild(oMsg);
        oMsg.style.visibility = "hidden";
        var oBody = document.body;
        var widthBody;
        if (oBody.currentStyle)
        {
            widthBody = parseInt(oBody.currentStyle.width.substr(0, oBody.currentStyle.width.length - 2));
        }
        else
        {
            parseInt(oBody.style.width.substr(0, oBody.style.width.length - 2));
        }
        oMsg.style.width = "400px";
        oMsg.style.left = "310px";
        oMsg.style.top = "200px";
        oMsg.style.border = "1px solid #b31516";
        oMsg.style.background = "#fadfdf";
        oMsg.style.color = "#b31516";
        oMsg.style.textAlign = "center";
        oMsg.style.lineHeight = "2em";
        oMsg.zIndex = 999;
    }
    oMsg.innerHTML = mensaje;
    oMsg.style.visibility = "visible";
    setTimeout('ocultaMensaje()', 1000);
};

function ocultaMensaje()
{
    timerDesvanecimiento = setInterval('desvaneceObjeto("msgFlotante")', 100);
};

function desvaneceObjeto(idObj)
{
    var tiempoRestante = parseFloat(tiempoMaxDesvanecimiento - tiempoDesvanecimiento);
    var opacidad = 0.0;
    if (tiempoRestante >= 0.0)
    {
        opacidad = tiempoRestante / parseFloat(tiempoMaxDesvanecimiento);
    };
    obj = document.getElementById(idObj);
    obj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(Opacity="+parseInt(opacidad * 100)+")";
    obj.style.MozOpacity = parseFloat(opacidad);
	
    tiempoDesvanecimiento += intervaloDesvanecimiento;
    if (tiempoDesvanecimiento > tiempoMaxDesvanecimiento)
    {
        clearInterval(timerDesvanecimiento);
        obj.style.visibility = "hidden";
        obj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(Opacity="+parseInt(100)+")";
        obj.style.MozOpacity = parseFloat(1.0);
        tiempoDesvanecimiento = 0;
    };
};

var cadenaPost = "";
function anyadeArticulo()
{
    // Continuamos sólo si el objeto xmlHttp no está ocupado
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
    {
        // Codificamos los parámetros a enviar
        var cadenaPostEnc = encodeURIComponent(cadenaPost);

        if (($('#select-color').size() > 0))
        {
            cadenaPost += "&color="+$('#select-color').val();
        };

        // Llamamos a la página PHP
        xmlHttp.open("GET", "servicios/anyadirAlCarro.php?"+cadenaPost, true);
        // Definimos el método para recoger la respuesta
        xmlHttp.onreadystatechange = respuestaAnyadirArticulo;
        // Enviamos la petición
        xmlHttp.send(null);
    }
    else
    {
        // Si la conexión está ocupada, lo intentamos más tarde
        setTimeout('anyadeArticulo()', 500);
    };
}

function obtenNrFicherosRequeridos()
{
    window.status = "";
    // Continuamos sólo si el objeto xmlHttp no está ocupado
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
    {
        // Codificamos los parámetros a enviar
        var cadenaPostEnc =  encodeURIComponent(cadenaPost);

        // Llamamos a la página PHP
        xmlHttp.open("GET", "servicios/obtenerNrFicherosRequeridos.php?"+cadenaPost, true);
        // Definimos el método para recoger la respuesta
        xmlHttp.onreadystatechange = respuestaObtenNrFicherosRequeridos;
        // Enviamos la petición
        xmlHttp.send(null);
    }
    else
    {
        // Si la conexión está ocupada, lo intentamos más tarde
        window.status = "Conexión ocupada. reintentando...";
        setTimeout('obtenNrFicherosRequeridos()', 500);
    };
}

function respuestaObtenNrFicherosRequeridos()
{
    // Comprobamos que la transacción haya finalizado
    if (xmlHttp.readyState == 4)
    {
        // Comprobamos que la respuesta es ok (estado 200)
        if (xmlHttp.status == 200)
        {
            // Extraemos el XML recibido
            respuestaXML = xmlHttp.responseXML;
	    if (!respuestaXML)
            {
                alert("La respuesta del servidor está vacía.");
            }
            else
            {
                // Obtenemos el elemento root
                xmlRoot = respuestaXML.documentElement;
                var resultado = xmlRoot.getElementsByTagName("resultado")[0].childNodes[0].nodeValue;
                switch (resultado)
                {
                    case 'ok':
                        // Obtenemos los artículos totales
                        var numeroFicheros = parseInt(xmlRoot.getElementsByTagName("nrFicheros")[0].childNodes[0].nodeValue);
                        muestraDialogoFicheros(numeroFicheros);
                        break;
                    case 'ko':
                        var codError = xmlRoot.getElementsByTagName("codError")[0].childNodes[0].nodeValue;
                        var descError = xmlRoot.getElementsByTagName("descError")[0].childNodes[0].nodeValue;
                        alert("Error "+codError+": "+descError);
                        break;
                    default:
                        alert("Error desconocido");
                        break;
                }
            }
        }
        // Si se ha producido un error (estado HTTP distinto de 200) mostramos un mensaje de error
        else
        {
            alert("Se ha producido un error al intentar acceder al servidor: " + xmlHttp.statusText + ". Por favor, vuelva a intentarlo.");
        };
    };
}

function muestraDialogoFicheros(numeroFicheros)
{
    if (numeroFicheros > 0)
    {
        var oDialogoUpload = document.getElementById("divDialogoFicheros");
        var formUpload = document.getElementById("formUpload");
        oDialogoUpload.style.visibility = "visible";
        formUpload.action += "?" + cadenaPost;
    }
    else
    {
        anyadeArticulo();
    }
}
var nrCamposFicheros = 0;
function anyadeCampoFichero()
{
    var camposFicheros = document.getElementById("camposFicheros");
    var inputFichero = document.createElement("input");
    var saltoLinea = document.createElement("br");
    inputFichero.id = "adjFileUpload" + nrCamposFicheros;
    inputFichero.name = "adjFileUpload" + nrCamposFicheros;
    inputFichero.type = "file";
    nrCamposFicheros++;
    camposFicheros.appendChild(inputFichero);
    camposFicheros.appendChild(saltoLinea);
}

function subeFicherosAdjuntos()
{
    var oForm = document.getElementById("formUpload");
    var oDialogoUpload = document.getElementById("divDialogoFicheros");
    oForm.submit();
}

function cierraDialogoFicheros()
{
    var oDialogoUpload = document.getElementById("divDialogoFicheros");
    oDialogoUpload.style.visibility = "hidden";
    anyadeArticulo();
}

function errorAlSubirFicheroAdjunto(mensaje)
{
    alert(mensaje);
}

function ficherosAdjuntosSubidos()
{
    cierraDialogoFicheros();
}
/**
 * Los artículos tipo 1 tienen diferentes precios en función de las características
 * del artículo; por ejemplo, un bolso, puede tener diferentes precios en función 
 * del color que se elija.
 *
 * Al cliente se le da la opción de seleccionar varias unidades del artículo para cada
 * una de las características 
 */
function anyadeArticuloTipo1(idProducto)
{
    var msg = verificaDatos();
    if (msg != "")
    {
        alert(msg);
        return false;
    };
    // Obtenemos las unidades introducidas
    var oPrecios = document.getElementsByName("idPrecio");
    var idPrecio = -1;
    for (var i = 0; i < oPrecios.length; i++)
    {
        if (oPrecios[i].checked)
        {
            idPrecio = oPrecios[i].value;
        }
    }
    if (idPrecio != -1)
    {
        oUnidades = document.getElementsByName("unidades")[0];
        if (oUnidades.value && (oUnidades.value > 0))
        {
            cadenaPost = "id=" + idProducto + "&idp=" + idPrecio + "&uds=" + oUnidades.value;
            obtenNrFicherosRequeridos();
        }
        else
        {
            alert("Debes introducir el número de unidades que deseas añadir al carro.");
        };
    }
    else
    {
        alert("Debes seleccionar una opción.");
    };
};

/**
 * Los artículos tipo 2 tienen un precio por cada unidad del artículo, pero este precio
 * es menor cuantas más cantidades se pidan; por ejemplo, la impresión digital en A4 BN a
 * 1 cara, cuesta 0,08 €/unidad, pero si se piden de 101 a 500 unidades, el precio es de
 * 0,07 €/unidad.
 *
 * Al cliente se le da la opción de seleccionar el número de unidades del artículo que 
 * desea pedir. El precio se calculará en función de las unidades solicitadas.
 *
 * Para este tipo, por tanto, se recoge sólo el número de unidades pedidas 
 */
function anyadeArticuloTipo2(idProducto, idPrecio)
{
    var msg = verificaDatos();
    if (msg != "")
    {
        alert(msg);
        return false;
    };
    // Obtenemos las unidades introducidas
    oUnidades = document.getElementsByName("unidades")[0];
    if (oUnidades.value && (oUnidades.value > 0))
    {
        cadenaPost = "id=" + idProducto + "&idp=" + idPrecio + "&uds=" + oUnidades.value;
        obtenNrFicherosRequeridos();
    }
    else
    {
        alert("Debes introducir el número de unidades que deseas añadir al carro.");
    };
};

/**
 * Los artículos tipo 3 se venden por lotes de unidades; por ejemplo, la impresión de carpetas
 * con 1 solapa, tiene un precio para 500 unidades, otro para 1000 unidades, y así sucesivamente.
 * 
 * Al usuario se le da sólo la opción de que seleccione el lote que quiere comprar.
 *
 * Para este tipo, por tanto, se recoge sólo el lote seleccionado; es decir, el tipo de precio seleccionado. 
 */
function anyadeArticuloTipo3(idProducto)
{
    var msg = verificaDatos();
    if (msg != "")
    {
        alert(msg);
        return false;
    };
    // Obtenemos las unidades introducidas
    var oPrecios = document.getElementsByName("idPrecio");
    var idPrecio = -1;
    for (var i = 0; i < oPrecios.length; i++)
    {
        if (oPrecios[i].checked)
        {
            idPrecio = oPrecios[i].value;
        }
    }
    if (idPrecio != -1)
    {
        cadenaPost = "id=" + idProducto + "&idp=" + idPrecio + "&uds=1";
        obtenNrFicherosRequeridos();
    }
    else
    {
        alert("Debes seleccionar una opción.");
    };
};

/**
 * Productos con precio único. Se tratan igual que los productos de tipo 1. 
 */
function anyadeArticuloTipo4(idProducto, idPrecio)
{
    var msg = verificaDatos();
    if (msg != "")
    {
        alert(msg);
        return false;
    };
    // Obtenemos las unidades introducidas
    oUnidades = document.getElementsByName("unidades_" + idPrecio)[0];
    if (oUnidades.value && (oUnidades.value > 0))
    {
        cadenaPost = "id=" + idProducto + "&idp=" + idPrecio + "&uds=" + oUnidades.value;
        obtenNrFicherosRequeridos();
    }
    else
    {
        alert("Debes introducir el número de unidades que deseas añadir al carro.");
    };
};

function actualizaCarroCompra(articulos, importe)
{
    var oArticulos = document.getElementById("articulosCarro");
    var oImporte = document.getElementById("importeCarro");
    document.getElementById("textoCarroCompra").style.display = "block";
    if (oArticulos && oImporte)
    {
        oArticulos.innerHTML = articulos + ((articulos > 1) ? " artículos" : " artículo");
        var importeStr = "" + redondeaACentimosDeEuro(importe / 10000);
        oImporte.innerHTML = importeStr.replace(/\./, ",") + " &euro;";
		
        timerAnimacion = window.setInterval('animaCarroCompra()', intervalo);
        oArticulos.style.fontWeight = "bold";
        oImporte.style.fontWeight = "bold";
        animaCarroCompra();
    };
};

function animaCarroCompra()
{
    var oArticulos = document.getElementById("articulosCarro");
    var oImporte = document.getElementById("importeCarro");
    oArticulos.style.visibility = "visible";
    oImporte.style.visibility = "visible";

    tiempoAnimacion += intervalo;
    if (tiempoAnimacion > tiempoMaxAnimacion)
    {
        window.clearInterval(timerAnimacion);
        oArticulos.style.fontWeight = "normal";
        oImporte.style.fontWeight = "normal";
        oArticulos.style.visibility = "visible";
        oImporte.style.visibility = "visible";
        tiempoAnimacion = 0;
    }
    else
    {
        setTimeout('document.getElementById("articulosCarro").style.visibility = "hidden"; document.getElementById("importeCarro").style.visibility = "hidden";', intervalo / 2);
    };
};

function respuestaAnyadirArticulo()
{
    // Comprobamos que la transacción haya finalizado
    if (xmlHttp.readyState == 4)
    {
        // Comprobamos que la respuesta es ok (estado 200)
        if (xmlHttp.status == 200)
        {
            // Extraemos el XML recibido
            respuestaXML = xmlHttp.responseXML;
            if (!respuestaXML || !respuestaXML.documentElement)
            {
                alert("La respuesta del servidor está vacía.");
            }
            else
            {
                // Obtenemos el elemento root
                xmlRoot = respuestaXML.documentElement;
                var resultado = xmlRoot.getElementsByTagName("resultado")[0].childNodes[0].nodeValue;
                switch (resultado)
                {
                    case 'ok':
                        // Obtenemos los artículos totales
                        var numeroArticulos = parseInt(xmlRoot.getElementsByTagName("articulos")[0].childNodes[0].nodeValue);
                        var importeAcumulado = parseInt(xmlRoot.getElementsByTagName("importe")[0].childNodes[0].nodeValue);
                        actualizaCarroCompra(numeroArticulos, importeAcumulado);
                        muestraMensaje("Se ha añadido el artículo al carro de la compra.");
                        break;
                    case 'ko':
                        var codError = xmlRoot.getElementsByTagName("codError")[0].childNodes[0].nodeValue;
                        var descError = xmlRoot.getElementsByTagName("descError")[0].childNodes[0].nodeValue;
                        alert("Error "+codError+": "+descError);
                        break;
                    default:
                        alert("Error desconocido");
                        break;
                }
            }
        }
        // Si se ha producido un error (estado HTTP distinto de 200) mostramos un mensaje de error
        else
        {
            alert("Se ha producido un error al intentar acceder al servidor: " + xmlHttp.statusText + ". Por favor, vuelva a intentarlo.");
        };
    }
    else
    {
        setTimeout('respuestaAnyadirArticulo()', 500);
    };
};

function redondeaACentimosDeEuro(cantidad)
{
    var rlength = 2;
    if (cantidad > 8191 && cantidad < 10485)
    {
        cantidad = cantidad - 5000;
        var cantidadRedondeada = Math.round(cantidad * Math.pow(10,rlength)) / Math.pow(10,rlength);
        cantidadRedondeada = cantidadRedondeada + 5000;
    }
    else
    {
        var cantidadRedondeada = Math.round(cantidad * Math.pow(10,rlength)) / Math.pow(10,rlength);
    };
    return cantidadRedondeada;
};

function cambioFormaEntrega(modoEntrega)
{
    var oDireccion = document.getElementById("direccionEnvio");
    switch (modoEntrega)
    {
        case "domicilio":
            oDireccion.style.display = "block";
            break;
		
        case "tienda":
            oDireccion.style.display = "none";
            break;
			
        default:
            oDireccion.style.display = "block";
            break;
    }
}

function cambioUsaDirFacturacion()
{
    var oChk = document.getElementById("chkUsaDirFacturacion");
    var direccion = document.getElementById("txtDireccion");
    var cp = document.getElementById("txtCp");
    var localidad = document.getElementById("txtLocalidad");
    var provincia = document.getElementById("txtProvincia");
	
    if (oChk.checked == true)
    {
        direccion.setAttribute("readonly", "readonly", false);
        cp.setAttribute("readonly", "readonly", false);
        localidad.setAttribute("readonly", "readonly", false);
        provincia.setAttribute("readonly", "readonly", false);

        direccion.value = document.getElementById("txtDireccionFact").value;
        cp.value = document.getElementById("txtCpFact").value;
        localidad.value = document.getElementById("txtLocalidadFact").value;
        provincia.value = document.getElementById("txtProvinciaFact").value;
    }
    else
    {
        direccion.removeAttribute("readonly", false);
        cp.removeAttribute("readonly", false);
        localidad.removeAttribute("readonly", false);
        provincia.removeAttribute("readonly", false);

        direccion.value = "";
        cp.value = "";
        localidad.value = "";
        provincia.value = "";
    }
}

function cambioFormaPago(formaPago)
{
    var oBtnPagar = document.getElementById("botonPagar");
    var oDivTextoTarjeta = document.getElementById("divTextoPagoTarjeta");
    var oDivTextoTransf = document.getElementById("divTextoPagoTransferencia");

    switch (formaPago)
    {
        case "tarjeta":
            oDivTextoTarjeta.style.display = "block";
            oDivTextoTransf.style.display = "none";
            oBtnPagar.value = "Pagar";
            break;
		
        case "transferencia":
            oDivTextoTarjeta.style.display = "none";
            oDivTextoTransf.style.display = "block";
            oBtnPagar.value = "Enviar";
            break;
			
        default:
            oDivTextoTarjeta.style.display = "none";
            oDivTextoTransf.style.display = "block";
            oBtnPagar.value = "Enviar";
            break;
    }
};

function verificaDatos()
{
    // Si existe el combo del color, debe tener un valor
    if ($('#select-color') && ($('#select-color').val() == -1))
    {
        return "Debes seleccionar un color";
    };
    return "";
};


