
(function ($) {
Drupal.backup_migrate = {
  callbackURL : "",  
  autoAttach  : function() {
    if (Drupal.settings.backup_migrate !== undefined) {
      if ($("#edit-save-settings").length && !$("#edit-save-settings").attr("checked")) {
        // Disable input and hide its description.
        // Set display none instead of using hide(), because hide() doesn't work when parent is hidden.
        $('div.backup-migrate-save-options').css('display', 'none');
      }
  
      $("#edit-save-settings").bind("click", function() {
        if (!$("#edit-save-settings").attr("checked")) {
          $("div.backup-migrate-save-options").slideUp('slow');
        }
        else {
          // Save unchecked; enable input.
          $("div.backup-migrate-save-options").slideDown('slow');
        }
      });

      $('#backup-migrate-ui-manual-backup-form select[multiple], #backup-migrate-crud-edit-form select[multiple]').each(function() {
          $(this).after(
            $('<div class="description backup-migrate-checkbox-link"></div>').append(
              $('<a href="javascript:null(0);"></a>').text(Drupal.settings.backup_migrate.checkboxLinkText).click(function() {
                Drupal.backup_migrate.selectToCheckboxes($(this).parents('.form-item').find('select'));
              })
            )
          );
        }
      );
    }
  },

  selectToCheckboxes : function($select) {
    var field_id = $select.attr('id');
    var $checkboxes = $('<div></div>').addClass('backup-migrate-tables-checkboxes');
    $('option', $select).each(function(i) {
      var self = this;
      $box = $('<input type="checkbox" class="backup-migrate-tables-checkbox">').bind('change click', function() {
        $select.find('option[value="'+self.value+'"]').attr('selected', this.checked);
        if (this.checked) {
          $(this).parent().addClass('checked');
        }
        else {
          $(this).parent().removeClass('checked');
        }
      }).attr('checked', this.selected ? 'checked' : '');
      $checkboxes.append($('<div class="form-item"></div>').append($('<label class="option backup-migrate-table-select">'+this.value+'</label>').prepend($box)));
    });
    $select.parent().find('.backup-migrate-checkbox-link').remove();
    $select.before($checkboxes);
    $select.hide();
  }
}

$(document).ready(Drupal.backup_migrate.autoAttach);
})(jQuery);
