/**
 * Featured Contents Library
 * Require: VUIT Library
 */

function createVuitContentPane(contentDOM) {
  var contentHref = contentDOM.getAttribute("href");
  var contentLoadingMsg = contentDOM.getAttribute("loadingMessage");
  if (contentHref) {
    // this needs to load the content dynamically via AJAX
    var newContentPane = new vijit.layout.ContentPane(
      {
        href: contentHref,
        loadingMessage: contentLoadingMsg
      },
      contentDOM
    );
    newContentPane.startup();
  }
}

vuit.addOnLoad(function() {
  var featuredTabs = vuit.query(".featuredTabs li", vuit.byId("<portlet:namespace/>_Features"));
  var featuredContents = vuit.query(".featuredContent", vuit.byId("<portlet:namespace/>_Features"));

  /**
   * if a tab is clicked, then we want to show the respective content
   * (if 'href' attribute is set then we want to pull the content via AJAX)
   */
  featuredTabs.connect("onclick", function() {
    featuredTabs.removeClass("selected");
    vuit.addClass(this, "selected");
    featuredContents.style("display", "none");
    var contentId = this.id.replace(/^(.+)_FeaturedTab_([0-9]+)$/i, "$1_FeaturedContent_$2");
    var contentDiv = vuit.byId(contentId);
    var contentVijit = vijit.byNode(contentDiv);
    vuit.style(contentDiv, "display", "block");
    if (!contentVijit) {
      createVuitContentPane(contentDiv);
    }
  });

  /**
   * For a tab which is shown on the initial load, we want to show the content now
   */
  featuredContents.forEach(function(item) {
    if (vuit.style(item, "display") == "block") {
      createVuitContentPane(item);
    }
  });
});

