var XWiki = (function (XWiki) {
// Start XWiki augmentation.
XWiki.MessageStream = Class.create({
  initialize : function(container) {
    container = container || $(document.body);
    this.prepareForms(container);
    this.enhanceSelect(container);
  },
  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 (container) {
    container.select('.messagestream select[name="visibilityLevel"]').each(function(element) {
      element.observe('change', this.prepareTargetInput.bindAsEventListener(this, element));
      this.prepareTargetInput(null, element);
    }.bind(this));
  },
  prepareForms: function(container) {
    container.select('.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("Enviando...", 'inprogress');
            },
            onSuccess: function() {
              if (msForm) {
                msForm.messagestream_message.value = '';
              }
              if (msForm && msForm._notification) {
                msForm._notification.hide();
              }
              msForm._notification = new XWiki.widgets.Notification("Mensagem enviada", 'done');

              document.fire('xwiki:activity:newActivity', msForm);
            },
            onFailure: function(response) {
              var failureReason = response.statusText || 'Server not responding';
              if (msForm) {
                msForm._disabled = false
                if (msForm._notification) {
                  msForm._notification.hide();
                }
                msForm._notification = new XWiki.widgets.Notification("Falha ao enviar mensagem: " + failureReason, 'error');
              }
            },
            on0 : function(response) {  /*FAILURE*/
              response.request.options.onFailure(response);
            },
            onComplete: function() {
              msForm._disabled = false;
            }.bind(this)
          }
        );
      }.bindAsEventListener(this));
    }.bind(this));
  }
});

var init = function (event) {
  var elements = (event && event.memo.elements) || [$(document.body)];
  elements.forEach(function(container) {
    new XWiki.MessageStream(container);
  });
  return true;
};

// Initialize the message sender macro when the page is loaded.
(XWiki.domIsLoaded && init())
|| document.observe('xwiki:dom:loaded', init);

// Initialize the message sender macro when it is added after the page is loaded.
document.observe('xwiki:dom:updated', init);

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