// Shows a description text on the screen.
var descriptionBox = (function()
{
    // Constants

    var FADE_STEPS = 2;
    var TIMER_INTERVAL = 30;


    // Private Attributes

    var that = {};
    var divRef;
    var textMessage;
    var timerTick;
    var timerId;
    var fadingIn;
    var isShown = false;


    // Private Methods

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


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


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

        if (fadingIn === false)
        {
            step = 1 - step;
        }

        setOpacity(divRef, step);

        // Update timer tick
        if (timerTick === FADE_STEPS)
        {
            if (fadingIn === false && textMessage !== undefined)
            {
                // Set text and fade in again.
                divRef.innerHTML = textMessage;

                fadingIn = true;
                timerTick = 0;
            }
            else
            {
                isShown = fadingIn ? true : false;

                stopTimer();
            }

            textMessage = undefined;
        }

        timerTick++;
    }


    // Public Methods

    /**
     * Shows a string in on the screen
     * text: is the string to display.
     */
    that.show = function(text)
    {
        // Initialization
        if (divRef === undefined)
        {
            throw "descriptionBox.show - init must be called before show!";
        }

        // Handle ongoing fade in or out
        if (timerId !== undefined)
        {
            textMessage = text;
            fadingIn = false;
        }
        else
        {
            //  Handle text already present
            if (isShown)
            {
                fadingIn = false;
                textMessage = text;
            }
            else
            {
                fadingIn = true;
                divRef.innerHTML = text;
            }

            startTimer();
        }
    };


    /**
     * Fades out the description.
     */
    that.hide = function()
    {
        if (isShown && timerId === undefined)
        {
            startTimer();
        }

        fadingIn = false;
        textMessage = undefined;
    };
    
    
    /**
     * Initializes the descriptionBox.
     */
    that.init = function(element)
    {
        divRef = element;
        setOpacity(divRef, 0);
    };


    return that;
}());

