// Create and manipulate a list of buttons.
var buttonManager = (function()
{
    var that = {};
    var buttonList = [];


    var changeSelected = function(button)
    {
        for (var key in buttonList)
        {
            var b = buttonList[key];
            b.setSelected(b === button);
        }
    }


    /**
     * Creates a new button and returns it.
     * By convention the hover, down images are postfixed with "_over" and "_down".
     * imageSrc: a string that is the path to the image to display on the button.
     * alt: a string with the popup hint to show for the button.
     * action: is the page to go to when clicked.
     */
    that.createButton = function(imageSrc, alt, action)
    {
        var button = document.createElement("img");
        var highlighted = false;

        button.src = imageSrc;
        button.alt = alt;
        button.className = "button";
        button.width = "80";
        button.height = "82";


        button.onmousedown = function()
        {
            button.src = imageSrc.replace(".png", "_down.png");
        };


        button.onmouseup = function()
        {
            button.src = imageSrc.replace(".png", "_over.png");
        };


        button.onmouseover = function()
        {
            descriptionBox.show(alt);

            if (!highlighted)
            {
                button.src = imageSrc.replace(".png", "_over.png");
            }
        };


        button.onmouseout = function()
        {
            descriptionBox.hide();

            if (!highlighted)
            {
                button.src = imageSrc;
            }
        };


        button.onclick = function()
        {
            changeSelected(button);
            pageManager.changePage(action);
        };


        button.setSelected = function(selected)
        {
            if (typeof(selected) !== "boolean")
            {
                throw "buttonManager.getButton: argument needs to be a boolean.";
            }

            highlighted = selected;

            if (selected)
            {
                button.src = imageSrc.replace(".png", "_down.png");
            }
            else
            {
                button.src = imageSrc;
            }
        };

        buttonList.push(button);
        return button;
    };


    /**
     * Returns a button given an index.
     * index: a positive number representing the index of a button.
     */
    that.getButton = function(index)
    {
        if (index < 0 || index > buttonList.length)
        {
            throw "buttonManager.getButton: index out of range.";
        }

        return buttonList[index];
    }


    return that;
})();
