jQuery().ready(function (){
    
    obtenerClima();
    
    
        $("#txtToTransfer").val("Hotel Name");
        $("#cboToTransfer").val("select");
        
        $("#txtFechaIn").val("mm/dd/yyyy");
        $("#txtFechaOut").val("mm/dd/yyyy");
        
        $("#txtCheckIn").val("mm/dd/yyyy");
        $("#txtCheckOut").val("mm/dd/yyyy");
        $("#cboHab").val(1);
	
	$("#txtCheckInVuelo").val("mm/dd/yyyy");
        $("#txtCheckOutVuelo").val("mm/dd/yyyy");
	$("#cboOrigenVuelo").val("select");

        $(".tabQuick li a").live('click',function(e){
            e.preventDefault();
            
            var op = $(this).attr("title");
           
            $(".tabQuick li a").removeClass("activo");
            $(this).addClass("activo");
            
            switch(op){
                case "Transfers":
                    $("#frmTraslado").show();
                    $("#frmTour").hide();
                    $("#frmHotel").hide();
                    $("#frmVuelo").hide();                    
                    break;
                case "Tours":
                    $("#frmTour").show();
                    $("#frmTraslado").hide();
                    $("#frmHotel").hide();
                    $("#frmVuelo").hide();  
                    break;
                case "Hotels":
                    $("#frmHotel").show();
                    $("#frmTour").hide();
                    $("#frmTraslado").hide();
                    $("#frmVuelo").hide();  
                    break;
                case "Flights":
                    $("#frmVuelo").show();
                    $("#frmTour").hide();
                    $("#frmHotel").hide();
                    $("#frmTraslado").hide();  
                    break;
                
            }
        
        });      
        
        
        $(".chkViaje").live('click',function(){
		var valor = $(this).val();

		if(valor=="One Way")
			$("#dtOutT").hide();
		else
			$("#dtOutT").show();
	});        
        
        
        //Configuracion de las fechas
        $("input.date-picker").datepicker({minDate:2,onClose:function(input){moverDia($(this).attr("id"));},numberOfMonths: 2});
        
        $("input.date-picker-hotel").datepicker({minDate:1,onClose:function(input){moverDia($(this).attr("id"));},numberOfMonths: 2});
	
	$("input.date-picker-vuelo").datepicker({minDate:1,onClose:function(input){moverDia($(this).attr("id"));},numberOfMonths: 2}); 
        
        
	$(".datepicker").click(function(){
            
		var abuelo = $(this).parent();
		$("td#" + abuelo.attr("id") + " input.date-picker").focus();
	});        
        
	$(".datepicker-hotel").click(function(){
            
		var abuelo = $(this).parent();
		$("td#" + abuelo.attr("id") + " input.date-picker-hotel").focus();
	});
	
	$(".datepicker-vuelo").click(function(){
            
		var abuelo = $(this).parent();
		$("td#" + abuelo.attr("id") + " input.date-picker-vuelo").focus();
	});
	     
        
        function moverDia(id){
			var startDate = $("#"+id).datepicker('getDate');
			if (startDate != null) {

				if(id!="txtCheckInVuelo")
					startDate.setDate(startDate.getDate()+1);
				else
					startDate.setDate(startDate.getDate()+0);

				if(id=="txtFechaIn"){                                        
					$("#txtFechaOut").datepicker('option', 'minDate',startDate);
					$("#txtFechaOut").datepicker('setDate',startDate);                                        
				}
                                
                                if(id=="txtCheckIn"){                                       
					$("#txtCheckOut").datepicker('option', 'minDate',startDate);
					$("#txtCheckOut").datepicker('setDate',startDate);                                        
				}
				
				if(id=="txtCheckInVuelo"){                                       
					$("#txtCheckOutVuelo").datepicker('option', 'minDate',startDate);
					$("#txtCheckOutVuelo").datepicker('setDate',startDate);                                        
				}
				

			}
	}
        
        
        //Con esto cargamos los datos de las excepciones de traslados
	
	var excepciones = new Array();
	var idAfiliado = 0;
	
	$.post("/gets/cargarExcepciones.php",{idAfiliado:idAfiliado},function(data){
		sucess:
			excepciones = data;							
	},'json');
        
        $.ajax({
                url: "/gets/cargarDestinosVenta.php",
                dataType: "xml",
                success: function( xmlResponse ) {
                        var dataOrigen = $( "hotel", xmlResponse ).map(function() {
                                return {
                                        value: $( "nombre", this ).text(),
                                        id: $( "keyword", this ).text()
                                };
                        }).get();
			$( "#txtFromTransfer" ).autocomplete({
				source: dataOrigen,
				minLength: 2,
				select: function( event, ui ) {
				       $("#cboFromTransfer").val(ui.item.id);
				}
			});
                        
                }
        });        
        
        $.ajax({
                url: "/gets/cargarHoteles.php",
                dataType: "xml",
                success: function( xmlResponse ) {
                        var dataDestino = $( "hotel", xmlResponse ).map(function() {
                                return {
                                        value: $( "nombre", this ).text(),
                                        id: $( "keyword", this ).text()
                                };
                        }).get();
			$( "#txtToTransfer" ).autocomplete({
				source: dataDestino,
				minLength: 2,
				select: function( event, ui ) {
				       $("#cboToTransfer").val(ui.item.id);
				       validarSiSoloPrivado();
				}
			});
                        
                }
        });
        
        $.ajax({
                url: "/gets/cargarDestinoHotelTours.php",
                dataType: "xml",
                success: function( xmlResponse ) {
                        var DestinoTours = $( "hotel", xmlResponse ).map(function() {
                                return {
                                        value: $( "nombre", this ).text(),
                                        id: $( "keyword", this ).text()
                                };
                        }).get();
			$( "#txtHotelDestinoTour" ).autocomplete({
				source: DestinoTours,
				minLength: 2,
				select: function( event, ui ) {
				       $("#cboSalidaDesde").val(ui.item.id);
				}
			});
                        
                }
        });        
        
        $.ajax({
                url: "/gets/cargarToursVenta.php",
                dataType: "xml",
                success: function( xmlResponse ) {
                        var dataTours = $( "hotel", xmlResponse ).map(function() {
                                return {
                                        value: $( "nombre", this ).text(),
                                        id: $( "keyword", this ).text()
                                };
                        }).get();
			$( "#txtTour" ).autocomplete({
				source: dataTours,
				minLength: 2,
				select: function( event, ui ) {
				       $("#keyword_tour").val(ui.item.id);
				}
			});
                        
                }
        });
        
        $.ajax({
                url: "/gets/cargarHotelesVenta.php",
                dataType: "xml",
                success: function( xmlResponse ) {
                        var dataHoteles = $( "hotel", xmlResponse ).map(function() {
                                return {
                                        value: $( "nombre", this ).text(),
                                        id: $( "keyword", this ).text()
                                };
                        }).get();
			 $( "#txtHotel" ).autocomplete({
				source: dataHoteles,
				minLength: 2,
				select: function( event, ui ) {
				       $("#keyword_hotel").val(ui.item.id);
				}
			});
                        
                }
        });        
        
        
        $("#txtToTransfer").focus(function(){
            
            var valor = $(this).val();
            
            if(valor=="Hotel Name"){
                $(this).val('');
            }            
            
        });       

	function validarSiSoloPrivado(){
		var valorComboUno = $("#cboFromTransfer").val();
		var valorComboDos = $("#cboToTransfer").val();
		var vectorComboUno = valorComboUno.split('*');
		var vectorComboDos = valorComboDos.split('*');
		
		$("#frmTraslado input[value='Private']").removeAttr("disabled");
		$("#frmTraslado input[value='Share']").removeAttr("disabled");
		$("#frmTraslado input[value='Non stop']").removeAttr("disabled");
		$("#frmTraslado input[value='Private']").attr("checked","checked");
		$(".caja_privado").show();
		$(".caja_compartido").show();
		$(".caja_directo").show();

		if (vectorComboUno[0]=="Hotel" && vectorComboDos[0]=="Hotel"){			
			$(".caja_compartido").hide();
			$(".caja_directo").hide();
			$("#frmTraslado input[value='Share']").attr("disabled","disabled");
			$("#frmTraslado input[value='Non stop']").attr("disabled","disabled");						
		}else{		
			
			if(excepciones.length>0){
				
				for (j=0;j<excepciones.length;j++){					
					if(vectorComboUno[1]==excepciones[j][0]||vectorComboDos[1]==excepciones[j][0]){						
						if(excepciones[j][1]==0){							
							$(".caja_privado").hide();
							$("#frmTraslado input[value='Private']").attr("disabled","disabled");
							$("#frmTraslado input[value='Share']").attr("checked","checked");
						}
						if(excepciones[j][2]==0){							
							$(".caja_compartido").hide();
							$("#frmTraslado input[value='Share']").attr("disabled","disabled");
							if(excepciones[j][1]==0)
								$("#frmTraslado input[value='Non stop']").attr("checked","checked");
						}
						if(excepciones[j][3]==0){							
							$(".caja_directo").hide();
							$("#frmTraslado input[value='Non stop']").attr("disabled","disabled");							
						}
						break;
					}
				}				
			}		
		}
	}
        
        
        //Para cerrar el loading por emergencia
        $(".cerrarLoading").live('click',function(e){
                e.preventDefault();
                $("#ajax_loader").remove();
        });
        
        //Para validar el form del newsletter
        $("#frmNewsletter img").click(function(){
            
            //$("#ajax_loader").remove();
            
            //var loader = jQuery('<div id="ajax_loader"><img src="/recursos/images/ajax-loader.gif" alt="Loading..." /><br/><a class="cerrarLoading" href="#">X</a><p>Please wait, your request we are processing...</p></div>')
		//	.appendTo(".newsletter")
		//	.hide();
            
            $("#frmNewsletter").submit();            
            
        });  
        
        
        $("#frmNewsletter").validate({
                rules: {
			txtNombreNews: "required",
                        txtEmailNews: {
				required: true,
				email: true
			}
		},
		messages: {
			txtNombreNews: "Please enter your Name",
                        txtEmailNews: "Please enter a valid Email address"
		},
                submitHandler: function(form) {                                
                                $("#ajax_loader").show();
				jQuery(form).ajaxSubmit({
					success:       showResponse
				});
		}
        });
	
	
	function showResponse(responseText, statusText, xhr, $form)  {
		$("#txtNombreNews").val('');
		$("#txtEmailNews").val('');
		alert(responseText);
	}
        
        
        //Para validar el formulario de traslados
	$("#frmTraslado").submit(function(){
               
		var from = $("#cboFromTransfer").val();
		var to = $("#cboToTransfer").val();
		var fe_1 = $("#txtFechaIn").val();
		var fe_2 = $("#txtFechaOut").val();
		var numAdultos = $("#cboPax").val();

		if(from=="select"){
			alert("Please select your From");
			$("#txtFromTransfer").focus();
			return false;
		}

		if(to=="select"){
			alert("Please select your To");
                        $("#txtToTransfer").val('');
			$("#txtToTransfer").focus();
			return false;
		}

		if(from==to){
			alert("Please select your To");
			$("#txtToTransfer").val('');
			$("#txtToTransfer").focus();
			return false;
		}


		if(fe_1=="mm/dd/yyyy"){
			alert("Please enter arrival");
			return false;
		}

		if(fe_2=="mm/dd/yyyy"){
			alert("Please enter Departure");			
			return false;
		}
                
		return true;
	});
        
        $("#frmTour").submit(function(){
		var cboCategoria = $("#cboCategoria").val();
		var saliendo = $("#cboSalidaDesde").val();
		var tour = $("#txtTour").val();
                var keyword_tour = $("#keyword_tour").val();

		if(saliendo=="select"&&tour==""&&cboCategoria=="select"){
			alert("Please select your Departing from");
			$("#txtHotelDestinoTour").focus();
			return false;
		}
                
                if(tour==""){
			$("#keyword_tour").val('');
		}
                
                return true;
	});
        
        
        $("#cboHab").change(function(){
		var cboHab = $("#cboHab").val();

		$(".filaHab").hide();

		for(var i=1;i<=cboHab;i++){
			$("#filaHab_"+i).show();
		}

	});

	$(".cboNinoHab").change(function(){
		var id_grl = $(this).attr("id");
		var valores = id_grl.split("_");
		var id = valores[1];
		var numNinos = $(this).val();

		$("#lbEdad").hide();
		$("#cboEdadUno_"+id).hide();
		$("#cboEdadDos_"+id).hide();
		$("#cboEdadTres_"+id).hide();

		if(numNinos==1){
			$("#lbEdad").show();
			$("#cboEdadUno_"+id).show();
		}

		if(numNinos==2){
			$("#lbEdad").show();
			$("#cboEdadUno_"+id).show();
			$("#cboEdadDos_"+id).show();
		}

		if(numNinos==3){
			$("#lbEdad").show();
			$("#cboEdadUno_"+id).show();
			$("#cboEdadDos_"+id).show();
			$("#cboEdadTres_"+id).show();
		}

	});

	$("#frmHotel").submit(function(){
		var fe_1 = $("#txtCheckIn").val();
		var fe_2 = $("#txtCheckOut").val();
		var destino = $("#cboDestino").val();
		var keyword_hotel = $("#keyword_hotel").val();
		var txtHotel = $("#txtHotel").val();

		if(keyword_hotel=="select"){
			$("#txtHotel").val("");
			if(destino=="select"){
				alert("Please select a Destination");
				$("#cboDestino").focus();
				return false;
			}

			if(fe_1=="mm/dd/yyyy"){
				alert("Please select your arrival date");
				$("#txtCheckIn").focus();
				return false;
			}

			if(fe_2=="mm/dd/yyyy"){
				alert("Please select your departure date");
				$("#txtCheckOut").focus();
				return false;
			}
		}

		return true;
	});
	
	$("#cboOrigenVuelo").change(function(){

		var cboOrigenVuelo = $("#cboOrigenVuelo").val();
		var bookTipo = $("#bookTipo").val();

		if(cboOrigenVuelo=="select")
			return false;

		$("#cboDestinoVuelo").empty().append("<option>Wait, Loading destinations...</option>");
		$("#cboDestinoVuelo").attr("disabled","disabled");
		$.post("/includes/cargarDestinosVuelos.php",{cboOrigenVuelo:cboOrigenVuelo,bookTipo:bookTipo},function(data){
			sucess:
			$("#cboDestinoVuelo").empty().append(data);
			$("#cboDestinoVuelo").attr("disabled",false);
		});

	});
	
	
	$(".chkViajeVuelo").click(function(){
		var opViaje = $(this).val();

		if(opViaje=="R")
			$("#dtOutV").show();
		else
			$("#dtOutV").hide();
	});
	
	
	//Con esto abrimos el Chat de la nota de traslado
	$(".abrirChat").live('click',function(e){
		e.preventDefault();
		$(".lpStaticButtonTR a").click();
	});


	$(".menu_agency").click(function(e){
		e.preventDefault();
		//$("#contenedor_agency").toggle();
		$.post('/includes/formAgencias.php',{}, function(data) {
	 		sucess:
	 			$.facebox(data);
	 	});		
	});

	$("#btnSignOut").live('click',function(){
		//$("#contenedor_agency").hide();		
		$.facebox.close();
	});

	$("#btnReenviarPW").live('click',function(e){
		e.preventDefault();
		var txtAgencyId = $("#txtAgencyId").val();

		if(txtAgencyId==""){
			alert("Please type your Id Agency");
			$("#txtAgencyId").focus();
			return false;
		}else{		
			$.post('/includes/reenviarPWAgencias.php',{txtAgencyId:txtAgencyId}, function(data) {
		 		sucess:
		 			if(data==1)
		 				alert("You will receive your information account by email");
		 			else
		 				alert("We are sorry, try again");
		 	});	
		}		

	});

	$("#btnSignIn").live('click',function(){
		var datos = $("#frmSignIn").serialize();
		var txtAgencyId = $("#txtAgencyId").val();
		var txtAgencyPw = $("#txtAgencyPw").val();

		if(txtAgencyId==""){
			alert("Please type your Id Agency");
			$("#txtAgencyId").focus();
			return false;
		}

		if(txtAgencyPw==""){
			alert("Please type your password");
			$("#txtAgencyPw").focus();
			return false;
		}


		$.post("/includes/verificarDatosAgency.php",datos,function(data){
			sucess:
			if(data==0){
				alert("Incorrect information, please try again");
				return false;
			}else{
				window.location.href="/";
			}
		});

		return false;
	});


	
	
	$('#dialog').jqm();
 
        //cerrar popup                
        $("#cerrar").live("click",function(){
            for(var i=0; i<=10; i++){
            $(".sabias_que_"+i).css("display","none");
            }
        });
	        

	//links del menu		      
	$("#websites2_msa_1").live("click", function(){
	    $(window.location).attr('href', 'http://www.lomas-travel.com.mx');
	});
			      
	$("#websites2_msa_2").live("click", function(){
	    $(window.location).attr('href', 'http://www.cancunhoteis.com');
	});
	



                popUp = function(){
                $('.jqModal').trigger('click');
                }
		
		popUp();
			      
		//menu de idiomas
		try {
		oHandler = $("#websites2").msDropDown({mainCSS:'dd2'}).data("dd");
		//alert($.msDropDown.version);
		//$.msDropDown.create("body select");
		$("#ver").html($.msDropDown.version);
		} catch(e) {
		    alert("Error: "+e.message);
		}
		
		
        

});

	//funcion para el clima  
	obtenerClima = function() {        
		var localidad_id = $('#cmbCiudades').val();
		
		if (localidad_id) {
			//parametros para buscar la ciudad
			var parametros = {};
			parametros.op = 'clima';
			parametros.localidad_id = localidad_id;
			
			//llamamos al script php mediante ajax
			$.post('/includes/clima_ajax.php', parametros, function(resultado) {
				if (resultado.error)
					alert(resultado.mensaje);
				else {
					var clima = resultado.clima;
					
					$('#lblFecha').html(clima.fecha);
					$('#lblEstado').html(clima.estado);
					$('#lblTemperatura').html(clima.temperatura);
					$('#imgEstado').html('<img src="/images/iconos_clima/'+clima.codigo+'.png"/>');
                                        
                                        
                                        
                                        $('#lblTemp').html(clima.temperatura+ ' &deg;'+clima.temp);
                                        $('#lblDist').html(clima.dist);
                                        
                                        $('#lblHumedad').html(clima.humedad+'%');
                                        $('#lblVisibilidad').html(clima.visibilidad+' '+clima.dist);
                                        
                                        $('#lblSalida').html(clima.salida);
                                        $('#lblPuesta').html(clima.puesta);
                                        
                                        
                                        $('#lblViento').html(clima.direccion+' '+ clima.speed+' Km/h');
                                        
					
				}
			}, 'json');
		} else {
			alert('Debe escribir un valor');
		}
	}
	
	
	
	
		
	
	
