
/**
 * Class to manage tabbed panels.
 */
var TabManager = Class.create({

    /**
     * Called when a new TabManager instance is created.
     *
     * @param  containerElement
     *         either an element or an ID of an element that will be used
     *         to contain the unordered list (UL) for the tabs
     */
    initialize: function(containerElement) {
        this.containerElement = $(containerElement);
        this.tabs = $H();
        this.listElement = new Element("ul");
        this.listElement.addClassName("common-tabs");
        this.containerElement.appendChild(this.listElement);
    },

    
    /**
     * Adds a new tab to the manager, with an associated content DIV
     * that will be shown or hidden.
     *
     * The options must include "id", "title" and "content" fields.
     * The id field will be used as the ID of the list item used for the
     * tab.  The title field will appear as the text of the tab.  The content
     * field is either the element or the ID of an element that will be
     * displayed when the tab is selected.
     *
     * Content elements should have a "display:none" style set directly
     * on them (i.e. not through a CSS rule) before they are added to
     * the tab manager.
     *
     * @param  options
     *         the set of options for creating the tab
     */
    addTab: function(options) {
        options = $H(options);
        var tabItem = new Element("li");
        tabItem.id = options.get("id");
        tabItem.update(options.get("title"));
        tabItem.observe("click", this.onTabClick.bindAsEventListener(this));
        if (this.tabs.size() == 0) tabItem.addClassName("common-tabs-firstTab");
        this.listElement.insert(tabItem);
        var tab = $H();
        tab.set("element", tabItem);
        tab.set("content", $(options.get("content")));
        this.tabs.set(tabItem.id, tab);
    },


    /**
     * Selects the tab with the given ID and displays its content.
     *
     * @param  tabID
     *         the ID of the tab to select
     */
    selectTab: function(tabID) {
        // Reset the display of all tabs and hide all content.
        this.tabs.each(function(kv) {
            var tab = kv[1];
            tab.get("element").removeClassName("common-tabs-selectedTab");
            tab.get("content").hide();
        });
        // Show the selected tab.
        var selectedTab = this.tabs.get(tabID);
        selectedTab.get("element").addClassName("common-tabs-selectedTab");
        selectedTab.get("content").show();
    },
    
    
    /**
     * Called when a tab is clicked.
     *
     * @param  e
     *         the click event
     */
    onTabClick: function(e) {
        this.selectTab(e.element().id);
    }

});
