// Manger for changing pages.
var pageManager = (function()
{
    // Constants

    var FADE_STEPS = 5;
    var TIMER_INTERVAL = 20; // Optimistic frame rate of 50 fps for smooth performance.


    // Private Attributes

    var that = {};
    var currentPage = "blank";
    var currentPageRef;
    var nextPage;
    var nextPageRef;
    var timerId;
    var timerTick;
    var buttonsRef;


    // Private Methods

    function startTimer()
    {
        timerTick = 0;
        timerId = setInterval(onTimer, TIMER_INTERVAL);
    }


    function stopTimer()
    {
        clearInterval(timerId);
        timerId = undefined;
    }


    function onTimer()
    {
        var step = timerTick / FADE_STEPS;

        setOpacity(nextPageRef, step);

        if (currentPageRef)
        {
            setOpacity(currentPageRef, 1 - step);
        }

        if (buttonsRef !== undefined)
        {
            setOpacity(buttonsRef, step);
        }

        // Update timer tick
        if (timerTick === FADE_STEPS)
        {
            if (currentPageRef)
            {
                currentPageRef.style.display = "none";
            }

            currentPage = nextPage;
            buttonsRef = undefined;

            stopTimer();
        }

        timerTick++;
    }


    // Public Methods

    /**
     * Changes the current page to the specified.
     * newPage: is the page name of the page to change to.
     */
    that.changePage = function(newPage)
    {
        if (newPage !== currentPage && timerId === undefined)
        {
            nextPage = newPage;
            nextPageRef = document.getElementById(newPage);

            if (!nextPageRef)
            {
                throw "pageManager.changePage - the given newPage does not exist in the DOM!";
            }

            currentPageRef = document.getElementById(currentPage);

            // Display new page but with opacity 0.
            setOpacity(nextPageRef, 0);
            nextPageRef.style.display = "block";

            // If the buttons are not shown, fade in with the rest of the page.
            buttonsRef = document.getElementById("button_panel");

            if (buttonsRef.style.display !== "block")
            {
                setOpacity(buttonsRef, 0);
                buttonsRef.style.display = "block";
            }
            else
            {
                // Already shown, don't animate.
                buttonsRef = undefined;
            }

            startTimer();
        }
    };


    return that;
}());

