/*
 * VARIABLES GLOBALES
 */

var isIE = /*@cc_on!@*/false;
var body = $("body").attr("className");
var cookie = {};
var transferType = "T";
cookie.length = 0;

var filters = {
    fecha: function(el) {
          return /^((([0][1-9]|[12][\d])|[3][01])[-\/]([0][13578]|[1][02])[-\/][1-9]\d\d\d)|((([0][1-9]|[12][\d])|[3][0])[-\/]([0][13456789]|[1][012])[-\/][1-9]\d\d\d)|(([0][1-9]|[12][\d])[-\/][0][2][-\/][1-9]\d([02468][048]|[13579][26]))|(([0][1-9]|[12][0-8])[-\/][0][2][-\/][1-9]\d\d\d)$/.test($(el).val());
    }
}

/*
 * FUNCIONES
 */

function numDaysMonth(month,year) {
  var days = 31;
  if (month == 4 || month == 6 || month == 9 || month == 11) 
          days = 30;
  if (month == 2 && (year/ 4) != Math.floor (year/4)) 
          days = 28;
  if (month == 2 && (year/ 4) == Math.floor (year/4))
          days = 29;
  return days;
}


/*
 * CARGA DE PÁGINA
 */

$(document).ready(function(){
    


   /**************************************************
    **************** MÓDULO DE HOTELES ***************
    **************************************************/
    

    $('#i_children, #i_rooms').bind("change", function(){
        if ($('#i_children').val() > 0) {
                $('#children_age').html('<span class="sidebar_label" style="font-weight:bold;">'+$.lang("Edades")+'</span>');
                var i, j = 0;
                var k = 1;
                for (j = 1; j <= $('#i_rooms').val(); j++) {
			for (i = 1; i <= $('#i_children').val(); i++) {
				if ((k % 2) == 0) {
					$('#children_age').append('<div class="i_childfield right">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
				} else {
					$('#children_age').append('<div class="i_childfield left">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
				}
				k++;
			}
		}
                $('#children_age').append('<div class="clearer">&nbsp;</div>');
                $('#children_age').show();             
        } else {
                $('#children_age').html('');
                $('#children_age').hide();
		$('#children_age').css('display','none');
        }
		$('#children_age input.i_childage').bind("keydown", function(){
    			var	val =  $(this).val();
    			return (val.length < 2);
		}); 
    });
    $('#i_children').trigger('change');

    /*
    * COMBOS DEPENDIENTES PARA HOTELES
    */

	if ("hotel" == body) {  
	    $("#i_country").bind("change", function(){
		$.post("destinationList.jsp", {serv_type:"hotel", paisP:this.value},
		    function(xml){
			 $("#i_destination").empty();
			 $("#i_destination").append('<option value="-1">'+$.lang("Por favor, seleccione un destino")+'</option>')
			 $(xml).find("Destination").each(function(x,el) {
			    var code = $(el).attr("code");
			    $(el).find("Name").each(function(x,el) {
				var content = (!isIE)?el.textContent:el.text;
				$("#i_destination").append('<option value="'+code+'">' + content + '</option>');
			    });
			 });
			 if (cookie.length > 0 && cookie["#i_destination"] && cookie["#i_destination"] !='-1'){
			    $("#i_destination").attr("selectedIndex", $('option[value="'+cookie["#i_destination"]+'"]', $("#i_destination")).attr("index"));
			    $("#i_destination").val(cookie["#i_destination"]);
			    $("#i_destination").change();
			 }
			 $("#i_destination").attr("disabled", "");
		    });
		var value = $("#i_country option:selected").text().split('-')[0];

		$("#i_countryName").val(value);
	    });
	}
	
    $("#i_destination").bind("change", function(){
        var valueD = $("#i_destination option:selected").text().split('-')[0];
        $("#i_destinationName").val(valueD); 
    });
    
    /*
     * FORMATO DE HORAS PARA HYDRA 
     */

    $("#i_checkindate, #i_nights, #i_arrivaldate").bind("change", function () {
      /* FECHA IDA*/
      var format = $("#i_dateFormat").val();
      var initDate = $("#i_checkindate").val();
      if ($(this).attr('id') == 'i_arrivaldate'){
          initDate = $("#i_arrivaldate").val();          
      }
      var returnDate = 'yyyymmdd';
        switch(format){
          case "dd/mm/yyyy":
            returnDate = initDate.substr(6,4) + initDate.substr(3,2) + initDate.substr(0,2);
            break;
          case "mm/dd/yyyy":
            returnDate = initDate.substr(6,4) + initDate.substr(0,2) + initDate.substr(3,2);
            break;
          case "yyyy/dd/mm":
            returnDate = initDate.substr(0,4) + initDate.substr(8,2) + initDate.substr(5,2);
            break;
          case "dd/mm/yy":
            returnDate = '20' + initDate.substr(6,2) + initDate.substr(3,2) + initDate.substr(0,2);
            break;
          case "mm/dd/yy":
            returnDate = '20' + initDate.substr(6,2) + initDate.substr(0,2) + initDate.substr(3,2);
            break;
          case "yy/dd/mm":
            returnDate = '20' + initDate.substr(0,2) + initDate.substr(6,2) + initDate.substr(3,2);
            break;
          case "ddmmyyyy":
            returnDate = initDate.substr(4,4) + initDate.substr(2,2) + initDate.substr(0,2);
            break;
          case "mmddyyyy":
            returnDate = initDate.substr(4,4) + initDate.substr(0,2) + initDate.substr(2,2);
            break;
          case "yyyyddmm":
            returnDate = initDate.substr(0,4) + initDate.substr(6,2) + initDate.substr(4,2);
            break;
          default:
               alert('formato incorrecto: '+format);
          break;
        }
        $("#f_checkindate").val(returnDate);    
        
        if ($(this).attr('id') != 'i_arrivaldate'){
            /* FIN FECHA IDA*/

            var month = initDate.substr(3,2);
            var year = initDate.substr(6,4);

            /* FECHA VUELTA*/ 
            var nights = $("#i_nights").val();
            if (nights == 0) alert("noches = 0");
            var newDate = $("#i_checkindate").val(); //convertDateFormat(date);
            if ($(this).attr('id') == 'i_arrivaldate'){
              newDate = $("#i_arrivaldate").val(); //convertDateFormat(date);
            } 
            var temp = new Array();
            temp = newDate.split('/');
            var d1 = temp[0];
            d1 = Number(d1);
            var m1 = temp[1];
            var y1 = temp[2];
            d1 += parseInt(nights);
            if (d1 > 0) {
              while (d1 > numDaysMonth (m1,y1)) {
                d1 -= numDaysMonth (m1,y1);
                m1++;
                if (m1 > 12) {
                  m1 = 1;
                  y1++;
                }
                if (m1 <= 9){
                  m1 = '0'+m1;
                }
              }
            } else {
              while (d1 < 1) {
                m1--;
                if (m1 < 1) {
                   m1 = 12;
                   y1--;
                }
                d1 += numDaysMonth (m1,y1);
              }
            }
            if (d1 <= 9){
                d1 = '0'+d1;
            }
            var f_out = y1+m1+d1;
            $("#f_checkoutdate").val(f_out);  
            /* FIN FECHA VUELTA*/
        }
    });
    
    /*
     * SUBMIT DEL FORMULARIO
     */
    
    $("#motor").bind("submit", function() { 
        $("form#motor #fDestino").val("availabilityHotel.jsp");  
        $("#servType").val("H");
        $("#pagina").val("1");        
        var str = $(this).serialize();
	var a, b = 0;
	var c = 1;
	for (a = 1; a <= $('#i_rooms').val(); a++){
	    for (b = 1; b <= $('#i_children').val(); b++){
		str = str.replace(/agepax/i, "child"+c);   
		c++;
	    }	    
	}        
        
        $.cookie("wlhotel", str);

        var error = true;
        if ($('#i_country').val() == '-1'){
            $("#error_module").fadeIn('slow');
            $("#error_country").fadeIn('slow');
            error = false;
        } else{
            $("#error_country").fadeOut('slow');
        }
        if ($('#i_destination').val() == '-1'){
            $("#error_module").fadeIn('slow');
            $("#error_destination").fadeIn('slow');
            error = false;
        } else{
            $("#error_destination").fadeOut('slow');
        }
        if ($('#i_checkindate').val() == 'dd/mm/yyyy' || $('#i_checkindate').val() ==''){
            $("#error_module").fadeIn('slow');
            $("#error_date").fadeIn('slow');
            error = false;
        } else{
            $("#error_date").fadeOut('slow');
        }
	if ($(".i_childage").length != 0){
	      $(".i_childage").each(function(x,el){
		  if ($(el).val() == '0' || parseInt($(el).val())>= 18){
		      $("#error_module").fadeIn('slow');
		      $("#error_child").fadeIn('slow');  
		      error = false;                
		  } else{
		      $("#error_child").fadeOut('slow');
		  }
	      });
	} else{
	      $("#error_child").fadeOut('slow');
	}
        return error;
        
    });    
    
   /**************************************************
    **************** MÓDULO DE TICKETS ***************
    **************************************************/
    
	if ("ticket" == body) {
	    $('#i_children').bind("change", function(){
		if ($('#i_children').val() > 0) {
			$('#children_age').html('<span class="sidebar_label" style="font-weight:bold;">'+$.lang("Edades")+'</span>');
			var i, j = 0;
			var k = 1;
			for (i = 1; i <= $('#i_children').val(); i++) {
				if ((k % 2) == 0) {
					$('#children_age').append('<div class="i_childfield right">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
				} else {
					$('#children_age').append('<div class="i_childfield left">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
				}
				k++;
			}

			$('#children_age').append('<div class="clearer">&nbsp;</div>');
			$('#children_age').show();             
		} else {
			$('#children_age').html('');
			$('#children_age').hide();
			$('#children_age').css('display','none');
		}
	    });
	    $('#i_children').trigger('change');
	}
    /*
    * COMBOS DEPENDIENTES PARA TICKETS
    */
  
    $("#i_tic_country").bind("change", function(){
        $.post("destinationList.jsp", {serv_type:"ticket", paisP:this.value},
            function(xml){
                 $("#i_tic_destination").empty();
                 $("#i_tic_destination").append('<option value="-1">'+$.lang("Por favor, seleccione un destino")+'</option>')
                 $(xml).find("Destination").each(function(x,el) {
                    var code = $(el).attr("code");
                    $(el).find("Name").each(function(x,el) {
                        var content = (!isIE)?el.textContent:el.text;
                        $("#i_tic_destination").append('<option value="'+code+'">' + content + '</option>');
                    });
                 });
                 if (cookie.length > 0 && cookie["#i_tic_destination"] && cookie["#i_tic_destination"] !='-1'){
                    $("#i_tic_destination").attr("selectedIndex", $('option[value="'+cookie["#i_tic_destination"]+'"]', $("#i_tic_destination")).attr("index"));
                    $("#i_tic_destination").val(cookie["#i_tic_destination"]);
                    $("#i_tic_destination").change();
                 }
                 $("#i_tic_destination").attr("disabled", "");
            });
    });

    $("#i_tic_destination").bind("change", function(){
        $.post("eventList.jsp", {cod_dest:this.value},
            function(xml){
                 $("#i_eventtype").empty();
                 $("#i_eventtype").append('<option value="-1">'+$.lang("Todos")+'</option>')
                 $(xml).find("Classification").each(function(x,el) {
                    var code = $(el).attr("code");
                    var content = (!isIE)?el.textContent:el.text;
                    $("#i_eventtype").append('<option value="'+code+'">' + content + '</option>');
                 });
                 if (cookie.length > 0 && cookie["#i_eventtype"] && cookie["#i_eventtype"] !='-1'){
                    $("#i_eventtype").attr("selectedIndex", $('option[value="'+cookie["#i_eventtype"]+'"]', $("#i_eventtype")).attr("index"));
                    $("#i_eventtype").val(cookie["#i_eventtype"]);
                    $("#i_eventtype").change();
                 }
                 $("#i_eventtype").attr("disabled", "");
            });
    });
    
    $("#i_tic_destination").bind("change", function(){
        var valueD = $("#i_tic_destination option:selected").text();
        $("#i_tic_destinationName").val(valueD); 
    });
    
    /*
     * FORMATO DE HORAS PARA HYDRA 
     */

    $("#i_fromdate, #i_todate").bind("change", function () {
        /* FECHA IDA*/
        var format = $("#i_dateFormat").val();
        var initDate = $(this).val();
        var returnDate = 'yyyymmdd';
        switch(format){
            case "dd/mm/yyyy":
              returnDate = initDate.substr(6,4) + initDate.substr(3,2) + initDate.substr(0,2);
              break;
            case "mm/dd/yyyy":
              returnDate = initDate.substr(6,4) + initDate.substr(0,2) + initDate.substr(3,2);
              break;
            case "yyyy/dd/mm":
              returnDate = initDate.substr(0,4) + initDate.substr(8,2) + initDate.substr(5,2);
              break;
            case "dd/mm/yy":
              returnDate = '20' + initDate.substr(6,2) + initDate.substr(3,2) + initDate.substr(0,2);
              break;
            case "mm/dd/yy":
              returnDate = '20' + initDate.substr(6,2) + initDate.substr(0,2) + initDate.substr(3,2);
              break;
            case "yy/dd/mm":
              returnDate = '20' + initDate.substr(0,2) + initDate.substr(6,2) + initDate.substr(3,2);
              break;
            case "ddmmyyyy":
              returnDate = initDate.substr(4,4) + initDate.substr(2,2) + initDate.substr(0,2);
              break;
            case "mmddyyyy":
              returnDate = initDate.substr(4,4) + initDate.substr(0,2) + initDate.substr(2,2);
              break;
            case "yyyyddmm":
              returnDate = initDate.substr(0,4) + initDate.substr(6,2) + initDate.substr(4,2);
              break;
            default:
                 alert('formato incorrecto: '+format);
            break;
        }
      if ($(this).attr('id') == 'i_fromdate'){
          $("#f_checkindate").val(returnDate);         
      }
      if ($(this).attr('id') == 'i_todate'){
          $("#f_checkoutdate").val(returnDate);         
      }      
    });
    
    /*
     * SUBMIT DEL FORMULARIO
     */
     
     
     if ("ticket" == body) {
         $('.datepick:eq(1)').datepicker({
            buttonImageOnly: true,
            showOn: '',
            showAnim: '',
            duration: '',
            dateFormat: 'dd/mm/yy',
            yearRange: '-0:+3',
            minDate: ''
         });
         
         $('.datepick:eq(0)').datepicker({
            buttonImageOnly: true,
            showOn: '',
            showAnim: '',
            duration: '',
            dateFormat: 'dd/mm/yy',
            yearRange: '-0:+3',
            minDate: '',
            onSelect: function(dateText, inst) { 
                 var dia = new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay).getTime() + (30 *24 *60 *60 *1000);
                 $(".datepick:eq(1)").datepicker('option', 'maxDate', new Date(dia));
                 $("#i_fromdate, #i_todate").change();
            }
         });
         
         $("form#motorTicket").bind("submit", function(){
               var $dateini = $('.datepick:eq(0)').val();
               var $datefin = $('.datepick:eq(1)').val();
     
               var diaini = new Date($dateini.split("/")[2], $dateini.split("/")[1], $dateini.split("/")[0]);
               var diafin = new Date($datefin.split("/")[2], $datefin.split("/")[1], $datefin.split("/")[0]);
               
               // Cálculamos día tope
               var diatope = new Date(diaini.getTime() + (30 *24 *60 *60 *1000));
               
	        var str = $(this).serialize();
		var a, b = 0;
		var c = 1;
		    for (b = 1; b <= $('#i_children').val(); b++){
			str = str.replace(/agepax/i, "child"+c);   
			c++;
		    }	    

		$.cookie("wlhotel", str);
		$("form#motorTicket #fDestino").val("availabilityTicket.jsp");  
		$("#servType").val("E");
		$("#pagina").val("1");      

		var error = true;
		if ($('#i_tic_country').val() == '-1'){
		    $("#error_module").fadeIn('slow');
		    $("#error_country").fadeIn('slow');
		    error = false;
		} else{
		    $("#error_country").fadeOut('slow');
		}
		if ($('#i_tic_destination').val() == '-1'){
		    $("#error_module").fadeIn('slow');
		    $("#error_destination").fadeIn('slow');
		    error = false;
		} else{
		    $("#error_destination").fadeOut('slow');
		}
		if (diafin >= diatope || $('#i_fromdate').val() == 'dd/mm/yyyy' || $('#i_fromdate').val() =='' || $('#i_todate').val() == 'dd/mm/yyyy' || $('#i_todate').val() =='' || (parseInt($('#f_checkoutdate').val()) <= parseInt($('#f_checkindate').val()))){
		     $("#error_module, #error_date").fadeIn('slow').css("opacity", 1);
		    error = false;
		} else{
		    $("#error_date").fadeOut('slow');
		}

		if ($(".i_childage").length != 0){
		      $(".i_childage").each(function(x,el){
			  if ($(el).val() == '0' || parseInt($(el).val())>= 18){
			      $("#error_module").fadeIn('slow');
			      $("#error_child").fadeIn('slow');  
			      error = false;                
			  } else{
			      $("#error_child").fadeOut('slow');
			  }
		      });
		} else{
		      $("#error_child").fadeOut('slow');
		}
		return error;                          
               
         });
     } else {
         $('.datepick').datepicker({
            buttonImageOnly: true,
            showOn: '',
            showAnim: '',
            duration: '',
            dateFormat: 'dd/mm/yy',
            yearRange: '-0:+3',
            minDate: ''
         });
}
    

   /**************************************************
    *************** MÓDULO DE TRANSFERS **************
    **************************************************/
    
	if ("transfer" == body) {
	    $('#i_children').bind("change", function(){
		if ($('#i_children').val() > 0) {
			$('#children_age').html('<span class="sidebar_label" style="font-weight:bold;">'+$.lang("Edades")+'</span>');
			var i, j = 0;
			var k = 1;
			for (i = 1; i <= $('#i_children').val(); i++) {
				if ((k % 2) == 0) {
					$('#children_age').append('<div class="i_childfield right">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
				} else {
					$('#children_age').append('<div class="i_childfield left">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
				}
				k++;
			}

			$('#children_age').append('<div class="clearer">&nbsp;</div>');
			$('#children_age').show();             
		} else {
			$('#children_age').html('');
			$('#children_age').hide();
			$('#children_age').css('display','none');
		}
	    });
	    $('#i_children').trigger('change');
	}  
    
    $("#tipoTrasladoin,#tipoTrasladoout").bind("change click", function(){
        if ($("#tipoTrasladoin:checked").val() == "E") {
            transferType = "T";
            $("#terminalLlegada").show();
            $("#terminalSalida").hide();
            $("#fechaLlegada").show();
            $("#fechaSalida").hide();
        } else if ($("#tipoTrasladoout:checked").val() == "S"){
            transferType = "D";
            $("#terminalSalida").show();
            $("#terminalLlegada").hide();
            $("#fechaSalida").show();
            $("#fechaLlegada").hide();
        }
    });

    /*
    * COMBOS DEPENDIENTES PARA TRANSFERS
    */
   
        
    $("#i_destination_hotel").bind("change", function(){
        var valueH = $("#i_destination_hotel option:selected").text();
        $("#i_hotelName").val(valueH); 
    });
    
    $("#i_departure_hotel").bind("change", function(){
        var valueH2 = $("#i_departure_hotel option:selected").text();
        $("#i_hotelName").val(valueH2); 
    });
   
    $("#i_arrival_country").bind("change", function(){
        var elem = transferType == "D"?'i_departure_destination':'i_arrival_airport';
        if (elem == "i_departure_destination"){
            $("#"+elem).empty();
            $("#i_departure_destination").attr("disabled", "disabled");            
            $("#i_departure_destination").append('<option  value="-1">'+$.lang("Cargando destinos...") + '</option>')
        }else{
            $("#"+elem).empty();
            $("#i_arrival_airport").attr("disabled", "disabled"); 
            $("#i_arrival_airport").append('<option  value="-1">'+$.lang("Cargando aeropuertos...") + '</option>');                    
        }
        $.post("transfers1.jsp", { op: "1", paisP: this.value, type: transferType },
            function(xml){
                 $("#"+elem).empty();
                 $(xml).find("option").each(function(x,el) {
                      var content = (!isIE)?el.textContent:el.text;
                      $("#"+elem).append('<option rel="'+$(el).attr("rel")+'" value="'+$(el).attr("value")+'">' + content + '</option>');
                 });
                 $("#"+elem).attr("disabled", "");
                 if (elem == "i_departure_destination"){
                     if (cookie.length > 0 && cookie["#i_departure_destination"] && cookie["#i_departure_destination"] !='-1'){
                        $("#i_departure_destination").attr("selectedIndex", $('option[value="'+cookie["#i_departure_destination"]+'"]', $("#i_departure_destination")).attr("index"));
                        $("#i_departure_destination").val(cookie["#i_departure_destination"]);
                        $("#i_departure_destination").change();
                     }
                 }else{
                     if (cookie.length > 0 && cookie["#i_arrival_airport"] && cookie["#i_arrival_airport"] !='-1'){
                        $("#i_arrival_airport").attr("selectedIndex", $('option[value="'+cookie["#i_arrival_airport"]+'"]', $("#i_arrival_airport")).attr("index"));
                        $("#i_arrival_airport").val(cookie["#i_arrival_airport"]);
                        $("#i_arrival_airport").change();
                     }                     
                 }
            });
    });
    
    $("#i_departure_country").bind("change", function(){
        $("#i_departure_destination").empty();
        $("#i_departure_destination").attr("disabled", "disabled");         
        $("#i_departure_destination").append('<option  value="-1">'+$.lang("Cargando destinos...") + '</option>');        
        $.post("transfers1.jsp", { op: "1", paisP: this.value, type: transferType },
            function(xml){
                 $("#i_departure_destination").empty();
                 $(xml).find("option").each(function(x,el) {
                      var content = (!isIE)?el.textContent:el.text;
                      $("#i_departure_destination").append('<option rel="'+$(el).attr("rel")+'" value="'+$(el).attr("value")+'">' + content + '</option>');
                 });
                 $("#i_departure_destination").attr("disabled", "");
               if (cookie.length > 0 && cookie["#i_departure_destination"] && cookie["#i_departure_destination"] !='-1'){
                  $("#i_departure_destination").attr("selectedIndex", $('option[value="'+cookie["#i_departure_destination"]+'"]', $("#i_departure_destination")).attr("index"));
                  $("#i_departure_destination").val(cookie["#i_departure_destination"]);
                  $("#i_departure_destination").change();
               }
            });
    });

    // Rellenamos combo de zonas
    $("#i_arrival_airport").bind("change", function(){
        $("#i_destination_zone:visible").empty();       
        $("#i_destination_zone:visible").attr("disabled", "disabled"); 
        $("#i_destination_zone:visible").append('<option  value="-1">'+$.lang("Cargando zonas...") + '</option>');        
        $.post("transfers2.jsp", { op: "1", aeroP: this.value.split("_")[1], destinoP: this.value.split("_")[2] },
            function(xml){
                $("#i_destination_zone:visible").empty();
                $("#i_destination_zone").attr("disabled", "");
                $("#i_destination_zone").append('<option value="-1">' + $.lang("Por favor, seleccione una zona") + '</option>')
                $(xml).find("optgroup").each(function(x,el) {
                    if ($(el).find("option").length > 0) {
                      var contentOptGroup = '<optgroup label="'+$(el).attr("label")+'">';
                      $(el).find("option").each(function(x, el) {
                          var content = (!isIE)?el.textContent:el.text;
                          content = content.toUpperCase();
                          contentOptGroup += '<option rel="'+$(el).attr("rel")+'" value="'+$(el).attr("value")+'">' + content + '</option>';
                      });
                      $("#i_destination_zone").append( contentOptGroup + '</optgroup>');	  
                    }
               });
               $("#i_destination_zone").attr("disabled", "");
               if (cookie.length > 0 && cookie["#i_destination_zone"] && cookie["#i_destination_zone"] !='-1') {
                  $("#i_destination_zone").attr("selectedIndex", $('option[value="'+cookie["#i_destination_zone"]+'"]', $("#i_destination_zone")).attr("index"));
                  $("#i_destination_zone").val(cookie["#i_destination_zone"]);
                  $("#i_destination_zone").change();
               }
            });
    });

    // Rellenamos combo de destinos
    $("#i_departure_destination").bind("change", function(){
        $("#i_departure_zone").empty();    
        $("#i_departure_zone").attr("disabled", "disabled"); 
        $("#i_departure_zone").append('<option  value="-1">'+$.lang("Cargando zonas...") + '</option>');                
        $.post("transfers2.jsp", { op: "2", aeroP: this.value.split("_")[1], destinoP: this.value.split("_")[2] },
            function(xml){
                 $("#i_departure_zone").empty();
                 $("#i_departure_zone").append('<option value="-1">' + $.lang("Por favor, seleccione una zona") + '</option>')
                $(xml).find("optgroup").each(function(x,el) {
                    if ($(el).find("option").length > 0) {
                    var contentOptGroup = '<optgroup label="'+$(el).attr("label")+'">';
                    $(el).find("option").each(function(x, el) {
                            var content = (!isIE)?el.textContent:el.text;
                            content = content.toUpperCase();
                            contentOptGroup += '<option rel="'+$(el).attr("rel")+'" value="'+$(el).attr("value")+'">' + content + '</option>';
                    });
                    $("#i_departure_zone").append( contentOptGroup + '</optgroup>');	  
                    }
                 });
             $("#i_departure_zone").attr("disabled", "");
             if (cookie.length > 0 && cookie["#i_departure_zone"] && cookie["#i_departure_zone"] !='-1') {
                $("#i_departure_zone").attr("selectedIndex", $('option[value="'+cookie["#i_departure_zone"]+'"]', $("#i_departure_zone")).attr("index"));
                $("#i_departure_zone").val(cookie["#i_departure_zone"]);
                $("#i_departure_zone").change();
             }
        });
    });

   $("#i_departure_zone").bind("change", function(){
          if (transferType != 'D') return;
          // Cogemos parï¿½metros
          var pais = $("#i_departure_country").val();
          var destino = $("#i_departure_destination").val();
          $("#i_departure_airport").attr("disabled", "disabled"); 
          $("#i_departure_airport").append('<option  value="-1">'+$.lang("Cargando aeropuertos...") + '</option>');                
          // Lanzamos petición
           $.post("transfers1.jsp", { op: "1", paisP: pais, type: "T", destinoP:  destino.split("_")[2]},
          function(xml){
               $("#i_departure_airport").empty();
               $(xml).find("option").each(function(x,el) {
                    var content = (!isIE)?el.textContent:el.text;
                    $("#i_departure_airport").append('<option rel="'+$(el).attr("rel")+'" value="'+$(el).attr("value")+'">' + content + '</option>');
               });
            $("#i_departure_airport").attr("disabled", "");
            if (cookie.length > 0 && cookie["#i_departure_airport"] && cookie["#i_departure_airport"] != '-1'){
                $("#i_departure_airport").attr("selectedIndex", $('option[value="'+cookie["#i_departure_airport"]+'"]', $("#i_departure_airport")).attr("index"));
                $("#i_departure_airport").val(cookie["#i_departure_airport"]);
                $("#i_departure_airport").change();                      
            }
           });
   });
   
   $("#i_departure_zone").bind("change", function(){
        $("#i_departure_hotel").empty();
        $("#i_departure_hotel").attr("disabled", "disabled");
        $("#i_departure_hotel").append('<option  value="-1">'+$.lang("Cargando hoteles...") + '</option>');
        $.getJSON('transfers3.jsp?zonaP='+$("#i_departure_zone").find(" option:selected").val(),function(data){
            $("#i_departure_hotel").html('<option  value="-1">'+$.lang("Por favor, seleccione un hotel") + '</option>');            
            $.each(data.hotelzone, function(x,el) {
                var lat = this.latitude || '';
                var lng = this.longitude || '';
                var code = this.code;
                var name = this.name;
                if (this.code)
                    $("#i_departure_hotel").append('<option rel="'+lat+"#"+lng+'" value="'+code+'">'+name+'</option>');
                    $("#i_departure_hotel").attr("disabled", "");                
            });
            $("#i_departure_hotel").append('<option class="bg_color6" value="Other">'+$.lang("Otro lugar de recogida") + '</option>');   
            if (cookie.length > 0 && cookie["#i_departure_hotel"]) {
                $("#i_departure_hotel").attr("selectedIndex", $('option[value="'+cookie["#i_departure_hotel"]+'"]', $("#i_departure_hotel")).attr("index"));
                $("#i_departure_hotel").val(cookie["#i_departure_hotel"]);
                $("#i_departure_hotel").change();
            }            
        });
   });
   
    $("#i_destination_zone").bind("change", function(){
        $("#i_destination_hotel").empty();
        $("#i_destination_hotel").attr("disabled", "disabled");
        $("#i_destination_hotel").append('<option  value="-1">'+$.lang("Cargando hoteles...") + '</option>');
        $.getJSON('transfers3.jsp?zonaP='+$(this).find(" option:selected").val(),function(data){
            $("#i_destination_hotel").html('<option  value="-1">'+$.lang("Por favor, seleccione un hotel") + '</option>');            
            $.each(data.hotelzone, function(x,el) {
                var lat = this.latitude || '';
                var lng = this.longitude || '';
                var code = this.code;
                var name = this.name;
                if (this.code)
                    $("#i_destination_hotel").append('<option rel="'+lat+"#"+lng+'" value="'+code+'">'+name+'</option>');
                    $("#i_destination_hotel").attr("disabled", "");                
            });
            $("#i_destination_hotel").append('<option class="bg_color6" value="Other">'+$.lang("Otro lugar de recogida") + '</option>'); 
            if (cookie.length > 0 && cookie["#i_destination_hotel"]) {
                $("#i_destination_hotel").attr("i_destination_hotel", $('option[value="'+cookie["#i_destination_hotel"]+'"]', $("#i_destination_hotel")).attr("index"));
                $("#i_destination_hotel").val(cookie["#i_destination_hotel"]);
                $("#i_destination_hotel").change();
            }
        });
    });

        $("#i_departdate").bind("change", function () {
          /* FECHA IDA*/
          var format = $("#i_dateFormat").val();
          var finalDate = $("#i_departdate").val();          
          var returnDate = 'yyyymmdd';
            switch(format){
              case "dd/mm/yyyy":
                returnDate = finalDate.substr(6,4) + finalDate.substr(3,2) + finalDate.substr(0,2);
                break;
              case "mm/dd/yyyy":
                returnDate = finalDate.substr(6,4) + finalDate.substr(0,2) + finalDate.substr(3,2);
                break;
              case "yyyy/dd/mm":
                returnDate = finalDate.substr(0,4) + finalDate.substr(8,2) + finalDate.substr(5,2);
                break;
              case "dd/mm/yy":
                returnDate = '20' + finalDate.substr(6,2) + finalDate.substr(3,2) + finalDate.substr(0,2);
                break;
              case "mm/dd/yy":
                returnDate = '20' + finalDate.substr(6,2) + finalDate.substr(0,2) + finalDate.substr(3,2);
                break;
              case "yy/dd/mm":
                returnDate = '20' + finalDate.substr(0,2) + finalDate.substr(6,2) + finalDate.substr(3,2);
                break;
              case "ddmmyyyy":
                returnDate = finalDate.substr(4,4) + finalDate.substr(2,2) + finalDate.substr(0,2);
                break;
              case "mmddyyyy":
                returnDate = finalDate.substr(4,4) + finalDate.substr(0,2) + finalDate.substr(2,2);
                break;
              case "yyyyddmm":
                returnDate = finalDate.substr(0,4) + finalDate.substr(6,2) + finalDate.substr(4,2);
                break;
              default:
                   alert('formato incorrecto: '+format);
              break;
            }
            $("#f_checkoutdate").val(returnDate);    
        });
        $("#i_departdate_out").bind("change", function () {
          /* FECHA IDA*/
          var format = $("#i_dateFormat").val();
          var finalDate = $("#i_departdate_out").val();          
          var returnDate = 'yyyymmdd';
            switch(format){
              case "dd/mm/yyyy":
                returnDate = finalDate.substr(6,4) + finalDate.substr(3,2) + finalDate.substr(0,2);
                break;
              case "mm/dd/yyyy":
                returnDate = finalDate.substr(6,4) + finalDate.substr(0,2) + finalDate.substr(3,2);
                break;
              case "yyyy/dd/mm":
                returnDate = finalDate.substr(0,4) + finalDate.substr(8,2) + finalDate.substr(5,2);
                break;
              case "dd/mm/yy":
                returnDate = '20' + finalDate.substr(6,2) + finalDate.substr(3,2) + finalDate.substr(0,2);
                break;
              case "mm/dd/yy":
                returnDate = '20' + finalDate.substr(6,2) + finalDate.substr(0,2) + finalDate.substr(3,2);
                break;
              case "yy/dd/mm":
                returnDate = '20' + finalDate.substr(0,2) + finalDate.substr(6,2) + finalDate.substr(3,2);
                break;
              case "ddmmyyyy":
                returnDate = finalDate.substr(4,4) + finalDate.substr(2,2) + finalDate.substr(0,2);
                break;
              case "mmddyyyy":
                returnDate = finalDate.substr(4,4) + finalDate.substr(0,2) + finalDate.substr(2,2);
                break;
              case "yyyyddmm":
                returnDate = finalDate.substr(0,4) + finalDate.substr(6,2) + finalDate.substr(4,2);
                break;
              default:
                   alert('formato incorrecto: '+format);
              break;
            }
            $("#f_checkoutdate_out").val(returnDate);    
        });
    /*
     * SUBMIT DEL FORMULARIO
     */
    
    $("#motorTransfer").bind("submit", function() {
        var error = true;

        if ($("#tipoTrasladoin:checked").val() == "E") {
            $("#error_hour_to_out").fadeOut('slow');
            $("#error_date_to_out").fadeOut('slow');    
            $("#error_destination").fadeOut('slow');            
            if ($("#i_departdate").val() != "" && $("#i_departdate").val() != "dd/mm/yyyy"){
                $("#transfer_type").val('E/S');
            } else {
                $("#transfer_type").val('E');            
            }
            
            if ($('#i_arrival_country').val() == '-1'){
                $("#error_module, #error_country").fadeIn('slow');error = false;
            } else{
                $("#error_country").fadeOut('slow');
            }
            if ($('#i_arrival_airport').val() == '-1'){
                $("#error_module, #error_airport").fadeIn('slow');error = false;
            } else{
                $("#error_airport").fadeOut('slow');
            }
            if ($('#i_destination_zone').val() == '-1'){
                $("#error_module, #error_zone").fadeIn('slow');error = false;
            } else{
                $("#error_zone").fadeOut('slow');
            }             
            if ($('#i_arrivaldate').val() == 'dd/mm/yyyy' || $('#i_arrivaldate').val() =='' || !filters.fecha($('#i_arrivaldate'))){
                $("#error_module, #error_date").fadeIn('slow');error = false;
            } else{
                $("#error_date").fadeOut('slow');                
            }  
            if ($('#i_hh_from').val() == 'hh' || $('#i_mm_from').val() =='mm'){
                $("#error_module, #error_hour").fadeIn('slow');error = false;
            } else{
                $("#error_hour").fadeOut('slow');
            }
            if ($('#i_departdate').val() != 'dd/mm/yyyy' && $('#i_departdate').val() !=''){
                var arrivalDate = $('#i_arrivaldate').val()
                arrivalDate = arrivalDate.substr(6,4) + arrivalDate.substr(3,2) + arrivalDate.substr(0,2) + $('#i_hh_from').val() + $('#i_mm_from').val();                   
                var departDate = $('#i_departdate').val()
                departDate = departDate.substr(6,4) + departDate.substr(3,2) + departDate.substr(0,2) + $('#i_hh_to').val() + $('#i_mm_to').val();                
                if ($('#i_hh_to').val() == 'hh' || $('#i_mm_to').val() =='mm'){
                    $("#error_module, #error_hour_to").fadeIn('slow');error = false;
                } else{
                    $("#error_hour_to").fadeOut('slow');
                }
                if (!filters.fecha($('#i_departdate'))){            
                    $("#error_module, #error_date").fadeIn('slow');error = false;
                } else {
                    $("#error_date_to").fadeOut('slow');                
                }      
                if (arrivalDate > departDate){
                    $("#error_module, #error_compare_date").fadeIn('slow');error = false;                    
                } else {
                    $("#error_compare_date").fadeOut('slow');                                    
                }
            } else{
                  $("#error_hour_to").fadeOut('slow');
                  $("#error_date_to").fadeOut('slow');                                
            }
            $(".i_childage").each(function(x,el){
                if ($(el).val() == '0' || parseInt($(el).val())>= 18){
                    $("#error_module, #error_child").fadeIn('slow');error = false;                
                } else{
                    $("#error_child").fadeOut('slow');
                }
            });
        } else if ($("#tipoTrasladoout:checked").val() == "S"){
            $("#transfer_type").val('S'); 
            $("#error_hour_to").fadeOut('slow');
            $("#error_date_to").fadeOut('slow');
            $("#error_hour").fadeOut('slow');
            $("#error_date").fadeOut('slow');             
            if ($('#i_departure_country').val() == '-1'){
                $("#error_module, #error_country").fadeIn('slow');error = false;
            } else{
                $("#error_country").fadeOut('slow');
            }
            if ($('#i_departure_destination').val() == '-1'){
                $("#error_module, #error_destination").fadeIn('slow');error = false;
            } else{
                $("#error_destination").fadeOut('slow');
            }              
            if ($('#i_departure_zone').val() == '-1'){
                $("#error_module, #error_zone").fadeIn('slow');error = false;
            } else{
                $("#error_zone").fadeOut('slow');
            } 
            if ($('#i_departure_airport').val() == '-1'){
                $("#error_module, #error_airport").fadeIn('slow');error = false;
            } else{
                $("#error_airport").fadeOut('slow');
            }            
            if ($('#i_departdate_out').val() == 'dd/mm/yyyy' || $('#i_departdate_out').val() =='' || !filters.fecha($('#i_departdate_out'))){
                $("#error_module, #error_date_to_out").fadeIn('slow');error = false;
            } else{
                $("#error_date_to_out").fadeOut('slow');                
            } 
            if ($('#i_hh_to_out').val() == 'hh' || $('#i_mm_to_out').val() =='mm'){
                $("#error_module, #error_hour_to_out").fadeIn('slow');error = false;
            } else{
                $("#error_hour_to_out").fadeOut('slow');
            }     
	    if ($(".i_childage").length != 0){
	        $(".i_childage").each(function(x,el){
	  	    if ($(el).val() == '0' || parseInt($(el).val())>= 18){
			$("#error_module").fadeIn('slow');
			$("#error_child").fadeIn('slow');  
			error = false;                
		    } else{
			$("#error_child").fadeOut('slow');
		    }
		});
	    } else{
	        $("#error_child").fadeOut('slow');
	    }         
        }
        var str = $(this).serialize();
	var a, b = 0;
	var c = 1;
	    for (b = 1; b <= $('#i_children').val(); b++){
		str = str.replace(/agepax/i, "child"+c);   
		c++;
	    }	    
        
        $.cookie("wlhotel", str);
        $("#servType").val("T");
        $("form#motorTransfer #fDestino").val("availabilityTransfer.jsp");  
      
        return error;
    });
    
    
    /*
     * GUARDAMOS DATOS EN LA COOKIE
     */

    var temp = $.cookie("wlhotel");
    if (temp){
        var items = temp.split("&");
        for (var i in items) {
            var key = "#" + items[i].split("=")[0];
            var value = items[i].split("=")[1];
            $(key).val(value); 
            cookie[key] = value;
            cookie.length++;
        }
        //Paises
        $("#i_country").val(cookie["#i_country"]);
        $("#i_country").change();
        $("#i_arrival_country").val(cookie["#i_arrival_country"]);
        $("#i_arrival_country").change();
        $("#i_tic_country").val(cookie["#i_tic_country"]);
        $("#i_tic_country").change();        
        $("#tipoTrasladoin,#tipoTrasladoout").bind("click", function() {        
          if ($("#tipoTrasladoin:checked").val() == "E") {        
              $("#i_arrival_country").val(cookie["#i_arrival_country"]);
              $("#i_arrival_country").change();
          }            
          if ($("#tipoTrasladoout:checked").val() == "S") {        
              $("#i_departure_country").val(cookie["#i_departure_country"]);
              $("#i_departure_country").change();        
          }
        });
        //Fechas
        if(cookie["#i_arrivaldate"]){
            $("#i_arrivaldate").val(cookie["#i_arrivaldate"].replace(/%2F/g, "/"));
            $("#i_arrivaldate").change();
        }
        if(cookie["#i_departdate"]){
            $("#i_departdate").val(cookie["#i_departdate"].replace(/%2F/g, "/"));
            $("#i_departdate").change();            
        }
        if(cookie["#i_departdate_out"]){
            $("#i_departdate_out").val(cookie["#i_departdate_out"].replace(/%2F/g, "/")); 
            $("#i_departdate_out").change();    
        }
        if(cookie["#i_checkindate"]){
            $("#i_checkindate").val(cookie["#i_checkindate"].replace(/%2F/g, "/"));
            $("#i_checkindate").change();
        }       
        if(cookie["#i_hh_to"]){
            $("#i_hh_to").val(cookie["#i_hh_to"]);
            $("#i_hh_to").change();
        }    
        if(cookie["#i_mm_to"]){
            $("#i_mm_to").val(cookie["#i_mm_to"]);
            $("#i_mm_to").change();
        }
        if(cookie["#i_fromdate"]){
            $("#i_fromdate").val(cookie["#i_fromdate"].replace(/%2F/g, "/"));
            $("#i_fromdate").change();
        }    
        if(cookie["#i_todate"]){
            $("#i_todate").val(cookie["#i_todate"].replace(/%2F/g, "/"));
            $("#i_todate").change();
        }          
        //Refinamiento
        $("#i_category").val("-1");
        $("#i_category").change();
        $("#i_board").val("-1");
        $("#i_board").change();
        if (cookie["#i_facilities"]){
            $("#i_facilities").val("-1");
            $("#i_facilities").change();
        }
        $("#i_hotelname").val("");
        $("#i_hotelname").change();
        if (cookie["#i_eventtype"]){
            $("#i_eventtype").val(cookie["#i_eventtype"].replace(/%23/g, "#"));
            $("#i_eventtype").change();
        }
    }
    
	if ("hotel" == body) {

	    if ($('#i_children').val() != '0') {
		    $('#children_age').html('<span class="sidebar_label" style="font-weight:bold;">'+$.lang("Edades")+'</span>');
			var i, j = 0;
			var k = 1;
			for (j = 1; j <= $('#i_rooms').val(); j++) {
				for (i = 1; i <= $('#i_children').val(); i++) {
					if ((k % 2) == 0) {
						$('#children_age').append('<div class="i_childfield right">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
					} else {
						$('#children_age').append('<div class="i_childfield left">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
					}
					k++;
				}
			}
		    $('#children_age').append('<div class="clearer">&nbsp;</div>');
		    $('#children_age').show();             
	    } else {
		    $('#children_age').html('');
		    $('#children_age').hide();
		    $('#children_age').css('display','none');
	    }

			$('#children_age input.i_childage').bind("keydown", function(){
			    var val =  $(this).val();
			    return (val.length < 2);
			}); 
	    var a, b = 0;
	    var c = 1;
	    for (a = 1; a <= $('#i_rooms').val(); a++){
		    for (b = 1; b <= $('#i_children').val(); b++){
			$("#i_childage" + c.toString()).val(cookie["#child"+c]);
			$("#i_childage" + c.toString()).change();        
			c++;
		    }	    
	    }
	    
    	} else {
    
    	    if ($('#i_children').val() != '0') {
    		    $('#children_age').html('<span class="sidebar_label" style="font-weight:bold;">'+$.lang("Edades")+'</span>');
    			var i = 0;
    			var k = 1;
			for (i = 1; i <= $('#i_children').val(); i++) {
				if ((k % 2) == 0) {
					$('#children_age').append('<div class="i_childfield right">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
				} else {
					$('#children_age').append('<div class="i_childfield left">'+$.lang("Niño") + '&nbsp;' + k.toString() + ': <input id="i_childage' + k.toString() + '" maxlength="2" class="sidebar_field i_childage" name="agepax" type="text" value="0"/></div>');
				}
				k++;
			}
    		    $('#children_age').append('<div class="clearer">&nbsp;</div>');
    		    $('#children_age').show();             
    	    } else {
    		    $('#children_age').html('');
    		    $('#children_age').hide();
		    $('#children_age').css('display','none');
    	    }
    
    			$('#children_age input.i_childage').bind("keydown", function(){
    			    var val =  $(this).val();
    			    return (val.length < 2);
    			}); 
    	    var b = 0;
    	    var c = 1;
	    for (b = 1; b <= $('#i_children').val(); b++){
		$("#i_childage" + c.toString()).val(cookie["#child"+c]);
		$("#i_childage" + c.toString()).change();        
		c++;
	    }	    
    
    	}
    

}); //document.ready