var XWiki = (function (XWiki) {
// Start XWiki augmentation.
/**
 * Extends the UserPicker in order to display the selected user/group inline after the target text input.
 */
var CustomUserPicker = Class.create(XWiki.widgets.UserPicker, {
  // @Override
  _createSelectionManager: function($super, options) {
    var selectionManager = $super(Object.extend(options, {
      listInsertionPosition : 'after',
      acceptFreeText : false
    }));
    // Overwrite the way the selected item is displayed.
    selectionManager.displayItem = function(suggestion) {
      var targetInfo = new Element('span').update(suggestion.info).insert(this.createDeleteTool());
      var targetClass = this.suggest.sources[0].script.indexOf('uorg=group') > 0 ? 'target-group' : 'target-user';
      return new Element('li', {'class': targetClass}).insert(targetInfo).insert(this.createItemInput(suggestion));
    }.bind(selectionManager);
    return selectionManager;
  }
});

XWiki.MessageStream = Class.create({
  targetsWithName : ['user', 'group'],
  suggestParameters : {
    user : {
      script: 'https://developer.stage.payex.com/xwiki/wiki/developer/get/Main/MessageSenderMacro?xpage=uorgsuggest&uorg=user&wiki=global&',
      noresults: "User not found"
    },
    group : {
      script: "https://developer.stage.payex.com/xwiki/wiki/developer/get/Main/MessageSenderMacro?xpage=uorgsuggest&uorg=group&",
      noresults: "Group not found"
    }
  },
  initialize : function() {
    this.prepareForms();
    this.enhanceSelect();
  },
  prepareTargetInput : function(event, element) {
    var targetType = element.options[element.selectedIndex].value;
    element.className = targetType;
    if (!element.__targetNameInput) {return;}
    if (this.targetsWithName.indexOf(targetType) < 0) {
      element.__targetNameInput.addClassName('hidden');
      if (element.__targetNameInput.__x_suggest) {
        element.__targetNameInput.__x_suggest.detach();
      }
    } else {
      // Focus the text input so that the place-holder value is cleared if present. Otherwise the user picker will treat
      // the place-holder value as if it was typed by the user and will automatically select the corresponding suggestion.
      element.__targetNameInput.removeClassName('hidden').activate();
      // Defer the creation of the user picker to allow the focus listeners to be called first (in order to clear the
      // place-holder value).
      this.suggestParameters[targetType] && function() {
        new CustomUserPicker(element.__targetNameInput, this.suggestParameters[targetType]);
      }.bind(this).defer();
    }
  },
  enhanceSelect: function () {
    $$('.messagestream select[name="visibilityLevel"]').each(function(element) {
      element.addClassName(element.options[element.selectedIndex].value);
      element.__targetNameInput = element.up('.messagestream').down('input[name="targetName"]');
      if (element.__targetNameInput && this.targetsWithName.indexOf(element.options[element.selectedIndex].value) < 0) {
        element.__targetNameInput.addClassName('hidden');
      }
      element.observe('change', this.prepareTargetInput.bindAsEventListener(this, element));
      this.prepareTargetInput(null, element);
    }.bind(this));
  },
  prepareForms: function() {
    $$('.messagestream form').each(function(msForm) {
      msForm.action = msForm.action.replace(/xredirect=.*$/, 'xpage=plain')
      msForm.observe('submit', function(event) {
        event.stop();
        if (msForm._disabled == true || msForm.down('textarea').value.strip() == '') {
          return;
        }
        new Ajax.Request(
          msForm.action, {
            parameters: msForm.serialize(true),
            onCreate: function() {
              msForm._disabled = true;
              msForm._notification = new XWiki.widgets.Notification("Sending...", 'inprogress');
            },
            onSuccess: function() {
              if (msForm) {
                msForm.messagestream_message.value = '';
              }
              if (msForm && msForm._notification) {
                msForm._notification.hide();
              }
              msForm._notification = new XWiki.widgets.Notification("Message sent", 'done');

              document.fire('xwiki:activity:newActivity', msForm);
            },
            onFailure: function(response) {
              var failureReason = '';
              if (response.statusText == '' /* No response */ || response.status == 12031 /* In IE */) {
                failureReason = 'Server not responding';
              } else {
                failureReason = response.statusText;
              }
              if (msForm) {
                msForm._disabled = false
                if (msForm._notification) {
                  msForm._notification.hide();
                }
                msForm._notification = new XWiki.widgets.Notification("Failed to send message: " + failureReason, 'error');
              }
            },
            on1223 : function(response) { /*SUCCESS*/
              response.request.options.onSuccess(response);
            },
            on0 : function(response) {  /*FAILURE*/
              response.request.options.onFailure(response);
            },
            onComplete: function() {
              msForm._disabled = false;
            }.bind(this)
          }
        );
      }.bindAsEventListener(this));
    }.bind(this));
  }
});

var init = function() {
  return new XWiki.MessageStream();
};
(XWiki.domIsLoaded && init()) || document.observe('xwiki:dom:loaded', init);

// End XWiki augmentation.
return XWiki;
}(XWiki || {}));
