﻿var date = new Date();
/*Función para agregar la página a los favoritos del navegador*/
function agregarAFavoritos(url,titulo){
if (window.sidebar) {
    window.sidebar.addPanel(titulo, url,"");
  } else if( document.all ) {
    window.external.AddFavorite(url, titulo);
  } else if( window.opera && window.print ) {
    alert("Presione Ctrl + D para agregar a Favoritos en Google Chrome");
    //return true;
  }
}

function body_load() 
{
    // if ((getCookie("tipo_precio") == null) && (document.getElementById("switchprecio")!= null)) //CORREGIDO POR GUSTAVO - MARIO, VERIFICAR
    //document.getElementById("switchprecio").style.display = "block";

    //guardarAsociado(); //CORREGIDO POR GUSTAVO - MARIO, VERIFICAR
    //DoFootSteps();  //CORREGIDO POR GUSTAVO - MARIO, VERIFICAR
    //MostrarDisplayCarrito();  //CORREGIDO POR GUSTAVO - MARIO, VERIFICAR
}


function DoFootSteps()
{
    var mishuellas = new footsteps(5);
    mishuellas.bind_footsteps("misfootsteps", "txtVisitas","a_txtVisitas","sinfootsteps");
    mishuellas.add_to_footsteps(document.title,window.location.href);
}
// CARGAR PRECIO EN FICHA

function ObtenerPrecio(codigo) {
    var url = "func.ajax?a=getprecio&codigo=" + codigo;
    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;
                    procesarPrecio(res);
                }
        }
        req.send(null);
	}
}

function procesarPrecio(respuesta)
{
    if (respuesta.getElementsByTagName("error")[0] != null)
        alert(respuesta.getElementsByTagName("error")[0].childNodes[0].data);
    else
    {
        var precio = respuesta.getElementsByTagName("precio")[0].childNodes[0].data
        if (precio.indexOf("-1") < 0) {
            document.getElementById("articulo_precio").innerHTML = precio;
            document.getElementById("ctl00_ContentPlaceHolder1_a_btn_consultarprecio").style.display = "none";
            document.getElementById("precioLibroDes").style.display = "block";
            document.getElementById("catidadLibroDes").style.display = "block";
            document.getElementById("ctl00_ContentPlaceHolder1_a_btn_comprar").style.display = "block";
        }
        else {
            document.getElementById("ctl00_ContentPlaceHolder1_a_btn_consultarprecio").style.display = "block";
            document.getElementById("precioLibroDes").style.display = "none";
            document.getElementById("catidadLibroDes").style.display = "none";
            document.getElementById("ctl00_ContentPlaceHolder1_a_btn_comprar").style.display = "none";
//            document.getElementById("comprarLibroDes").style.border-top = "2px dotted";
//            document.getElementById("comprarLibroDes").style.border-bottom = "2px dotted";
        }
    }
}

function AgregaAlChango(id) {
    //debugger;
  
    
    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);
    }
}

// ASOCIADOS

var vienede;
function guardarAsociado()
{
	var query = window.location.search.substring(1);
	var qs = parseParams(query);
	if (qs['vienede'])
	{
		vienede=qs['vienede'];
		if(getCookie("vienede")!=vienede)
		{
		var current_date = new Date();
		    //setCookie('vienede', qs['vienede'], 366);
		    set_cookie('vienede', qs['vienede'], current_date.getFullYear() + 1, current_date.getMonth(), current_date.getDate());
		    SendQueryAsoc();
		}
	}
}

// estos lo usa para guardar el vienede de los asociados
// los de arriba los usa para el cambio de idioma
function getCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') {
		    c = c.substring(1,c.length);
		}
		if (c.indexOf(nameEQ) == 0) 
		    return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function setCookie(name,value,expires, options) {
if (options===undefined) { options = {}; }
if ( expires ) {
var expires_date = new Date();
expires_date.setDate(expires_date.getDate() + expires)
}
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) +
( ( options.path ) ? ';path=' + options.path : '' ) +
( ( options.domain ) ? ';domain=' + options.domain : '' ) +
( ( options.secure ) ? ';secure' : '' );
}

function parseParams(query) 
{
	var qsParm = new Array();
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
   		var pos = parms[i].indexOf('=');
   		if (pos > 0) {
      			var key = parms[i].substring(0,pos);
      			var val = parms[i].substring(pos+1);
      			qsParm[key] = val;
      		}
	}
	return qsParm;
}

function SendQueryAsoc() {
    var xmlhttpreq = crearXMLHttpRequest();
    var url = "/actualizaAsoc.aspx?vienede=" + vienede;
    if (xmlhttpreq != null) {
        xmlhttpreq.open("GET", url, true);
        xmlhttpreq.send(null);
    }
}

// FIN ASOCIADOS


//COMPRA


//efectos compra desde ficha
function compraDesdeFicha(imagen, titulo) 
{
//    window.scrollTo(0,0);
//    document.getElementById('imagen_libro_compra').src = imagen; //respuesta.getElementsByTagName("url_imagen_libro")[0].childNodes[0].data;
//    document.getElementById('titulo_libro_compra').innerHTML = titulo; //respuesta.getElementsByTagName("titulo_libro")[0].childNodes[0].data;
//    Effect.toggle('carritoAdd','slide'); 
//    document.getElementById("carritoAddBack").style.display='block';
//    setTimeout("ret()",4000);
}
/*
function ret()
{
    document.getElementById("carritoAddBack").style.display='none';
    Effect.toggle('carritoAdd','slide'); 
}
*/


function AgregaAlChango(id) {
//debugger;
    var cantidad = document.getElementById("select_cantidad")[document.getElementById("select_cantidad").selectedIndex].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 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 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 != 1)
        document.getElementById("ctl00_lbl_cantidad").innerHTML = cantidad + " libros";
    else
        document.getElementById("ctl00_lbl_cantidad").innerHTML = cantidad + " libro";

    document.getElementById("ctl00_lbl_total").innerHTML = precio;
}

function ActualizarDisplayCarrito(precio, cantidad) {
    delete_cookie("carrito_cantidad");
    delete_cookie("carrito_total");

    set_cookie("carrito_cantidad", cantidad);
    set_cookie("carrito_total", precio);

    MostrarDisplayCarrito()
}

function compraDesdeFicha(imagen, titulo, precio) {
    window.scrollTo(0, 0);
    var preciodepagina = document.getElementById("articulo_precio").innerHTML;
    document.getElementById('imagen_libro_compra').src = imagen; //respuesta.getElementsByTagName("url_imagen_libro")[0].childNodes[0].data;
    document.getElementById('titulo_libro_compra').innerHTML = titulo; //respuesta.getElementsByTagName("titulo_libro")[0].childNodes[0].data;
    document.getElementById('display_precio').innerHTML = preciodepagina; //precio;
    Effect.toggle('carritoAdd', 'slide');
    document.getElementById("carritoAddBack").style.display = 'block';
    setTimeout("ret()", 4000);
}

function compraDesdeFichaHome(imagen, titulo, precio) {
    window.scrollTo(0, 0);
   /* var preciodepagina = document.getElementById("articulo_precio").innerHTML; */
    document.getElementById('imagen_libro_compra').src = imagen; //respuesta.getElementsByTagName("url_imagen_libro")[0].childNodes[0].data;
    document.getElementById('titulo_libro_compra').innerHTML = titulo; //respuesta.getElementsByTagName("titulo_libro")[0].childNodes[0].data;
    document.getElementById('display_precio').innerHTML = precio; //precio;
    Effect.toggle('carritoAdd', 'slide');
    document.getElementById("carritoAddBack").style.display = 'block';
    setTimeout("ret()", 4000);
}

function ret() {
    document.getElementById("carritoAddBack").style.display = 'none';
    Effect.toggle('carritoAdd', 'slide');
}


/* redirects busqueda */

/* Obtener el valor de un parámetro determinado */

function getURLParam(strParamName) {
    var strReturn = "";
    var strHref = window.location.href;
    if (strHref.indexOf("?") > -1) {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (
        aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1) {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}

/* Retorna todas las queries con su valor salvo el parámtetro enviado como argumento */

function eliminarParam(strParamName) {
    var cadena = "";
    var strHref = window.location.href;

    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");

    for (var iParam = 0; iParam < aQueryString.length; iParam++) {
        var aParam = aQueryString[iParam].split("=");
        if (aParam[0] != strParamName && aParam[0] != "pg")
            cadena = cadena + aQueryString[iParam] + "&";
    }

    return cadena.substr(0, cadena.length - 1);
}

/* elimina un parametro de un string enviado */
function eliminarP(strval, strParamName) {
    var cadena = "";
    var strHref = strval;

    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");

    for (var iParam = 0; iParam < aQueryString.length; iParam++) {
        var aParam = aQueryString[iParam].split("=");
        if (aParam[0] != strParamName)
            cadena = cadena + aQueryString[iParam] + "&";
    }

    return cadena.substr(0, cadena.length - 1);
}


/* redirige a la página actual agregando el query que crea a partir del Drop Down de orden */

function redirectDDPlus(obj) {
    var idxval = obj.options[obj.selectedIndex].value;
    var idx = idxval.split("=");

    if (idx[1] == "none") {
        var strHref = window.location.href;
        var strQueryString = strHref.split("?");
        strHref = strQueryString[0] + eliminarParam("orden");
    }
    else {
        var strHref = window.location.href;
        var strQueryString = strHref.split("?");
        strHref = strQueryString[0] + eliminarParam("orden") + "&" + obj.options[obj.selectedIndex].value;
    }

    window.location = eliminarP(strHref, "p");  //devuelve la url sin el parametro p que representa la pagina
}

/* Redirige a la página actual excluyendo el parámetro del argumento */

function excluirParam(P) {
    var strHref = window.location.href;
    var strQueryString = strHref.split("?");
    strHref = strQueryString[0] + eliminarParam(P);

    window.location = eliminarP(strHref, "p");  //devuelve la url sin el parametro p que representa la pagina
}

/* Redirige a la misma página agregando el argumento pasado como parámetro */
function redirectPlus(strP) {
    var campos = strP.split("=");
    var strHref = window.location.href;
    var strQueryString = strHref.split("?");
    strHref = strQueryString[0] + eliminarParam(campos[0]) + "&" + strP;
    window.location = eliminarP(strHref, "p");  //devuelve la url sin el parametro p que representa la pagina
}

/* Realiza las acciones con los filtros dependiendo de su presencia o ausencia  */
function filtrar(strP) {
    // URL a la que voy a redirigir
    var strHref = window.location.href;

    var strQueryString = strHref.split("?");

    // Obtengo el array con el query enviado y su valor
    var campos = strP.split("=");

    // Me fijo si el query ya esta en la URL
    if (getURLParam(campos[0]) != "") {
        // Si esta y es un criterio distinto al criterio que se esta enviando, lo cambio por el nuevo
        if (getURLParam(campos[0]) != campos[1]) {

            strHref = strQueryString[0] + eliminarParam(campos[0]) + "&" + strP;
        }
        else
        // Si esta y es el mismo lo saco (elimino el filtro)
        {
            strHref = strQueryString[0] + eliminarParam(campos[0]);
        }
    }
    else
    // Si no esta en la URL, lo agrego
    {
        strHref = strQueryString[0] + eliminarParam(campos[0]) + "&" + strP;
    }

    // Redirijo a la URL armada
    //window.location = strHref;
    window.location = eliminarP(strHref, "p");  //devuelve la url sin el parametro p que representa la pagina
}

function redirectorden() {
    var aaaa = document.getElementById("ctl00_ContentPlaceHolder1_select_orden")[document.getElementById("ctl00_ContentPlaceHolder1_select_orden").selectedIndex].value;
    var bbbb;

    if (aaaa == "A")
        bbbb = "mp";
    if (aaaa == "R")
        bbbb = "re";
    if (aaaa == "B")
        bbbb = "mep";

    redirectPlus("or=" + bbbb);
}
/* fin redirects busqueda */



function abrirpop(codigo, titulo, autor, editorial, proveedor) {
    var url2 = "/consultaprecio.aspx?";
    if (codigo) url2 += "codigo=" + escape(codigo) + "&";
    if (titulo) url2 += "titulo=" + titulo + "&";
    if (autor) url2 += "autor=" + escape(autor) + "&";
    if (editorial) url2 += "editorial=" + escape(editorial) + "&";
    if (proveedor) url2 += "proveedor=" + escape(proveedor) + "&";

    ventana = window.open(url2, "_blank", "resizable,height=200,width=260,top=150,left=150");
}
function bookmark(anchor) {
    if (window.external) {
        window.external.AddFavorite(window.location.href, document.getElementsByTagName("title").item(0).innerHTML);
        return false;
    }
    return true;
}

function abre(URL) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=500,left = 470,top = 150');");
}


