﻿var date = new Date();
$(document).ready(function() {
    //    // add fixBroken code to all images on the document
    //    $('img').fixBroken();
    MostrarDisplayCarrito();

    BindFootSteps();
   


});


function BindFootSteps() {
    var mishuellas = new footsteps(5);
    mishuellas.bind_footsteps("ctl00_ContentPlaceHolderContenido_footSteps1_misfootsteps", "txtVisitas", "lnkVisitas", "itemPrecio", "sinfootsteps");
    
        
}

function saveFootSteps() {
    var mishuellas = new footsteps(5);
   var elprecio=$("#itemPrecio");
   var precio=0;
   if (elprecio!=null)
    precio=elprecio.html();
    mishuellas.add_to_footsteps(document.title, window.location.href,"Precio: " + precio);
}
    
    
    $.fn.fixBroken = function(){  
        return this.each(function(){  
        var tag = $(this);  
        var alt_img = 'images/noDisponible.jpg';  
        tag.error(function() { // this adds the onerror event to images  
        tag.attr("src",alt_img); // change the src attribute of the image  
        return true;  
        } );  
        });
    };



    function comprarDesdeFicha(imagen, titulo,link) {
        window.scrollTo(0, 0);
        document.getElementById('imagen_producto_compra').src = imagen;
        document.getElementById('titulo_producto_compra').innerHTML = titulo;
        //Effect.toggle('carritoAdd', 'slide');

        $("#carritoAdd").fadeSliderToggle();
        document.getElementById("carritoAddBack").style.display = 'block';
        setTimeout("toggle()", 4000);
    }

   

    function toggle() {
        $("#carritoAdd").fadeSliderToggle();
        document.getElementById("carritoAddBack").style.display = 'none';
        document.getElementById('imagen_producto_compra').src = "";
    }
    var res;
    function AgregaAlChango(id) {
        //debugger;
        window.scrollTo(0, 0);
        var cantidad = $("#CantCompraEnFicha").attr('value'); 
        var url = "func.ajax?a=add&cod=" + id + "&cant=" + cantidad;
        var req = crearXMLHttpRequest();
        if (req != null) {
            req.open("GET", url, true);
            req.onreadystatechange = function() {
                if (req.readyState == 4)
                    if (req.status == 200) {
                    res = req.responseXML;
                    ProcesarRespuesta(res);
                }
            }
            req.send(null);
        }
    }   

    function agregaAlChangoHome(id) {
        //debugger;
        window.scrollTo(0, 0);
        var cantidad = 1;
        var url = "func.ajax?a=add&cod=" + id + "&cant=" + cantidad;
        var req = crearXMLHttpRequest();
        if (req != null) {
            req.open("GET", url, true);
            req.onreadystatechange = function() {
                if (req.readyState == 4)
                    if (req.status == 200) {
                    res = req.responseXML;
                    ProcesarRespuesta(res);
                }
            }
            req.send(null);
        }
    }

    function crearXMLHttpRequest() {
        var xmlHttp = null;
        if (window.ActiveXObject)
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        else
            if (window.XMLHttpRequest)
            xmlHttp = new XMLHttpRequest();
        return xmlHttp;
    }

    function ProcesarRespuesta(resp) {
        
        if (resp.getElementsByTagName("error")[0] != null)
            alert(resp.getElementsByTagName("error")[0].childNodes[0].data);
        else {
            var precio = res.getElementsByTagName("response")[0].getElementsByTagName("precio_total")[0].childNodes[0].data;
            var cantidad = res.getElementsByTagName("response")[0].getElementsByTagName("cantidad_total")[0].childNodes[0].data;
            

            ActualizarDisplayCarrito(precio, cantidad);
        }
    }
    function abre(pagina) {
        window.open(pagina, 'Formatos', 'resizable=yes,menubar=no,location=no,toolbar=no,status=no,scrollbars=yes,directories=no,width=380,height=460')
    }
    function MostrarDisplayCarrito() {
        
        var cantidad = get_cookie("carrito_cantidad");
        var precio = get_cookie("carrito_total");

        if (cantidad == null)
            cantidad = 0;
        if (precio == null)
            precio = '0.00';
        if (cantidad == 0) {
            $("#ctl00_lnkCerrarCarritoMaster").attr("href", "carrito.aspx?cerrarcompra=no");
            if ($("#ctl00_ContentPlaceHolderContenido_lnkCerrarCompra").length>0)
            {
                $("#ctl00_ContentPlaceHolderContenido_lnkCerrarCompra").css("display", "none");
            }
        }
        else
            $("#ctl00_lnkCerrarCarritoMaster").attr("href", "carrito.aspx?cerrarcompra=si");
        if (cantidad != 1)
            $('#ctl00_cantItemsCarrito').html(cantidad + " items")
        else
            $('#ctl00_cantItemsCarrito').html(cantidad + " item")
        $('#ctl00_totalPrecioCarrito').html("US$" + precio);
        
        
        
    }
    function ActualizarDisplayCarrito(precio, cantidad) {
        delete_cookie("carrito_cantidad");
        delete_cookie("carrito_total");

        set_cookie("carrito_cantidad", cantidad);
        set_cookie("carrito_total", precio);

        MostrarDisplayCarrito()
    }
    /* COOKIES */

    // devuelve el valor de una cookie
    function get_cookie(cookie_name) {
        var results = document.cookie.match(cookie_name + '=(.*?)(;|$)');

        if (results)
            return (unescape(results[1]));
        else
            return null;
    }

    // borra una cookie
    function delete_cookie(cookie_name) {
        var cookie_date = new Date();  // current date & time
        cookie_date.setTime(cookie_date.getTime() - 1);
        document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
    }

    // guarda una cookie
    function set_cookie(name, value, exp_y, exp_m, exp_d, domain) {
        var cookie_string = name + "=" + escape(value);

        if (exp_y) {
            var expires = new Date(exp_y, exp_m, exp_d);
            cookie_string += "; expires=" + expires.toGMTString();
        }

        if (domain)
            cookie_string += "; domain=" + escape(domain);
        cookie_string += "; path=/"

        document.cookie = cookie_string;
    }

    /* FIN COOKIES */
    /* FOOTSTEPS */

    // se encarga de inicializar el sistema de footsteps
    // lo que se guarda en footsteps es un valor asociado a una url
    function footsteps(cantidad) {
        //variables de configuracion de footsteps
        this.Cantidad = 5 //por defecto es 5
        if (cantidad) this.Cantidad = cantidad;

        // si no estan creadas las cookies las crea con el texto null para evitar conflictos con IE mas adelante.
        for (i = 1; i <= this.Cantidad; i++) {
            if (get_cookie("footsteps_" + i) == null)
                set_cookie("footsteps_" + i, "null", date.getFullYear() + 1, date.getMonth(), date.getDate());
        }

        //agrega a footsteps
        this.add_to_footsteps = agregar_a_footsteps
        this.bind_footsteps = bind_footsteps
        this.get_footstep_at = mostrar_footsteps

        this.get_cantidad = function() { return this.Cantidad; }
    }


    function footstep(nombre, link,precio) {
        this.link = link
        this.nombre = nombre
        this.precio=precio
        
    }

    // agrega a footsteps
    function agregar_a_footsteps(nombre, url,precio) {
        // decide si se agrega o no a footsteps
        if (valida_footstep(nombre, url,precio)) {
            var hoy = new Date();
            // primero desplaza los footsteps hasta llegar al final
            for (i = this.Cantidad; i > 1; i--) {
                var aux;
                aux = get_cookie("footsteps_" + (i - 1));
                set_cookie("footsteps_" + i, aux, hoy.getFullYear() + 1, hoy.getMonth(), hoy.getDate());
            }
            // luego guarda en el primer footstep
            set_cookie("footsteps_1", nombre + "~" + precio + "~" + url, hoy.getFullYear() + 1, hoy.getMonth(), hoy.getDate());
        }
    }

    function valida_footstep(nombre, url,precio) {
        // Esta funcion queda a criterio de cada uno
        return true;
    }

    function bind_footsteps(id_todo, id_div, id_a,id_text, sin_visitas) {
        var sem = false;
        var huella

        for (i = 1; i <= this.Cantidad; i++) {
            var elHuellaLink = document.getElementById(id_a + "_" + i);
            var elHuellaDiv = document.getElementById(id_div + "_" + i);
            var elHuellaTodo = document.getElementById(id_todo);
            var elSinVisitas = document.getElementById(sin_visitas);
            var elHuellaText = document.getElementById(id_text + "_" + i);
            huella = this.get_footstep_at(i);
            if (huella != null) {
                sem = true;
                if (elHuellaLink != null) {
                    elHuellaLink.href = huella.link;
                    elHuellaLink.innerHTML = huella.nombre;
                }
                if (elHuellaText != null) {
                    elHuellaText.innerHTML = huella.precio;
                }
                if (elHuellaDiv!=null)
                    elHuellaDiv.style.display = "block";
            }
            else {
                if (elHuellaDiv != null)
                    elHuellaDiv.style.display = "none";
            }

            if (sem) {
                if (elHuellaTodo != null)
                    elHuellaTodo.style.display = "block";
                if (sin_visitas) {
                    if (elSinVisitas != null)
                    elSinVisitas.style.display = "none";
                }
            }
            else {
                if (elHuellaTodo != null)
                    elHuellaTodo.style.display = "none";
                if (sin_visitas) {
                    if (elSinVisitas != null)
                    elSinVisitas.style.display = "block";
                }
            }
        }


    }


    function mostrar_footsteps(num) {
        var aux;
        var vector;
        aux = get_cookie("footsteps_" + num);
        if (aux != null && aux != "" && aux != "undefined" && aux != "null") {
            vector = aux.split("~");
            return new footstep(vector[0], vector[2],vector[1]);
        }
        else
            return null;
    }


    ///* FIN FOOTSTEPS */


    ///* Inicio SOLAPAS FICHA */
    function mostrarSolapa(solapaAMostrar) {
        $("div#detSolapas >h2").hide();
        $("div#detSolapas #header" + solapaAMostrar).show();
        
         $("div#detSolapas >a").show();
         $("div#detSolapas #lnkHeader" + solapaAMostrar).hide();

         $("div#contenidoSolapas .detSolapasCont").hide();
         $("div#contenidoSolapas #solapa" + solapaAMostrar).show();
    }
    ///* fIN SOLAPAS FICHA */



    ///INICIO IMPRIMIR FICHA//
    function printFicha() {
        $(".lienzo").jqprint({ importCSS: true });
    }
    ///FIN IMPRIMIR FICHA//

    ///COMPATIBILIDADES//
    function viewCompatilibilidades(idanchor, table) {
        var tComp = $("#" + table);
        var lComp = $("#" + idanchor);

        if (tComp.hasClass('oculta')) {
            tComp.removeClass('oculta');
            tComp.show(200);
            lComp.text("Compatibilidades [-]");
        }
        else {
            tComp.addClass('oculta');
            tComp.hide(200);
            lComp.text("Compatibilidades [+]");
        }
    }
