﻿// JScript File
/*

En este archivo javascript hay funciones utiles para trabajar en el desarrollo de paginas.
Se debe usar como recurso, pero se pide no incluir el archivo entero en el desarrollo de un sitio.

## Variables globales;
    - Date();
## Cookies
    - get_cookie (cookie_name) //devuelve una cookie
    - delete_cookie(cookie_name) // borra una cookie
    - set_cookie(name, value, exp_y, exp_m, exp_d, domain) // guarda una cookie
## Funciones utiles
    - request_querystring(nombre, url_enviada) // devuelve un parametro de querystring
    - parse_querystring(querystring, nombre) // parsea una linea de querystring 

## Footsteps
    - Crea un objeto footsteps que tiene los siguientes metodos y propiedades
            - this.add_to_footsteps(nombre, url) // guarda en cookies los footstetps
            - this.show_footsteps() // muestra los footsteps en la pagina
    - validar_footstep // es una funcion que se debe definir segun el ambiente de la pagina para decidir
                       // si se guarda en footstep o no.
                       
## Ajax
    - crearXMLHttpRequest() // crear un objeto xmlHttpRequest
    - procesarEventos() // sirve de ejemplo para procesar los datos traidos por el xmlHttpRequest
        // ejemplo de como parsear datos xml desde javascript


*/

/* VARIABLES GLOBALES */
// Son variables globales que se deben tener en cuenta a la hora de utilizar algunas de las funciones dadas abajo.
        var date = new Date();
        var idioma; 
/* FIN VARIABLES GLOBALES */

/* 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 */

/* AJAX */
function crearXMLHttpRequest()
{ 
    var xmlhttp=false; 
    try 
    { 
        xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
    }
    catch(e)
    { 
        try
        { 
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
        catch(E) { xmlhttp=false; }
    }
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp=new XMLHttpRequest(); } 
    return xmlhttp; 
} 

function procesarEventos()
{
    if (xmlhttpreq.readyState == 4) // Si ya esta la conexion
    {
        if (xmlhttpreq.status == 200) // Si la respuesta fue exitosa
        {
            var respuesta = xmlhttpreq.responseXML; //ejemplo de como recuperar un dato xml desde javascript
            document.getElementById('imagen_libro_compra').src = respuesta.getElementsByTagName("url_imagen_libro")[0].childNodes[0].data;
            document.getElementById('titulo_libro_compra').innerHTML = respuesta.getElementsByTagName("titulo_libro")[0].childNodes[0].data;
            document.getElementById('carrDPrecio').innerHTML = 'Precio: $' + respuesta.getElementsByTagName("precio_libro")[0].childNodes[0].data;
        }
    }
}

/* FIN AJAX */
/* FUNCIONES UTILES */

        // devuelve el parametro solicitado de querystring
        // se puede usar tanto con la url del navegador como con una direccion url cualquiera
        // solo hace falta incluirla como parametro.
        function request_querystring(nombre, url_enviada)
        {
            var url;
            var aux;
            var aux1;

            //si me envia una url para comparar uso esa, sino, uso la del navegador
            if (url) url = url_enviada
            else url = window.location.href;
            
            aux = url.split("?");
            if (aux[1] != null) //si hay querystring en la url
            {
                return parse_querystring(aux[1],nombre);
            }
            return null;
        }

        //recive una cadena del tipo "q=1&p=2&j=hola" y devuelve el valor pedido
        function parse_querystring(querystring, nombre, separador_int, separador_ext)
        {
            var aux;
            var aux1;
            var el_separador_int;
            var el_separador_ext;
            
            if (separador_int) el_separador_int = separador_int;
                else el_separador_int = "="; // por defecto es el igual. ej: pag=1
            if (separador_ext) el_separador_ext = separador_ext;
                else el_separador_ext = "&"; // por def es el &. ej: key=harry&pag=1
            
            aux = querystring.split(el_separador_ext);

            for (i = 0; i < aux.length; i++)
            {
                aux1 = aux[i].split(el_separador_int);
                if (aux1[0] == nombre) return aux1[1];
            }
            return null;
        }

/* FIN FUNCIONES UTILES */

/* 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)
{
    this.link = link
    this.nombre = nombre
}

// agrega a footsteps
function agregar_a_footsteps(nombre, url)
{
    // decide si se agrega o no a footsteps
    if (valida_footstep(nombre, url))
    {
        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 + "~" + url,hoy.getFullYear() + 1,hoy.getMonth(),hoy.getDate());
    }
}

function valida_footstep(nombre, url)
{
    // Esta funcion queda a criterio de cada uno
    return true;
}

function bind_footsteps(id_todo, id_div, id_a, sin_visitas)
{
    var sem = false;
    var huella 
    for (i = 1; i <= this.Cantidad; i++)
    {
        huella = this.get_footstep_at(i);
        if (huella != null)
        {
            sem = true;
            document.getElementById(id_a + "_" + i).href = huella.link;
            document.getElementById(id_a + "_" + i).innerHTML = huella.nombre;
            document.getElementById(id_div + "_" + i).style.display = "block";
        }
        else
        {
           document.getElementById(id_div + "_" + i).style.display = "none";
        }
        
        if (sem)
        {
            document.getElementById(id_todo).style.display = "block";
            if (sin_visitas)
                document.getElementById(sin_visitas).style.display = "none";
        }
        else
        {
            document.getElementById(id_todo).style.display = "none";
            if (sin_visitas)
                document.getElementById(sin_visitas).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[1]);
   }
   else
    return null;
}


///* FIN FOOTSTEPS */





