﻿
function Identificacion_Gestion(id_alerta) {
    window.open('UserLogin.aspx?id_alerta=' + id_alerta);
}

function ocultar_mostrar_combos_alertas(seleccionado) {
    if (seleccionado == 1) {//mostrar autocomplete, ocultar combos
        document.getElementById('bloquedestinoalertas').style.display = 'none';
        if (document.getElementById('bloquedestinoalertas2'))
            document.getElementById('bloquedestinoalertas2').style.display = 'none';
        document.getElementById('bloquedestinoalertasauto').style.display = 'block';
        //document.getElementById('bloqueintrodestinoalertas').style.top='-20px';
    }
    else {//ocultar autocomplete, mostrar combos
        document.getElementById('bloquedestinoalertas').style.display = 'block';
        document.getElementById('bloquedestinoalertasauto').style.display = 'none';
        //document.getElementById('bloqueintrodestinoalertas').style.top='5px';
    }
}

function Activar_Opcion_Plazo() {
    document.getElementById('fecha').disabled = true;
    document.getElementById('btnCalendario').style.display = 'none';
    //document.getElementById('btnCalendario').disabled = true;
    document.getElementById('cmbplazoexpiracion').disabled = false;
}

function Activar_Opcion_Fecha() {
    document.getElementById('fecha').disabled = false;
    document.getElementById('btnCalendario').style.display = 'inline';
    //document.getElementById('btnCalendario').disabled = false;
    document.getElementById('cmbplazoexpiracion').disabled = true;
}

function Desactivar_Opciones_Fecha_Plazo() {
    document.getElementById('fecha').disabled = true;
    document.getElementById('btnCalendario').style.display = 'none';
    document.getElementById('cmbplazoexpiracion').disabled = true;
}

function cambiar_anio() {
    if (document.getElementById("Mesalertas").value == '') {
        document.getElementById("Anioalertas").value = '';
    }
    else {
        document.getElementById('Salidadesdealertas').value = '';
        if (document.getElementById("Anioalertas").value == '') {
            var fecha = new Date();
            document.getElementById("Anioalertas").value = fecha.getFullYear();
        }
    }
}

function cambiar_mes() {
    if (document.getElementById("Anioalertas").value == '') {
        document.getElementById("Mesalertas").value = '';
    }
    else {
        document.getElementById('Salidadesdealertas').value = '';
    }
}

function elegir_aeropuerto_alertas(control) {
    window.open('AeropuertosRepeater.aspx?control=' + control);
}

function recoger_aeropuerto(aeropuerto, control) {
    if (control != null) {
        if (control == 'origenalertas')
            document.getElementById('origenalertas').value = aeropuerto;
        if (control == 'destinoalertas')
            document.getElementById('destinoalertas').value = aeropuerto;
    }
}

function recoger_resultadobd() {
    if (GlobalAjaxObjectVal.readyState == 4) {
        if (GlobalAjaxObjectVal.status == 200) { //200 = success
            //pageTracker._trackEvent("ALERTAS" , "CREAR_NUEVA", "", 0);
            pageTracker._trackPageview("/alertas.aspx?acabado=1");
            text = GlobalAjaxObjectVal.responseText;
            var element = document.getElementById('divresultadobd');
            element.innerHTML = text;
            if (document.getElementById('divform') != null)
                document.getElementById('divform').style.display = 'none';
            document.getElementById('divresultadobd').style.display = 'block';
        }
    }
}

function Guardar_Alerta(nuevo) {
    //Llamar por AJAX a alertasgestion.aspx con los valores de la alerta, que estan en el formulario alertasform. nuevo=1
    //la llamada debe devolver una página de error o de ok, cuyo html se recoge del response y :
    // se muestra en un div del alertasform hecho para tal efecto, y se oculta el resto del formulario
    if (window.XMLHttpRequest) //Non-IE Browsers
        GlobalAjaxObjectVal = new XMLHttpRequest(); //Global Variable
    else if (window.ActiveXObject) //IE Browsers
        GlobalAjaxObjectVal = new ActiveXObject("Msxml2.XMLHTTP");  //Global Variable
    else { //Your browsers is not compatible with AJAX
        alert('Your browser is not supported.')
        return; //exit
    }
    //Initialized the Ajax object to access the URL

    url = "AlertasGestion.aspx?nuevo=" + nuevo
    url = url + "&origenalertas=" + document.getElementById('origenalertas').value.toString();
//    if (document.getElementById('tipovuelociudades').checked) {
        url = url + "&destinoalertas=" + document.getElementById('destinoalertas').value.toString();
//    }
//    else {
//        url = url + "&destinozonaalertas=" + document.getElementById('destinozonaalertas').value.toString();
//        if (document.getElementById('destinopais') != null)
//            url = url + "&destinopaisalertas=" + document.getElementById('destinopais').value.toString();
//    }
    url = url + "&preciomaxalertas=" + document.getElementById('preciomaxalertas').value.toString();
    url = url + "&aeropuertoorigencercano=" + (document.getElementById('aeropuerto_origen_cercano').checked ? "1" : "0");
    url = url + "&aeropuertodestinocercano=" + (document.getElementById('aeropuerto_destino_cercano').checked ? "1" : "0");

    url = url + "&idayvueltaalertas=" + (document.getElementById('ridavuelta').checked ? "1" : "0");
    url = url + "&diasemanaidaalertas=" + document.getElementById('Diasemanaidaalertas').value.toString();
    if (document.getElementById('Salidadesdealertas').value != '') {
        url = url + "&salidadesde=" + document.getElementById('Salidadesdealertas').value.toString();
        url = url + "&flexibleida=" + (document.getElementById('flexibleIda').checked ? "1" : "0");
    }
    else {
        url = url + "&anioalertas=" + document.getElementById('Anioalertas').value.toString();
        url = url + "&mesalertas=" + document.getElementById('Mesalertas').value.toString();
    }
    if (document.getElementById('Salidahastaalertas').value != '') {
        url = url + "&salidahasta=" + document.getElementById('Salidahastaalertas').value.toString();
        url = url + "&flexiblevuelta=" + (document.getElementById('flexibleVuelta').checked ? "1" : "0");
    }
    url = url + "&diasemanavueltaalertas=" + document.getElementById('Diasemanavueltaalertas').value.toString();
    url = url + "&mindiasalertas=" + document.getElementById('mindiasalertas').value.toString();
    url = url + "&maxdiasalertas=" + document.getElementById('maxdiasalertas').value.toString();
    url = url + "&frecuencia=" + document.getElementById('frecuenciaalertas').value.toString();
    if (document.getElementById('himagenmv') == null) {
        url = url + "&imagenmv=1";
    } else {
        url = url + "&imagenmv=" + document.getElementById('himagenmv').value.toString();
    }


    function dateToLocaleString(dt) {
        return dt.getDate().toString() + "/" + (dt.getMonth() + 1).toString() + "/" + dt.getFullYear().toString();
    }

    if (document.getElementsByName('fechaexpiracion')[1].checked == true) {
        var fecha = new Date();
        var dias = document.getElementById('cmbplazoexpiracion').value.toString();
        url = url + "&diasexpiracion=" + dias;
    }
    if (document.getElementsByName('fechaexpiracion')[2].checked == true) {
        url = url + "&fechaexpiracion=" + document.getElementById('fecha').value.toString("dd/MM/yyyy");
    }
    if (nuevo == 1)
        url = url + "&email=" + document.getElementById('emailalertas').value.toString();
    else
        url = url + "&id_alerta=" + document.getElementById('hid_alerta').value.toString();

    var url_encode = encodeURI(url);

    GlobalAjaxObjectVal.open("GET", url_encode);
    //Sets the function that is run many times.
    GlobalAjaxObjectVal.onreadystatechange = recoger_resultadobd;
    //Executes the request
    GlobalAjaxObjectVal.send(null);
}

function carga_ajax_inicio_alertas(url, cap) {
    if (window.XMLHttpRequest) //Non-IE Browsers
        GlobalAjaxObject = new XMLHttpRequest(); //Global Variable
    else if (window.ActiveXObject) //IE Browsers
        GlobalAjaxObject = new ActiveXObject("Msxml2.XMLHTTP");  //Global Variable
    else {
        alert('Your browser is not supported.')
        return; //exit
    }
    capa = cap;
    GlobalAjaxObject.open("GET", url);
    GlobalAjaxObject.onreadystatechange = keepChecking_inicio_alertas;
    GlobalAjaxObject.send(null);
}

function keepChecking_inicio_alertas() {
    var element = 'document.getElementById("' + capa + '")';
    if (GlobalAjaxObject.readyState == 4) {
        if (GlobalAjaxObject.status == 200) {
            text = GlobalAjaxObject.responseText;
            eval(element).innerHTML = text;
        }
    }
}

function RedirigirRSS() {
    url = "Creacion-RSS.aspx";

    var oriAlerta;
    var desAlerta;
    if (document.getElementById('origenalertas') == undefined) {
        oriAlerta = document.getElementById('origen').value;
    }
    else {
        oriAlerta = document.getElementById('origenalertas').value;
    }
    if (document.getElementById('origenalertas') == undefined) {
        desAlerta = document.getElementById('destino').value;
    }
    else {
        desAlerta = document.getElementById('destinoalertas').value;
    }
    url = url + "?origenofertas=" + oriAlerta.toString();
    url = url + "&destinofertas=" + desAlerta.toString();
    if (document.getElementById('destinozonaalertas') == undefined) {
        url = url + "&destinozona=";
    }
    else {
        url = url + "&destinozona=" + document.getElementById('destinozonaalertas').value.toString();
    }

    if (document.getElementById('destinopais') != null) {
        url = url + "&destinopais=" + document.getElementById('destinopais').value.toString();
    }
    else {
        url = url + "&destinopais=";
    }
    if (document.getElementById('preciomaxalertas') != null) {
        url = url + "&preciofertas=" + document.getElementById('preciomaxalertas').value.toString();
    }
    else {
        url = url + "&preciofertas=";
    }
    if (document.getElementById('Diasemanaidaalertas') != null) {
        url = url + "&diasemanasalida=" + document.getElementById('Diasemanaidaalertas').value.toString();
    }
    else {
        url = url + "&diasemanasalida=";
    }
    if (document.getElementById('Diasemanavueltaalertas') != null) {
        url = url + "&diasemanallegada=" + document.getElementById('Diasemanavueltaalertas').value.toString();
    }
    else {
        url = url + "&diasemanallegada=";
    }
    if (document.getElementById('mindiasalertas') != null) {
        url = url + "&mindias=" + document.getElementById('mindiasalertas').value.toString();
    }
    else {
        url = url + "&mindias=";
    }
    if (document.getElementById('maxdiasalertas') != null) {
        url = url + "&maxdias=" + document.getElementById('maxdiasalertas').value.toString();
    }
    else {
        url = url + "&maxdias=";
    }

    window.open(url, "RSS");
}

function validar_campos_alertas() {

    //document.getElementById('btnguardar_a').setAttribute('href','javascript:;')
    if (window.XMLHttpRequest) //Non-IE Browsers
        GlobalAjaxObjectVal = new XMLHttpRequest(); //Global Variable
    else if (window.ActiveXObject) //IE Browsers
        GlobalAjaxObjectVal = new ActiveXObject("Msxml2.XMLHTTP");  //Global Variable
    else { //Your browsers is not compatible with AJAX
        alert('Your browser is not supported.')
        return; //exit
    }
    //Initialized the Ajax object to access the URL

    url = "validaciones.aspx?alertas=1&origen=" + document.getElementById('origenalertas').value.toString() + "&destino=" + document.getElementById('destinoalertas').value.toString() + "&preciomax=" + document.getElementById('preciomaxalertas').value.toString() + "&email=" + document.getElementById('emailalertas').value.toString() + "&Salidadesdealertas=" + document.getElementById('Salidadesdealertas').value.toString().replace('dd/mm/aaaa', '') + "&Salidahastaalertas=" + document.getElementById('Salidahastaalertas').value.toString().replace('dd/mm/aaaa', '') + "&chklegales=" + document.getElementById('chklegales').checked;

    if (document.getElementsByName('fechaexpiracion')[2].checked == true) {
        url = url + "&fechaexpiracion=" + document.getElementById('fecha').value.toString("dd/MM/yyyy");
    }

    var url_encode = encodeURI(url);

    GlobalAjaxObjectVal.open("GET", url_encode);
    //Sets the function that is run many times.
    GlobalAjaxObjectVal.onreadystatechange = comprobar_validacion_alertas;
    //Executes the request
    GlobalAjaxObjectVal.send(null);
}

//This function keeps checking for a successful connection
function comprobar_validacion_alertas() {
    if (GlobalAjaxObjectVal.readyState == 4) {
        if (GlobalAjaxObjectVal.status == 200) { //200 = success
            text = GlobalAjaxObjectVal.responseText;
            var element = document.getElementById('validaciones');
            element.innerHTML = text;

            var totalninos = 0;
            var totaladultos = 0;
            var error = 0;

            //mostramos los mensajes de error
            if (document.getElementById('horigenalertas').value == 0) {
                error = 1;
                document.getElementById('avisoorigenalertas').style.display = 'block';
            }
            else {
                document.getElementById('avisoorigenalertas').style.display = 'none';
            }

            document.getElementById('avisodestinoalertas').style.display = 'none';

            if (document.getElementById('hdestinoalertas').value == 0) {
                error = 1;
                document.getElementById('destinoalertasLabel').innerText = 'Destino no encontrado!!';
                document.getElementById('avisodestinoalertas').style.display = 'block';
            }

            if (document.getElementById('hdistintosalertas').value == 0) {
                error = 1;
                document.getElementById('destinoalertasLabel').innerText = 'Origen igual a destino!!';
                document.getElementById('avisodestinoalertas').style.display = 'block';
            }

            if (document.getElementById('hpreciomaxalertas').value == 0) {
                error = 1;
                document.getElementById('avisopreciomaxalertas').style.display = 'block';
            }
            else {
                var precio = document.getElementById('preciomaxalertas').value.toString();
                if (precio.indexOf(".") != -1)
                    document.getElementById('preciomaxalertas').value = precio.substring(0, precio.indexOf("."));
                precio = document.getElementById('preciomaxalertas').value.toString();
                if (precio.indexOf(",") != -1)
                    document.getElementById('preciomaxalertas').value = precio.substring(0, precio.indexOf(","));
                document.getElementById('avisopreciomaxalertas').style.display = 'none';
            }
            if (document.getElementById('hemailalertas').value == 0) {
                error = 1;
                document.getElementById('avisoemailalertas').style.display = 'block';
            }
            else {
                document.getElementById('avisoemailalertas').style.display = 'none';
            }
            if (document.getElementById('hfechaexpiracion').value == 0) {
                error = 1;
                document.getElementById('avisofechaexpiracion').style.display = 'block';
            }
            else {
                document.getElementById('avisofechaexpiracion').style.display = 'none';
            }

            if (document.getElementById('hSalidadesdealertas').value == 0) {
                error = 1;
                document.getElementById('avisosalidadesdealertas').style.display = 'block';
            }
            else {
                document.getElementById('avisosalidadesdealertas').style.display = 'none';
            }

            if (document.getElementById('hSalidahastaalertas').value == 0) {
                error = 1;
                document.getElementById('avisosalidahastaalertas').style.display = 'block';
            }
            else {
                document.getElementById('avisosalidahastaalertas').style.display = 'none';
            }

            document.getElementById('avisolegal').style.display = 'none';

            if (document.getElementById('hlegales').value == 0) {
                error = 1;
                document.getElementById('avisolegal').innerText = 'Debe aceptar las condiciones legales!!';
                document.getElementById('avisolegal').style.display = 'block';
            }

            if (error == 0) {
                document.getElementById('btnguardar').src = 'images/misc/btn-creando.png';
                //esta función llamara por ajax a gestionalerta.aspx, donde se guardará la alerta y se devolverá una página de ok o error, que se mostrará en el div 
                Guardar_Alerta(document.getElementById('hnuevo').value);
            }
            else {
                document.getElementById('btnguardar_a').setAttribute('href', 'javascript:validar_campos_alertas();')
            }
        }
    }
}

function Ocultar_dia_vuelta(valor) {
    //NOTA: aqui habrá que ocultar los combos de mindias y maxdias.
    //alert(document.getElementById('ridavuelta').value);
    if (valor == 0) {
        document.getElementById('bloquediavueltaalertas').style.display = 'none';
        document.getElementById('bloquemindiasalertas').style.display = 'none';
        document.getElementById('bloquemaxdiasalertas').style.display = 'none';
    }
    else {
        document.getElementById('bloquediavueltaalertas').style.display = 'block';
        document.getElementById('bloquemindiasalertas').style.display = 'block';
        document.getElementById('bloquemaxdiasalertas').style.display = 'block';
    }
}

function carga_paises_alertas() {

    var cadena = '';
    var zona = document.getElementById('destinozonaalertas').value;
    if (zona != '' && zona != ZONA_SPAIN) {
        cadena = 'carga_paises.aspx?id_zona=' + document.getElementById('destinozonaalertas').value + '&id_pais=' + document.getElementById('hpaisalertas').value;
        carga_ajax_inicio_alertas(cadena, 'bloquedestinoalertas2')
        document.getElementById('bloquedestinoalertas2').style.display = 'block';
    }
}

function inicializar_form_alerta() {
    asociar_autocomplete();
    ocultar_mostrar_combos_alertas(1);
    carga_paises_alertas();
    inicializar_calendarios();
    if (document.getElementById('hid_alerta').value != '') {
        document.getElementById('btnvolver').style.display = 'inline';
        document.getElementById('bloqueemailalertas').style.display = 'none';
    }
    else {
        document.getElementById('btnvolver').style.display = 'none';
        document.getElementById('bloqueemailalertas').style.display = 'block';
    }
}

var daysBefore = 3;
var daysVuelta = 7;
var currentDate = new Date();
var salidadesdeDate;
var salidahastaDate;

function inicializar_calendarios() {
    /* CALENDARIOS DE RANGO DE FECHAS DE SALIDA */
    currentDate.setDate(currentDate.getDate() + daysBefore);
    //alert('en inicializar calendarios');
    salidadesdeDate = new Date();
    salidadesdeDate = currentDate;
    salidahastaDate = new Date(salidadesdeDate.getFullYear(), salidadesdeDate.getMonth(), salidadesdeDate.getDate() + daysVuelta)
}
function dateToLocaleString(dt, cal) {
    return dt.getDate().toString() + "/" + (dt.getMonth() + 1).toString() + "/" + dt.getFullYear().toString();
}

function stringToDate(strdate) {
    var arr = strdate.split("/");
    var date = new Date();
    if (arr.length = 3) {
        /*var mes =parseInt(arr[1]);
        date.setFullYear(arr[2]);
        date.setMonth(mes-1);
        date.setDate(arr[0]);*/
        date.setTime(Date.parse(arr[1] + "/" + arr[0] + "/" + arr[2]));
        return date;
    }
    else
        return currentDate;
}


function asociar_autocomplete() {

    //AUTOCOMPLETE DE DESTINO
    YAHOO.example.ACFlatData = new function() {
        // Define a custom formatter function
        this.fnCustomFormatter = function(oResultItem, sQuery) {
            var sKey = oResultItem[0];
            var nQuantity = oResultItem[1];
            var sKeyQuery = sKey.substr(0, sQuery.length);
            var sKeyRemainder = sKey.substr(sQuery.length);
            var aMarkup = ["<div class='sample-result'><div class='sample-quantity'>",
            nQuantity,
            "</div>",
            sKeyQuery,
            "",
            sKeyRemainder,
            "</div>"];
            return (aMarkup.join(""));
        };

        // Instantiate one XHR DataSource and define schema as an array:
        //     ["Record Delimiter",
        //     "Field Delimiter"]
        this.oACDS = new YAHOO.widget.DS_XHR("busca.aspx?control=destinoalertas&", ["\n", "\t"]);
        this.oACDS.responseType = YAHOO.widget.DS_XHR.TYPE_FLAT;

        this.oACDS.maxCacheEntries = 0;
        this.oACDS.queryMatchSubset = false;


        // Instantiate second AutoComplete
        this.oAutoComp_des_al = new YAHOO.widget.AutoComplete('destinoalertas', 'ysearchcontainer_des_al', this.oACDS);
        this.oAutoComp_des_al.minQueryLength = 3;
        this.oAutoComp_des_al.delimChar = "";
        this.oAutoComp_des_al.formatResult = this.fnCustomFormatter;
        this.oAutoComp_des_al.typeAhead = false;
        this.oAutoComp_des_al.useShadow = true;
        this.oAutoComp_des_al.useIFrame = true;

    }
    //AUTOCOMPLETE DE ORIGEN
    YAHOO.example.ACFlatData = new function() {
        // Define a custom formatter function
        this.fnCustomFormatter = function(oResultItem, sQuery) {
            var sKey = oResultItem[0];
            var nQuantity = oResultItem[1];
            var sKeyQuery = sKey.substr(0, sQuery.length);
            var sKeyRemainder = sKey.substr(sQuery.length);
            var aMarkup = ["<div class='sample-result'><div class='sample-quantity'>",
            nQuantity,
            "</div>",
            sKeyQuery,
            "",
            sKeyRemainder,
            "</div>"];
            return (aMarkup.join(""));
        };

        // Instantiate one XHR DataSource and define schema as an array:
        //     ["Record Delimiter",
        //     "Field Delimiter"]
        this.oACDS = new YAHOO.widget.DS_XHR("busca.aspx?control=origenalertas&", ["\n", "\t"]);
        this.oACDS.responseType = YAHOO.widget.DS_XHR.TYPE_FLAT;
        this.oACDS.maxCacheEntries = 0;
        this.oACDS.queryMatchSubset = false;

        // Instantiate second AutoComplete
        this.oAutoComp_ori_al = new YAHOO.widget.AutoComplete('origenalertas', 'ysearchcontainer_ori_al', this.oACDS);
        this.oAutoComp_ori_al.minQueryLength = 3;
        this.oAutoComp_ori_al.delimChar = "";
        this.oAutoComp_ori_al.formatResult = this.fnCustomFormatter;
        this.oAutoComp_ori_al.typeAhead = false;
        this.oAutoComp_ori_al.useShadow = true;
        this.oAutoComp_ori_al.useIFrame = true;

    }
}

function MiCuenta() {
    window.open('UserLogin.aspx');
}
function cerrar_session() {
    window.open('UserLogin.aspx?mode=cerrar');
}

function mostrar_opciones() {

    if (document.getElementById('alertas_mas_opciones').style.display == 'none') {
        document.getElementById('alertas_mas_opciones').style.display = 'block';
    } else {
        document.getElementById('alertas_mas_opciones').style.display = 'none';
    }

}


/*function seleccionar_tipo_destino(tipo)
{
if (tipo==1)
{
document.getElementById('checkintrodestinoalertas').checked=true;
ocultar_mostrar_combos();   
}
else
{
document.getElementById('checkintrodestinoalertas').checked=false;
ocultar_mostrar_combos();   
}
}        


function ocultar_mostrar_combos()
{
if(document.getElementById('checkintrodestinoalertas').checked == true)
{//mostrar autocomplete, ocultar combos
document.getElementById('bloque-destino').style.display='none';
document.getElementById('bloquedestinalertas2').style.display='none';
document.getElementById('bloquedestinalertasauto').style.display='inline';
}
else
{//ocultar autocomplete, mostrar combos
document.getElementById('bloque-destino').style.display='inline';
document.getElementById('bloquedestinalertas2').style.display='inline';
document.getElementById('bloquedestinalertasauto').style.display='none';
}
}*/