$(document).ready( function(){

    var urlPost = (("https:" == document.location.protocol) ? "https://www.mayair.com.mx" : "http://www.mayair.com.mx");

    //seleccionamos por default oneway
    $("#oneway").click();

    //carga los destinos
    $("#from").change( function(){
        var origen=$("#from").val();

        //deshabilito el select #to
        $("#to").attr("disabled","disabled");
        $("#img_procesa2").show(); //mostramos el gif loader

        if (origen=="Select")
        {
            $("#to").empty().append("<option value='Select'>Select a Location</option>");
            $("#check_in_2").val('');

            return false;
        }

        $.post(urlPost+"/includes/ajax.php","metodo=obtener_lista_destinos&origen="+origen, function(data){
        success:
            $("#to").empty().append(data);
            $("#img_procesa2").hide();
            $("#to").removeAttr("disabled");
        });
    });

    $("#roundtrip").click( function(){
        $("#ocultar_returning").show();
        $("#tipo_viaje").val('roundtrip');
        $("#check_in_2").val('');
        $("#num_adultos").val(1);
        $("#num_ninios").val(0);
    });

    $("#oneway").click( function(){
        $("#ocultar_returning").hide();
	$("#tipo_viaje").val('oneway');
	$("#check_in_2").val('');
	$("#num_adultos").val(1);
	$("#num_ninios").val(0);
    });

    

    //cuando se hace submit al form y se despliega el overlay cuando se cotiza
    $("#frm_quickreservation").submit( function(){
        //constante que nos sirve para el num. de pasajeros
        var tipo_viaje=$("#tipo_viaje").val();
        var num_pax=parseInt($("#num_adultos").val())+parseInt($("#num_ninios").val());
        var num_disp=9;
        var num_adultos=parseInt($("#num_adultos").val());
        var num_infantes=parseInt($("#num_infantes").val());       

        if( ($("#from").val())=="Select")
        {
            alert("Please select your Departure Airport.");
            $("#from").focus();
            return false;
	}

        if( ($("#to").val())=="Select")
        {
            alert("Please select your Arrival Airport.");
            $("#to").focus();
            return false;
	}

        if (tipo_viaje=="roundtrip")
        {
            if( ($("#check_in_2").val())=="")
            {
                alert("Please select the date of your return Flight.");
		$("#check_in_2").focus();
		return false;
            }
	}



        if( ($("#adulto").val())=="0")
        {
            alert("Please select the amount of Passengers.");
            $("#num_adultos").focus();
            return false;
	}

        if( num_pax>num_disp)	
        {
            alert("To book a Reservation, please note that the amount of Adult and/or Child\n Passengers cannot be more than " + num_disp + ", on the contrary please select\n another Flight (change Time and/or Date).");
            $("#num_adultos").val("1");
            $("#num_ninios").val("0");
            $("#num_adultos").focus();
            return false;
        }
        
        if(num_infantes>num_adultos){
        	alert("The number of infants can not be greater than the number of adults");
        	$("#num_infantes").val("0");
            $("#num_adultos").focus();
            return false;
        }


        if( ($("#issued").val())=="Select")
        {
            alert("Please select where is your Credit Card from.");
            $("#tipo_pago").focus();
            return false;
        }
		
		var ori = $("#from").val();
		var des = $("#to").val();
		
		
		if( ori=='CUN' && des=='CTM' ) 
		{
			if( !confirm("This flight is only available from Monday to Saturday, please click (ok) to continue with your reservation or click (cancel) to changing your schedule.") )
			{
				return false;
			}
		}
		
		if( ori=='CTM' && des=='CUN' ) 
		{
			if( !confirm("This flight is only available from Monday to Saturday, please click (ok) to continue with your reservation or click (cancel) to changing your schedule.") )
			{
				return false;
			}
		}
		
		if( ori=='CUN' && des=='CPE' ) 
		{
			if( !confirm("This flight is only available on Monday and Friday, please click (ok) to continue with your reservation or click (cancel) to changing your schedule.") )
			{
				return false;
			}
		}
		
		if( ori=='CUN' && des=='CME' ) 
		{
			if( !confirm("This flight is only available on Monday and Friday, please click (ok) to continue with your reservation or click (cancel) to changing your schedule.") )
			{
				return false;
			}
		}

        //si todo sale bien continuamos
        //overlay
        $("#facebox").overlay({
        // custom top position
        top: 260,

        // some mask tweaks suitable for facebox-looking dialogs
        mask: {
        // you might also consider a "transparent" color for the mask
        color: '#666',

        // load mask a little faster
        loadSpeed: 200,

        // very transparent
        opacity: 0.5
        },

        // disable this for modal dialog-type of overlays
        closeOnClick: false,

        // load it immediately after the construction
        load: true
        });
    });

    //calendario js
    $('#check_in').datepicker({showOn: 'button', buttonImage: urlPost+'/images/cal.gif', buttonImageOnly: true, dateFormat: 'd M yy', minDate: 0, maxDate: null});
    $('#check_in_2').datepicker({showOn: 'button', buttonImage: urlPost+'/images/cal.gif', buttonImageOnly: true, dateFormat: 'd M yy', minDate: 0, maxDate: null});

    //tabs
    $("#tabs").tabs();

    //ajax newsletter

    $("#frm_newsletter").submit( function(){
        var datos = $("#frm_newsletter").serialize();

        $("#btn_newsletter").attr("disabled","disabled");
        $.post(urlPost+"/includes/procesa_newsletter.php",datos,function(e){
            sucess:
                if(e==1)
                    alert("Thank you, your email was added successfully in our newaletter system.");
                else
                    alert("We are sorry, something is wrong, you may check and try again");
            
            $("#btn_newsletter").removeAttr("disabled");
        });
        
        return false;
    });
    
    //validar al afiliado
    $("#frm_afil_btn").click( function(){

        var datos = $("#frm_login_agencia").serialize();
        $.post("/includes/procesa_afiliado.php",datos,function(e){
            success:
                if(e==1)
                {
                    $("#frm_status_login").val('bien');
                    //alert("Ahora ya puede reservar como afiliado, en unos momentos será redirigido, Gracias.");
                    $("#frm_login_agencia").submit();
                }
                else
                {
                    alert("Incorrect information, please try again");
                }
        });
        return false;
    });
    
    $("#abrir_cerrar").click(function(){
		$("#dv_afiliado").toggle();
		return false;
	});

    
    
    $("input.date-picker-hotel").datepicker({minDate:parseInt($("#diasBq").val()),onClose:function(input){moverDia2($(this).attr("id"));},numberOfMonths: 1});
    
    function moverDia2(id){
			var startDate = $("#"+id).datepicker('getDate');
			if (startDate != null) {
				
				startDate.setDate(startDate.getDate()+1);
				
				if(id=="txtCheckIn" && $("#"+id).val()!="mm/dd/yyyy"){
					$("#txtCheckOut").datepicker('option', 'minDate',startDate);
					$("#txtCheckOut").datepicker('setDate',startDate);
				}

			}
		}
		
	$("#txtHotel").focus(function(){
		var texto = $(this).val();
		if(texto=="Type your Hotel"){
			$(this).val('');
			$("#keyword_hotel").val("select");
		}
	});

	$("#txtHotel").blur(function(){
		var texto = $(this).val();
		if(texto==""){
			$(this).val('Type your Hotel');
			$("#keyword_hotel").val("select");
		}
	});
	
	
	$("#txtHotel").autocomplete("/includes/cargarHotelesVenta.php", {
		width: 260,
		selectFirst: false
	});
	

	$("#txtHotel").result(function(event, data, formatted) {
		if (data)
			$("#keyword_hotel").val(data[1]);

	});
	
	

	$("#txtHotel").keypress(function(e){
		if(e.keyCode==8){
			$("#keyword_hotel").val("select");
		}

	});


	//scrip que cambia los tabs en el quick-reservation
	$("#link_hotels").click( function(){
		$("#contenedor_vuelo").addClass("hide");
		$("#header_quick_id").removeClass("header_quick")
		$("#header_quick_id").addClass("header_quick_2")
		$("#contenedor_paquete").removeClass("hide");
		return false;
	});
	
	$("#link_flights").click( function(){
		$("#contenedor_paquete").addClass("hide");
		$("#header_quick_id").removeClass("header_quick_2");
		$("#header_quick_id").addClass("header_quick")
		$("#contenedor_vuelo").removeClass("hide");
		return false;
	});
    

});

