(function() {
var init = function() {
  // We only need this behavior in the admin (administration) and view modes.
  if (XWiki.contextaction != 'admin' && XWiki.contextaction != 'view') {
    return;
  }

  // Listen for the save & continue event (that we reuse with our button).
  document.observe("xwiki:actions:save", function(event) {
    // Rename the save button so that XWiki's action filter does not get in our way and send our request somewhere else
    // rather than the form's action.
    if ($$("input[name='action_saveandcontinue']")[0]) {
      $$("input[name='action_saveandcontinue']")[0].name = 'xaction_saveandcontinue';
    }

    // Ask for confirmation when the new owner does not exist and is entered by hand.
    if ($$("input[name='owner']")[0] && !$$("input[name='owner'][type='hidden']")[0]) {
      // We do it like this because we want to wait for the reply while blocking (window.confirm) the save event
      // handler so that we can eventually stop the event itself instead of having to re-submit the form in an asynch
      // callback (Confirm Widget).
      var confirmed = window.confirm("The new owner's user does not exist or it may come from a different wiki.\nAre you sure you want to use it and continue with the save operation?");
      if (!confirmed) {
        event.stop();
        if (event.memo) {
          event.memo.originalEvent.stop();
        }
      }
    }
  });
};

// Register on xwiki:dom:loading because we want to register a handler for xwiki:actions:save before the default
// handler gets registered, otherwise our handler will be called after the default, thus after the AJAX request
// is sent, and we don`t want that.
(XWiki && XWiki.domIsLoaded && init()) || document.observe('xwiki:dom:loading', init);

})();
