require(['jquery', 'xwiki-meta'], function($, xm) {
  // The livetable is refreshed after each action (add/remove).
  // Refresh the document version to avoid conflicts if we try to save afterwards
  $(document).on('xwiki:livetable:displayComplete', function (event) {
    xm.refreshVersion();
  });
  $(document).on('click', '#addMembers', function(event) {
    event.preventDefault();
    var addMembersButton = $(event.target);
    var form = addMembersButton.closest('form');
    var parameters = form.serializeArray();
    // Add the data from the submit button.
    if (addMembersButton.attr('name')) {
      parameters.push({
        name: addMembersButton.attr('name'),
        value: addMembersButton.val()
      });
    }
    var names = parameters.map(function(parameter) {
      return parameter.name === 'name' ? parameter.value.trim() : '';
    }).join('');
    if (addMembersButton.prop('disabled') || names === '') {
      // Nothing to add.
      return;
    }
    addMembersButton.prop('disabled', true);
    Promise.resolve($.post(form.attr('action'), parameters)).then(function(response) {
      // Clear the list of selected users and groups.
      $('#userInput')[0].selectize.clear(true);
      $('#groupInput')[0].selectize.clear(true);
      // Reload the live table.
      editgrouptable.refresh();
      // Show notification message.
      if(response.hasIgnored) {
        new XWiki.widgets.Notification(response.ignoredMessage, 'warning', {timeout: 5});
      } else {
        new XWiki.widgets.Notification("Benutzer erfolgreich hinzugefügt", 'done', {timeout: 5});
      }
    }).catch(function(response) {
      new XWiki.widgets.Notification("Fehlschlag beim Hinzufügen eines Benutzers:" +
        response.statusText, 'error', {timeout: 5});
    }).finally(function() {
      addMembersButton.prop('disabled', false);
    });
  });
});
