require(['jquery', 'xwiki-meta'], function ($, xm) {
  // Make sure the change listener is not added twice.
  $(document).off('change.notificationAutoWatchMode');
  $(document).on('change.notificationAutoWatchMode', '.notificationAutoWatchMode', function() {
    var input = $(this);
    var target = input.data('target') === 'wiki' ? 'wiki' : 'user';
    var notification = new XWiki.widgets.Notification("Ihre Einstellungen werden gespeichert…", 'inprogress');
    var url = new XWiki.Document('NotificationPreferenceService', 'XWiki.Notifications.Code').getURL('get',
      'outputSyntax=plain');
    $.post(url, {
      action: 'setAutoWatchMode',
      mode: input.val(),
      target: target,
      user: input.data('user'),
      csrf: xm.form_token
    }).then(() => {
      notification.replace(new XWiki.widgets.Notification("Einstellungen gespeichert!", 'done'));
    }).catch(() => {
      notification.replace(new XWiki.widgets.Notification("Fehler beim Speichern der Einstellungen", 'error'));
    });
  });
});
