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("Your settings are being saved...", '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("Saved!", 'done'));
    }).catch(() => {
      notification.replace(new XWiki.widgets.Notification("Failed to save your settings", 'error'));
    });
  });
});
