var XWiki = (function (XWiki) {
// Start XWiki augmentation.
Object.extend(XWiki, {
  userprofile : {
    init : function() {
      this.crtCategory = '';
      this.tabsContainer = $('user-vertical-menu');
      if (!this.tabsContainer) {
        return;
      }
      this.tabsContainer.select('.category-tab').each(function (tabElement) {
        tabElement.observe('click', function(event) {
          Event.stop(event);
          this.switchTab(tabElement.id);
        }.bindAsEventListener(this));
      }.bind(this));
      this.tabsContainer.select('.category-tab.current').each(function (activeTab) {
        this.updateCategoryFields(activeTab.id);
        document.fire('xwiki:profile:switchedCategory', {'category' : activeTab.id});
      }.bind(this));
      this.handleCancelAction();
    },

    switchTab : function(tab) {
      var tabName = tab.substring(14); // 14 = len('vertical-menu-')
      $("user-page-content").select("div.user-page-pane").each(function(pane){
        pane.addClassName('hidden');
      });
      $(tabName + 'Pane').removeClassName('hidden');
      $("user-vertical-menu").select("span.category-tab").each(function(tab){
        tab.removeClassName('current');
      });
      $(tab).addClassName('current');
      this.updateCategoryFields(tab);
      document.fire('xwiki:profile:switchedCategory', {'category' : tab});
    },

    updateCategoryFields : function (category) {
      category = category.substring(14); // 14 = len('vertical-menu-')
      this.crtCategory = category;
      this.updateField('xredirect', XWiki.currentDocument.getURL('view', 'category=' + category));
      this.updateField('xcontinue', XWiki.currentDocument.getURL('edit', 'editor=inline&category=' + category));
      this.updateField('category', category);
    },

    updateField : function (fieldName, value) {
      var element = $$('input[name=' + fieldName + ']');
      if (element && element.size() > 0) {
        element[0].value = value;
      }
    },

    handleCancelAction : function() {
      var elements = $$('form .buttons input[type=submit][name=action_cancel]');
      if (elements && elements.size() > 0) {
        var button = elements[0];
        Event.stopObserving(button, 'click');
        button.observe('click', function(event){
          event.stop();
          window.location = XWiki.currentDocument.getURL('view', 'category=' + this.crtCategory)
        }.bindAsEventListener(this));
      }
    }
  }
});

var init = function() {
  XWiki.userprofile.init();
  return true;
};
(XWiki.domIsLoaded && init()) || document.observe('xwiki:dom:loaded', init);
document.observe('lightbox:userprofile:loaded', init);
// End XWiki augmentation.
return XWiki;
}(XWiki || {}));
