﻿/// <reference path="jquery-1.3.2.js" />

/*
Muestra u oculta elementos
Parámetros: id
*/
function muestraOculta(id) {
    if ($('#' + id).is(":visible")) {
        $('#' + id).hide(250);
    } else {
        $('#' + id).show(250);
    }
}

/*
Oculta las subfamilias (para buscadores seguiran visibles)
*/
function menuLateral() {
    $(".subfamilias").css("display", "none");
}

/*
Deshabilita el botón enter
*/
function disableEnterKey(e) { var key; if (window.event) { key = window.event.keyCode } else { key = e.which; } return (key != 13); }

/*
Abre una nueva ventana
*/
function ventanaPopup(URL) {
    window.open(URL, "popup", "width=700,height=600,scrollbars=NO")
}


/*
######### SERVICIOS WEB #########
*/

var ruta = location.href.substr(0, location.href.lastIndexOf("/"));

/*
Obtiene provincias
Parámetros: id de país
*/
function obtenProvincias(id) {
    //Limpiamos el dropdown
    document.getElementById('Provincia').length = 0;
    //Indicamos que se están cargando las provincias
    if (id.length > 0) {
        var opt = document.createElement("option");
        opt.text = "Cargando...";
        opt.value = "";
        document.getElementById("Provincia").options.add(opt);    
    }
    //Consultamos el servicio web
    $.ajax({
        url: ruta + "/ws.asmx/obtenProvincias",
        data: ({ id: id }),
        success: function(datosDevueltos) {
            //Eliminamos la opción que indica que se estaban cargando las noticias
            document.getElementById('Provincia').length = 0;
            //Añadimos las provincias
            for (i = 0; i < datosDevueltos.getElementsByTagName('provinciaId').length; i++) {
                var opt = document.createElement("option");
                if (datosDevueltos.getElementsByTagName('provinciaNombre')[i].firstChild) {
                    if (datosDevueltos.getElementsByTagName('provinciaNombre')[i].firstChild.data) {
                        opt.text = datosDevueltos.getElementsByTagName('provinciaNombre')[i].firstChild.data;
                    }
                    if (datosDevueltos.getElementsByTagName('provinciaId')[i].firstChild) {
                        opt.value = datosDevueltos.getElementsByTagName('provinciaId')[i].firstChild.data;
                    }
                }
                document.getElementById("Provincia").options.add(opt);
            }
        }
    });
}
function seleccionaProvincia() {
    document.getElementById("ProvinciaHid").value = document.getElementById("Provincia").value;
}


/*
######### VALIDACIONES (Validators y servicios web) #########
*/

/* Comprueba si el check chk_aut está marcado */
function validaCheck(oSrc, args) {
    args.IsValid = document.getElementById("chk_aut").checked;
}

/*
Comprueba si un e-mail está en BD
Parámetros: e-mail
Devuelve: código de usuario (si el e-mail existe)
*/
function validaEmail(oSrc, args) {
    var valido = false;
    $.ajax({ url: ruta + "/ws.asmx/compruebaEmail", data: ({ email: document.getElementById("Email").value }), async: false,
        success: function(datosDevueltos) {
            if (datosDevueltos.getElementsByTagName('CliCodigo').length > 0) {
                valido = false;
                alert("Ya existe un usuario con esa dirección.\nPinche en 'Olvidé mi contraseña' si desea recuperarla.");
            } else {
                valido = true;
            }
        }
    });
    args.IsValid = valido;
}

/*
Comprueba si el e-mail y contraseña son correctos
Parámetros: e-mail, contraseña
Devuelve: código de usuario (si los datos son correctos)
*/
function hazLogin(oSrc, args) {
    //Cuando se llama desde un validator (registro_usuario.aspx):
    if (args) {
        var loginValido = false;
        $.ajax({ url: ruta + "/ws.asmx/login", data: ({ email: document.getElementById("txtEmail").value, contra: document.getElementById("txtContra").value }), async: false,
            success: function(datosDevueltos) {
                if (datosDevueltos.getElementsByTagName('usuarioId').length > 0) {
                    valido = true;
                    document.getElementById("UsuarioId").value = datosDevueltos.getElementsByTagName('usuarioId')[0].firstChild.data
                } else {
                    valido = false;
                }
            }
        });
        args.IsValid = valido;
    } else {
        //Cuando no se llama desde un validator (comprar.aspx):
        $.ajax({ url: ruta + "/ws.asmx/login", data: ({ email: document.getElementById("txtEmail").value, contra: document.getElementById("txtContra").value }), async: false,
            success: function(datosDevueltos) {
                if (datosDevueltos.getElementsByTagName('usuarioId').length > 0) {
                    valido = true;
                    document.getElementById("UsuarioId").value = datosDevueltos.getElementsByTagName('usuarioId')[0].firstChild.data
                } else {
                    valido = false;
                }
            }
        });
        return valido;
    }
}

/*
Añade un producto a la cesta
Parámetros: id de producto
Devuelve: id de la cesta
*/
function anadeProducto(id) {
    $.ajax({
        url: ruta + "/ws.asmx/anadeProducto",
        data: ({ id: id }),
        success: function(datosDevueltos) {
            for (i = 0; i < datosDevueltos.getElementsByTagName('cestaId').length; i++) {
                alert("Cesta " + datosDevueltos.getElementsByTagName('cestaId')[i].firstChild.data);

                //aqui debemos abrir el overlay de la cesta ya actualizado (datos de BD)
                
                // get handle to the API upon initialization by enabling the "api" variable
                var api = $("div.overlay").overlay({api:true, expose:{color:'#000'},expose:'#000', effect:'apple',
                onBeforeLoad: function() {

                    // grab wrapper element inside content 
                    var wrap = this.getContent().find(".contentWrap");

                    // load the page specified in the trigger 
                    wrap.load("carrito.aspx");
                }
                
                });
                // open the overlay programatically with this API call 
                api.load(); 

            }
        }
    });
}
