﻿
    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 == 0)
	{
	document.getElementById("Anioalertas").value = 0;
	}
	else
	{
	if(document.getElementById("Anioalertas").value == 0)
	{
	var fecha = new Date();
	document.getElementById("Anioalertas").value = fecha.getFullYear();
	}
	}
	}

	function cambiar_mes()
	{
	if (document.getElementById("Anioalertas").value == 0)
	{
	document.getElementById("Mesalertas").value = 0;
	}
	}

	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._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 + "&idayvueltaalertas=" + (document.getElementById('ridavuelta').checked?"1":"0");
	url = url + "&diasemanaidaalertas=" + document.getElementById('Diasemanaidaalertas').value.toString();
	url = url + "&anioalertas=" + document.getElementById('Anioalertas').value.toString();
	url = url + "&mesalertas=" + document.getElementById('Mesalertas').value.toString();
	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 validar_campos_alertas()
	{
	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() + "&Salidahastaalertas=" + document.getElementById('Salidahastaalertas').value.toString();;

	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';
	}	
	if (error==0)
	{
	document.getElementById('btnguardar').src='images/misc/btn-guardando.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);
	}
	}
	}
	}

	function Ocultar_dia_vuelta()
	{
	//NOTA: aqui habrá que ocultar los combos de mindias y maxdias.
	if(document.getElementById('Idayvueltaalertas').value==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='';
    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);

      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 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';
           }
            
        } 
