var XWiki = (function (XWiki) {
// Start XWiki augmentation.
XWiki.MessageStream = Class.create({
  initialize : function() {
    this.prepareForms();
    this.enhanceSelect();
  },
  prepareTargetInput : function(event, element) {
    var targetType = element.options[element.selectedIndex].value;
    element.className = targetType;
    var messageStream = element.up('.messagestream');
    var targetInputContainer = messageStream.down('.message-target-' + targetType);
    if (!targetInputContainer) {
      targetInputContainer = messageStream.down('.message-target-default');
    }
    messageStream.select('.message-target').forEach(function(messageTargetContainer) {
      var fields = messageTargetContainer.select('input, select, textarea');
      if (messageTargetContainer === targetInputContainer) {
        messageTargetContainer.removeClassName('hidden');
        fields.forEach(function(field) {
          field.enable();
          field.hasClassName('selectized') && field.selectize.enable();
        });
      } else {
        messageTargetContainer.addClassName('hidden');
        fields.forEach(function(field) {
          field.disable();
          field.hasClassName('selectized') && field.selectize.disable();
        });
      }
    });
  },
  enhanceSelect: function () {
    $$('.messagestream select[name="visibilityLevel"]').each(function(element) {
      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 || {}));
