var reservation = {
  autoAttach: function() {
    if(window.location.href.indexOf("reservation/search")>0){
      $("#edit-submit").hide();     
      $("#edit-to").hide(); 
    }
    $("#edit-from").change(function() {
      var nid = this.value;
      if(nid==0){
        $("#edit-to").hide();
        $("#edit-submit").hide();
        return false;
      }
      $.get(Drupal.settings.reservation.basePath +'reservation/search/destiny/'+nid, function(data) {
        var options = Drupal.parseJson(data);
        if (options.length > 0) {
          //Clear the current destination items.
          //show the drop down
          $("#edit-to").show();
          $("#edit-to").empty();
          //This is to have the 1st one selected by defauld.
          var op="";
          for (var i = 0; i < options.length; i++) {
            if($.browser.msie){
              $("#edit-to").append('<option value="' + options[i].nid + '">' + options[i].title + '</option>');
            }else{
              op+='<option value="' + options[i].nid + '">' + options[i].title + '</option>';
            }        
          }
          //populate the drop down
          if(!$.browser.msie){
            $("#edit-to").html(op);
          }
          //show the submit button
          $("#edit-submit").show();
          
        }
      });
      return false;
    });
    
    
    if($("#edit-field-round-trip-keys").length){
      if ($("#edit-field-round-trip-keys").attr("checked")) {
        $("fieldset[@class*=group-round-trip]").show();
      }else{
        $("fieldset[@class*=group-round-trip]").hide();
      }
    }
    //check if the field exist
    if($("#edit-field-return-pickup-location-0-value").length){
      if($("#edit-field-return-pickup-location-0-value").val().length>0){
        //if the field is not empty show the group and check the round trip checkbox
        $("fieldset[@class*=group-round-trip]").show();
        $("#edit-field-round-trip-keys").attr("checked", "checked");
      }
    }

    $("#edit-field-round-trip-keys").click(function() {
      $("fieldset[@class*=group-round-trip]").toggle( );
    });
  }
};

// Global Killswitch.
if (Drupal.jsEnabled) {
  $(document).ready(reservation.autoAttach);
}
