var XWiki = (function (XWiki) {
// Start XWiki augmentation.
XWiki.Activity = Class.create({
  initialize : function() {
    this.initHandlers();
    this.attachDeleteHandlers();
  },
  initHandlers: function() {
    $$('.activityHeader').each(function(activityHeader){
      if(activityHeader.up().hasClassName('collapsed')){
        activityHeader.observe('click', this.toggle.bind(this, activityHeader.up()));
      }
    }.bind(this));

    document.observe('xwiki:activity:newActivity', function(event) {
      // Update all activity streams to display the new message
      $$('.activity').each(this.updateActivity.bind(this));
    }.bind(this));
  },
  toggle: function() {
    var collapsable = arguments[0];
    if (collapsable.hasClassName('collapsed')) {
      collapsable.removeClassName('collapsed');
      collapsable.down('.toolExpand').update('&#9650;');
    } else {
      collapsable.addClassName('collapsed');
      collapsable.down('.toolExpand').update('&#9660;');
    }
  },
  updateActivity: function(activityContainer) {
    var updateURL = activityContainer.down('.updateURL').value;
    new Ajax.Updater(
      {success: activityContainer},
      updateURL, {
        onCreate: function() {
          // NOTE: Do we need any progress/success notification at this level or do we do it only in the "calling" component?
          //activityContainer._notification = new XWiki.widgets.Notification("Enviando solicitação...", 'inprogress');
        },
        onSuccess: function() {
          if (activityContainer && activityContainer._notification) {
            activityContainer._notification.hide();
          }
        },
        onFailure: function(response) {
          var failureReason = '';
          if (response.statusText == '' /* No response */ || response.status == 12031 /* In IE */) {
            failureReason = 'Server not responding';
          } else {
            failureReason = response.statusText;
          }
          if (activityContainer) {
            if (activityContainer._notification) {
              activityContainer._notification.hide();
            }
            activityContainer._notification = new XWiki.widgets.Notification("Falha: " + failureReason, 'error');
          }
        },
        on1223 : function(response) { /*SUCCESS*/
          response.request.options.onSuccess(response);
        },
        on0 : function(response) {  /*FAILURE*/
          response.request.options.onFailure(response);
        },
        onComplete: function(response) {
          // The newly retrieved activity element is inserted after onSuccess is called, so we must handle it here instead of in onSuccess.
          if (response.request.success()) {
            // The remplacement activity has a default updateURL. We discard that and replace it with the updateURL of the original activity so that, at each update, the URL stays the same.
            var newActivity = activityContainer.next();
            if (newActivity) {
              newActivity.down('.updateURL').value = updateURL;
            }

            // Remove the old activity element.
            activityContainer.remove();

            this.attachDeleteHandlers();
          }
        }.bind(this),
        insertion: 'after'
      }
    );
  },
  attachDeleteHandlers : function () {
    $$('.activity .activityItem .toolDelete').invoke('observe', 'click', function (event) {
      event.stop();
      var trigger = event.element();
      trigger.blur();
      if (trigger.disabled) {
        // Do nothing if the button was already clicked and it's waiting for a response from the server.
        return;
      } else {
        new XWiki.widgets.ConfirmedAjaxRequest(
          /* Ajax request URL */
          trigger.href.replace(/xredirect=.*$/, 'xpage=plain&confirm=1'),
          /* Ajax request parameters */
          {
            onCreate : function() {
              // Disable the button, to avoid a cascade of clicks from impatient users
              trigger.disabled = true;
            },
            onSuccess : function() {
              // Remove the corresponding HTML element from the UI
              trigger.up("li").remove();
            },
            onComplete : function() {
              // In the end: re-enable the button
              trigger.disabled = false;
            }
          },
          /* Interaction parameters */
          {
            confirmationText: "Você tem certeza que deseja remover essa mensagem?"
          }
        );
      }
    });
  }
});
// End XWiki augmentation.
return XWiki;
}(XWiki || {}));

document.observe('xwiki:dom:loaded', function() {
  new XWiki.Activity();
});
