﻿function TriviaRotator(objName) 
{
    var obj = null;
    var idx = 1;
    var htmlTemplate = "<b><i>[0]: </b></i><br />[1]</br>";
    
    var quoteList =  new Array();

    this.Init = function()
    {
        _addLoadEvent(this.FinishInit);
    }

    this.AddQuote = function(quote)
    {
        var x = quoteList.length;
        if (_isArray(quoteList))
        {
            quoteList[x] = quote;
        }
    }

    this.FinishInit = function()
    {
        obj = document.getElementById(objName);
        if (!obj)
        {
            alert("Trivia Rotator Error: Cannot locate the \"" + objName + "\" element.");
        }
        else
        {
            var quote = _getPreviousQuote().split("|");
            var html = _getFormattedQuote(quote);
            obj.innerHTML = html;
        }
    }

    this.GetNext = function()
    {
        if (obj)
        {
            var quote = _getNextQuote().split("|");
            var html = _getFormattedQuote(quote);
            obj.innerHTML = html;
        }
    }

    this.GetPrevious = function()
    {
        if (obj)
        {
            var quote = _getPreviousQuote().split("|");
            var html = _getFormattedQuote(quote);
            obj.innerHTML = html;
        }
    }

    function _addLoadEvent(func)
    {
        var oldonload = window.onload;
        if (typeof window.onload != 'function')
        {
            window.onload = func;
        } 
        else
        {
            window.onload = function()
            {
                if (oldonload)
                {
                    oldonload();
                }
                func();
            }
        }
    }

    
    function _getFormattedQuote(quote)
    {
        if (_isArray(quote))
        {
            return htmlTemplate.replace("[0]", quote[0]).replace("[1]", quote[1]);
        }
    }

    function _getNextQuote()
    {
        idx++;

        if (quoteList.length && idx >= quoteList.length)
        {
            idx = 0;
        }
        return quoteList[idx];
    }

    function _getPreviousQuote() 
    {
        idx--;
        if (quoteList.length && idx < 0)
        {
            idx = quoteList.length - 1;
        }
        return quoteList[idx];
    }

    function _isArray(arr)
    {
        if (arr.constructor.toString().indexOf("Array") == -1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    function _rndnumber() 
    {
        var randscript = -1;
        while (randscript < 0 || randscript > howMany || isNaN(randscript)) 
        {
            randscript = parseInt(Math.random() * (howMany + 1));
        }
        return randscript;
    }
    
    return true;
}
