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: target === 'user' ? 'setAutoWatchMode' : 'setDefaultAutoWatchMode',
      mode: input.val(),
      csrf: xm.form_token
    }).done(function() {
      notification.replace(new XWiki.widgets.Notification("Saved!", 'done'));
    }).error(function() {
      notification.replace(new XWiki.widgets.Notification("Failed to save your settings", 'error'));
    });
  });
});
