function AOLQuizAjax()
{
    var REST_URL = "/user-quizzes/REST/";
    var XMLHttpFactories = [
            function ()
            {
                return new XMLHttpRequest()
            },
            function ()
            {
                return new ActiveXObject("Msxml2.XMLHTTP")
            },
            function ()
            {
                return new ActiveXObject("Msxml3.XMLHTTP")
            },
            function ()
            {
                return new ActiveXObject("Microsoft.XMLHTTP")
            }
            ];
    function createXMLHTTPObject()
    {
        var xmlhttp = false;
        for( var i = 0; i < XMLHttpFactories.length; i++ )
        {
            try
            {
                xmlhttp = XMLHttpFactories[i]();
            }
            catch ( e )
            {
                continue;
            }
            break;
        }
        return xmlhttp;
    }

    function xhr( url, method, callback, params )
    {
        var req = createXMLHTTPObject();
        req.open(method, url, /*async*/true);
        if( method == "POST" )
        {
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        }
        req.onreadystatechange = function ()
        {
            if( req.readyState == 4 /*complete*/ )
            {
                var data = eval('(' + req.responseText + ')');
                callback(data);
            }
        };

        req.send(params);
    }

    function get( request, callback )
    {
        xhr(REST_URL + request, "GET", callback, null)
    }

    function post( request, callback, params )
    {
        xhr(REST_URL + request, "POST", callback, params)
    }

    this.loadQuiz = function( id, callback )
    {
        get("getQuiz?id=" + id, function( data )
        {
            callback(wrapQuiz(data))
        });
    }

    this.loadInfiniteQuiz = function( callback, genreId )
    {
        get("getInfiniteQuiz" + (genreId != null ? "?genre-id=" + genreId : ""), function( data )
        {
            callback(wrapQuiz(data))
        });
    }

    this.saveUserScore = function( quizObj, callback )
    {
        var params = "quiz-id=" + quizObj.id + "&score=" + quizObj.getComputedScore() + "&genre=" + quizObj.genreIds[0] + "&correct-count=" + quizObj.getTotalCorrectAnswers()
        post("saveScore", callback, params)
    }

    this.getGenres = function( callback )
    {
        get("getGenres", callback)
    }

    this.getUser = function( callback )
    {
        get("getUser", callback)
    }

    this.getUserScoreResults = function( callback )
    {
        get("getUserScoreResults", callback)
    }

    this.getLeaderboard = function( quizId, callback, timeframe )
    {
        get("getLeaderboard?quiz-id=" + quizId + "&timeframe=" + timeframe, callback);
    }

    this.getOverallLeaderboard = function( callback, timeframe )
    {
        get("getLeaderboard?timeframe=" + timeframe, callback)
    }

    this.getComments = function( quizId, start, limit, callback )
    {
        get("getComments?quiz-id=" + quizId + "&start=" + start + "&limit=" + limit, callback)
    }

    this.getRatingForUser = function( quizId, callback )
    {
        get("getRatingForUser?quiz-id=" + quizId, callback)
    }

    this.addComment = function( quizId, title, text, callback )
    {
        post("addComment", callback, "quiz-id=" + quizId + "&title=" + title + "&text=" + text)
    }

    this.addRating = function( quizId, score, callback )
    {
        post("addRating", callback, "quiz-id=" + quizId + "&score=" + score)
    }


    function wrapQuiz( quiz )
    {
        quiz.currentIndex = 0;
        quiz.correctMessageIndex = 0;
        quiz.wrongMessageIndex = 0;

        for( var i = 0; i < quiz.questions.length; i++ )
        {
            quiz.questions[i].userAnswer = -1;
            quiz.questions[i].elapsedTime = -1;
        }
        quiz.getDescription = function()
        {
            return this.description;
        }
        quiz.getTotalQuestions = function()
        {
            return this.questions.length;
        }
        quiz.nextQuestion = function()
        {
            if( !this.isLastQuestion() )
            {
                this.currentIndex++;
            }
        }
        quiz.prevQuestion = function()
        {
            if( this.currentIndex > 0 )
            {
                this.currentIndex--;
            }
        }

        quiz.getQuestion = function( i )
        {
            return this.questions[i];
        }
        quiz.isLastQuestion = function()
        {
            return this.currentIndex + 1 == this.getTotalQuestions();
        }
        quiz.getCurrentQuestion = function()
        {
            return this.questions[this.currentIndex];
        }
        quiz.getPreviousQuestion = function()
        {
            if( this.currentIndex > 0 )
            {
                return this.questions[this.currentIndex - 1 ];
            }
            else
            {
                return this.questions[this.currentIndex ];
            }
        }
        quiz.getCurrentIndex = function()
        {
            return this.currentIndex;
        }
        quiz.setUserAnswer = function( answer, elapsedTime )
        {
            this.questions[this.currentIndex].userAnswer = answer;
            this.questions[this.currentIndex].elapsedTime = elapsedTime;
        }
        quiz.getComputedScore = function()
        {
            var points = this.getCorrectPoints() - this.getWrongPoints() + this.getBonusPoints();
            if( points >= 0 )
            {
                return points
            }
            else
            {
                return 0
            }
        }

        quiz.getCurrentQuestionPoints = function()
        {
            var question = this.questions[this.currentIndex];
            if( question.userAnswer == question.correctAnswer.id )
            {
                if( question.type == "MULTIPLE" )
                {
                    return "60<span>correct</span>";
                }
                else if( question.type == "BOOLEAN" )
                {
                    return "30<span>correct</span>";
                }
            }
            else
            {
                if( question.type == "MULTIPLE" )
                {
                    return "-10<span>incorrect</span>";
                }
                else if( question.type == "BOOLEAN" )
                {
                    return "-20<span>incorrect</span>";
                }
            }
        }

        quiz.getCurrentBonusPoints = function()
        {
            var question = this.questions[this.currentIndex];
            if( question.userAnswer == question.correctAnswer.id )
            {
                return Math.max((question.elapsedTime), 0) + "<span>speed bonus</span>";
            }
            else
            {
                return "0<span>speed bonus</span>";
            }

        }


        quiz.getWrongPoints = function()
        {
            var score = 0;
            for( var i = 0; i < quiz.questions.length && quiz.questions[i].userAnswer != -1; i++ )
            {
                var question = quiz.questions[i];
                if( question.userAnswer != question.correctAnswer.id )
                {
                    if( question.type == "MULTIPLE" )
                    {
                        score += 10;
                    }
                    else if( question.type == "BOOLEAN" )
                    {
                        score += 20;
                    }
                }
            }
            return score;
        }
        quiz.getCorrectPoints = function()
        {
            var score = 0;
            for( var i = 0; i < quiz.questions.length && quiz.questions[i].userAnswer != -1; i++ )
            {
                var question = quiz.questions[i];
                if( question.userAnswer == question.correctAnswer.id )
                {
                    if( question.type == "MULTIPLE" )
                    {
                        score += 60;
                    }
                    else if( question.type == "BOOLEAN" )
                    {
                        score += 30;
                    }
                }
            }
            return score;
        }
        quiz.getBonusPoints = function()
        {
            var score = 0;
            for( var i = 0; i < quiz.questions.length && quiz.questions[i].userAnswer != -1; i++ )
            {
                var question = quiz.questions[i];
                if( question.userAnswer == question.correctAnswer.id && question.elapsedTime != -1 )
                {
                    score += (question.elapsedTime);
                }
            }
            return Math.floor(score);
        }
        quiz.getCorrectAnswerId = function()
        {
            return this.questions[this.currentIndex].correctAnswer.id;
        }
        quiz.getTotalCorrectAnswers = function()
        {
            var totalCorrectAnswers = 0;
            for( var i = 0; i < quiz.questions.length && quiz.questions[i].userAnswer != -1; i++ )
            {
                var question = quiz.questions[i];
                if( question.userAnswer == question.correctAnswer.id )
                {
                    ++totalCorrectAnswers;
                }
            }
            return totalCorrectAnswers;
        }
        quiz.getTotalWrongAnswers = function()
        {
            var totalWrongAnswers = 0;
            for( var i = 0; i < quiz.questions.length && quiz.questions[i].userAnswer != -1; i++ )
            {
                var question = quiz.questions[i];
                if( question.userAnswer != question.correctAnswer.id )
                {
                    ++totalWrongAnswers;
                }
            }
            return totalWrongAnswers;
        }
        quiz.getFinalTabData = function()
        {
            var obj = new Object();
            obj.correctAnswers = this.getTotalCorrectAnswers();
            obj.wrongAnswers = this.getTotalWrongAnswers();
            obj.computedScore = this.getComputedScore();
            obj.bonusPoints = this.getBonusPoints();
            obj.correctPoints = this.getCorrectPoints();
            obj.wrongPoints = this.getWrongPoints();
            return obj;
        }
        quiz.getNextCorrectMessage = function()
        {
            var message = this.correctMessages[this.correctMessageIndex];
            this.correctMessageIndex = (this.correctMessageIndex + 1) % this.correctMessages.length;
            return message;
        }
        quiz.getNextWrongMessage = function()
        {
            var message = this.wrongMessages[this.wrongMessageIndex];
            this.wrongMessageIndex = (this.wrongMessageIndex + 1) % this.wrongMessages.length;
            return message;
        }
        quiz.getScoringMessage = function()
        {
            var score = (this.getTotalCorrectAnswers() / this.getTotalQuestions()) * 100;

            if( score == 0 )
            {
                return this.scoringMessages[0];
            }
            else if( score < 60 )
            {
                return this.scoringMessages[1];
            }
            else if( score < 80 )
            {
                return this.scoringMessages[2];
            }
            else if( score < 100 )
            {
                return this.scoringMessages[3];
            }
            else
            {
                return this.scoringMessages[4];
            }
        }

        return quiz;
    }
}

function AOLQuiz( divId, id, startOnLoad, addQuizBottom )
{
    var quizContainer = null;
    var ajax = new AOLQuizAjax();
    var quiz = null;
    var scoreResults = null;
    var self = this;
    var showingFacts = false;
    var status = false;
    var autoStart = startOnLoad != null ? startOnLoad : true;
    var quizId = (id != null ? id : getQueryVariable("quiz-id"));
    var leaderboard = null;
    var preview = false;
    var infinite = (quizId == 0);
    var onNextQuestion = null;
    var onQuizLoaded = new Array();

    if( autoStart )
    {
        addEventSimple(window, "load", init);
    }

    this.show = function()
    {
        init();
    }

    this.remove = function()
    {
        while( quizContainer.childNodes.length > 0 )
        {
            quizContainer.removeChild(quizContainer.lastChild);
        }
        stopTimer();
    }

    this.setPreview = function( p )
    {
        preview = p;
    }

    this.setNextQuestionCallback = function( cb )
    {
        onNextQuestion = cb;
    }

    this.addQuizLoadedCallback = function( cb )
    {
        onQuizLoaded.push(cb);
    }

    this.getQuiz = function()
    {
        return quiz;
    }

    function init()
    {

        quizContainer = _$(divId);
        if( quizContainer )
        {
            loadQuizCSS();

            quizContainer.className = "aolQuiz";
            quizLoading();
            if( infinite )
            {
                ajax.loadInfiniteQuiz(function( q )
                {
                    quiz = q;
                    quizLoaded();
                });
            }
            else
            {
                ajax.loadQuiz(quizId, function( q )
                {
                    quiz = q;
                    quizLoaded();
                });
            }
        }
    }

    function submitScore( event )
    {
        status = true;
        stopDefaultEvent(event ? event : window.event);
        ajax.saveUserScore(quiz, function( results )
        {
            scoreResults = results;
            showTabNavs();
            showTabScore();
        });
    }

    this.nextQuestion = function( event )
    {
        stopDefaultEvent(event ? event : window.event);
        if( onNextQuestion != null )
        {
            onNextQuestion(quiz);
        }
        showingFacts = false;
        updateQuestion();
        startTimer();
    }


    this.onUserAnswer = function( evt )
    {
        stopDefaultEvent(evt ? evt : window.event);
        showingFacts = true;
        if( !document.getElementById('aolQuizFacts') )
        {
            var target = evt.target ? evt.target : evt.srcElement;
            while( target.tagName != "A" )
            {
                target = target.parentNode;
            }
            var targetNode = target;

            // Save time and answer
            var time = getElapsedTime();
            var totalTime = time.getMinutes() * 60 + time.getSeconds();

            quiz.setUserAnswer(target.id, totalTime);
            stopTimer();
            if( !preview )
            {
                _$("aolQuizCorrect").innerHTML = quiz.getTotalCorrectAnswers();
                _$("aolQuizWrong").innerHTML = quiz.getTotalWrongAnswers();
                new AOLQuizScoreAnimator(_$("aolQuizScore"), quiz.getCurrentQuestionPoints(), quiz.getCurrentBonusPoints(), quiz.getComputedScore() + "<br><span>quiz total</span>", target.id == quiz.getCorrectAnswerId());
            }
            if( target.id == quiz.getCorrectAnswerId() )
            {
                target.className = "awHighlight_r_on"
            }
            else
            {
                target.className = "awHighlight_w_on"
            }

            removeEventSimple(target, "click", self.onUserAnswer)
            for( var temp = target.nextSibling; temp != null && temp.tagName == "A"; temp = temp.nextSibling )
            {
                if( temp.id != quiz.getCorrectAnswerId() )
                {
                    temp.className = "awHighlight_w_off";
                }
                else
                {
                    temp.className = "awHighlight_r_off";
                }

                removeEventSimple(temp, "click", self.onUserAnswer)
            }
            for( var temp = target.previousSibling; temp != null && temp.tagName == "A"; temp = temp.previousSibling )
            {
                if( temp.id != quiz.getCorrectAnswerId() )
                {
                    temp.className = "awHighlight_w_off";
                }
                else
                {
                    temp.className = "awHighlight_r_off";
                }
                removeEventSimple(temp, "click", self.onUserAnswer)
            }

            setTimeout(function ()
            {
                showFacts(targetNode);
            }, 1000);
        }
    }

    function showFacts( target )
    {
        var btnMenu = _$("aolQuizBtnMenu");
        if( btnMenu != null )
        {
            btnMenu.style.display = "none";
        }
        var correctAnswerToKeep = null;
        for( var temp = target.nextSibling; temp != null && temp.tagName == "A"; )
        {
            var toRemove = temp;
            temp = temp.nextSibling;
            toRemove.parentNode.removeChild(toRemove);
            if( toRemove.id == quiz.getCorrectAnswerId() )
            {
                correctAnswerToKeep = toRemove
            }
        }
        for( var temp = target.previousSibling; temp != null && temp.tagName == "A"; )
        {
            var toRemove = temp;
            temp = temp.previousSibling;
            toRemove.parentNode.removeChild(toRemove);
            if( toRemove.id == quiz.getCorrectAnswerId() )
            {
                correctAnswerToKeep = toRemove;
            }
        }

        // Clear div
        var clearDiv = document.createElement("div");
        clearDiv.className = "cl";

        var facts = document.createElement("div");
        facts.setAttribute("id", "aolQuizFacts");
        facts.innerHTML = quiz.getCurrentQuestion().fact;

        var showFactsLink = document.createElement("a");
        showFactsLink.setAttribute("id", "showFactsLink");
        showFactsLink.setAttribute("href", "#");
        showFactsLink.innerHTML = "show question";
        addEventSimple(showFactsLink, "click", showHideFacts);

        var nextBtnDiv = document.createElement("div");
        nextBtnDiv.className = "btnNextDiv";
        if( quiz.getCurrentQuestion().fact != "" )
        {
            nextBtnDiv.appendChild(showFactsLink);
        }
        if( target.id == quiz.getCorrectAnswerId() )
        {
            target.parentNode.childNodes[1].innerHTML = quiz.getNextCorrectMessage();
        }
        else
        {
            target.parentNode.childNodes[1].innerHTML = quiz.getNextWrongMessage();
            var correctTitle = document.createElement("h4");
            correctTitle.innerHTML = "The Correct Answer is:"
            target.parentNode.appendChild(correctTitle);
            target.parentNode.appendChild(correctAnswerToKeep);
        }
        target.parentNode.appendChild(clearDiv);
        if( quiz.getCurrentQuestion().fact != "" )
        {
            target.parentNode.appendChild(facts);
        }
        if( !quiz.isLastQuestion() )
        {
            var nextBtn = document.createElement("a");
            nextBtn.setAttribute("href", "#");
            nextBtn.className = "btnB";
            nextBtn.innerHTML = "next question >"
            addEventSimple(nextBtn, "click", self.nextQuestion);
            nextBtnDiv.appendChild(nextBtn);
            target.parentNode.appendChild(nextBtnDiv);
        }
        else
        {
            if( !preview )
            {
                var seeResultBtn = document.createElement("a");
                seeResultBtn.setAttribute("href", "#");
                seeResultBtn.className = "btnB";
                seeResultBtn.innerHTML = "See Your Result >"
                addEventSimple(seeResultBtn, "click", submitScore);
                nextBtnDiv.appendChild(seeResultBtn);
                target.parentNode.appendChild(nextBtnDiv);
            }
        }
        
        //answer image
        var imgContainer = document.getElementById("quizImgArea");
        if(imgContainer != null )
        {
            if(quiz.getCurrentQuestion().answerImage != null)
            {
                var image = imgContainer.getElementsByTagName("img")[0];
                image.src = quiz.getCurrentQuestion().answerImage;
            }
        }    
        

        quiz.nextQuestion();
    }


    function quizLoading()
    {
        // Top container
        /*var titleSec = document.createElement("div");
        titleSec.setAttribute("id", "aolQuizTitleSec");

        // Title
        var title = document.createElement("div");
        title.setAttribute("id", "aolQuizTitle");
        title.innerHTML = "Loading...";

        // Creator
        var creator = document.createElement("div");
        creator.setAttribute("id", "aolQuizCreator");

        // Append to top container
        titleSec.appendChild(title);
        titleSec.appendChild(creator);*/

        // Counter
        var quizCounter = document.createElement("div");
        quizCounter.setAttribute("id", "aolQuizCounter");

        // Score
        var quizScore = document.createElement("div");
        quizScore.setAttribute("id", "aolQuizScore");
        quizScore.innerHTML = "0"

        // Timer container
        var quizTimerSec = document.createElement("div");
        quizTimerSec.setAttribute("id", "aolQuizTimerSec");

        // Actual timer
        self.quizTimer = document.createElement("span");
        self.quizTimer.setAttribute("id", "aolQuizTimer");
        self.quizTimer.setAttribute("title", "Bonus Point Timer");
        self.quizTimer.innerHTML = "60";

        // Correct counter
        var quizCorrect = document.createElement("span");
        quizCorrect.setAttribute("id", "aolQuizCorrect");
        quizCorrect.setAttribute("title", "Correct Answers");
        quizCorrect.innerHTML = "0";

        // Wrong counter
        var quizWrong = document.createElement("span");
        quizWrong.setAttribute("id", "aolQuizWrong");
        quizWrong.setAttribute("title", "Incorrect Answers");
        quizWrong.innerHTML = "0";

        // Clear div
        var clearDiv = document.createElement("div");
        clearDiv.className = "cl";

        // Clear div
        var clearDiv2 = document.createElement("div");
        clearDiv2.className = "cl";

        // Append children
        quizTimerSec.appendChild(self.quizTimer);
        quizTimerSec.appendChild(quizCorrect);
        quizTimerSec.appendChild(quizWrong);
        quizCounter.appendChild(quizScore);
        quizCounter.appendChild(quizTimerSec);
        quizCounter.appendChild(clearDiv);

        //Quiz bottom b
        if(addQuizBottom)
        {
            var quizBot = document.createElement("div");
            quizBot.setAttribute("id", "aolQuizBot");

            var btnCreate = document.createElement("a");
            btnCreate.className = "btnG create";
            btnCreate.setAttribute("href", "/user-quizzes/create");
            btnCreate.innerHTML = "create your own quiz";

            var btnInfo = document.createElement("a");
            btnInfo.className = "btnG infoBtn";
            btnInfo.setAttribute("href", "#");
            btnInfo.setAttribute("id", "aolHelpBtn");
            btnInfo.innerHTML = "?";
            addEventSimple(btnInfo, "click", showHelp);

            var btnMenu = document.createElement("a");
            btnMenu.className = "btnG menu";
            btnMenu.setAttribute("id", "aolQuizBtnMenu");
            btnMenu.setAttribute("href", "#");
            btnMenu.innerHTML = "menu";
            addEventSimple(btnMenu, "click", showMenu);

            var btnFeedback = document.createElement("a");
            btnFeedback.className = "btnG feedback";
            btnFeedback.setAttribute("href", "#");
            btnFeedback.setAttribute("id", "aolQuizBtnNotify");
            btnFeedback.innerHTML = "Notify";
            addEventSimple(btnFeedback, "click", showNotify);
            quizBot.appendChild(btnCreate);
            quizBot.appendChild(btnInfo);
            quizBot.appendChild(btnFeedback);
            quizBot.appendChild(btnMenu);
            quizBot.appendChild(clearDiv2);
        }
        else
        {
            var btnMenu = document.getElementById("aolQuizBtnMenu");
            var btnNotify = document.getElementById("aolQuizBtnNotify");
            var btnHelp = document.getElementById("aolHelpBtn");
            
            if(btnMenu != null)
                addEventSimple(btnMenu, "click", showMenu);
            
            if(btnNotify != null)
                addEventSimple(btnNotify, "click", showNotify);
            
            if(btnHelp != null)
                addEventSimple(btnHelp, "click", showHelp);
        }

        // Question container
        var questionContainer = document.createElement("div");
        questionContainer.setAttribute("id", "aolQuestionContainer");
        var loadingImage = document.createElement("img");
        loadingImage.setAttribute("src", CDN_HOST + "/images/loading.gif");
        loadingImage.setAttribute("border", "0");
        questionContainer.appendChild(loadingImage);

        // End Card container
        var quizEndCard = document.createElement("div");
        quizEndCard.setAttribute("id", "aolQuizEndCard");
        quizEndCard.style.display = "none";

        //var quizAboutDiv = document.createElement("div");
        //quizAboutDiv.setAttribute("id", "aolQuizAboutDiv");


        // Append containers and children
        //quizContainer.appendChild(titleSec);

        if( !preview )
        {
            quizContainer.appendChild(quizCounter);
        }

        quizContainer.appendChild(questionContainer);
        quizContainer.appendChild(quizEndCard);

        if( !preview )
        {
            //quizContainer.appendChild(quizBot);
        }
        //quizContainer.appendChild(quizAboutDiv);


    }

    function quizLoaded()
    {
        if( _$("aolQuizScore") != null )
        {
            _$("aolQuizScore").innerHTML = quiz.getComputedScore();
        }

        // Call other callbacks
        for (var i = 0; i < onQuizLoaded.length; i++)
        {
            onQuizLoaded[i](self);
        }

        // Pre load images
        for( var i = 0; i < quiz.getTotalQuestions(); i++ )
        {
            var question = quiz.getQuestion(i);
            if( question && question.image )
            {
                var image = new Image();
                image.src = question.image;
            }
        }

        updateQuestion();


        // Show timer notice
        if (!preview)
        {
            showTimerNotice();
        }
    }

    function showTimerNotice()
    {
        var questionContainer = _$("aolQuestionContainer");
        var timerMessage = document.createElement("div")
        timerMessage.id = "aolTimerNotice"
        timerMessage.style.height = questionContainer.offsetHeight + "px";
        questionContainer.appendChild(timerMessage)

        var aolTimerNoticeTop = document.createElement("div")
        aolTimerNoticeTop.id = "aolTimerNoticeTop"
        questionContainer.appendChild(aolTimerNoticeTop)

        var text = document.createElement("div")
        text.innerHTML = "Answer a question in less than 60 seconds to earn bonus points. <br>The countdown tells you how many points you'll get."
        text.style.margin = "10px 60px"
        aolTimerNoticeTop.appendChild(text)

        var closeBtn = document.createElement("a")
        closeBtn.setAttribute("href", "#")
        closeBtn.innerHTML = "[x] Closing in 5"
        closeBtn.id = "timerCloseBtn"
        aolTimerNoticeTop.appendChild(closeBtn)
        addEventSimple(closeBtn, "click", hideTimerNotice)
        setTimeout(timerNoticeCountDown, 1000)
    }

    function timerNoticeCountDown()
    {
        var closeBtn = _$("timerCloseBtn")
        if( closeBtn )
        {
            var sec = (closeBtn.innerHTML.replace("[x] Closing in ", "") - 1)
            closeBtn.innerHTML = "[x] Closing in " + sec
            if( sec > 0 )
            {
                closeBtn.innerHTML = "[x] Closing in " + sec
                setTimeout(timerNoticeCountDown, 1000)
            }
            else
            {
                hideTimerNotice();
            }
        }
    }
    function hideTimerNotice( event )
    {
        stopDefaultEvent(event ? event : window.event);
        _$("aolQuestionContainer").removeChild(_$("aolTimerNoticeTop"))
        _$("aolQuestionContainer").removeChild(_$("aolTimerNotice"))
        startTimer()
    }

    function showHideFacts( event )
    {
        stopDefaultEvent(event ? event : window.event);
        var mylink = _$("showFactsLink");
        var facts = _$("aolQuizFacts");
        if( mylink.innerHTML == "show question" )
        {
            mylink.innerHTML = "show facts";
            facts.innerHTML = quiz.getPreviousQuestion().text;
        }
        else if( mylink.innerHTML == "show facts" )
        {
            mylink.innerHTML = "show question";
            facts.innerHTML = quiz.getPreviousQuestion().fact;
        }
    }

    function signIn( event )
    {
        stopDefaultEvent(event ? event : window.event);
        if( quizSNS )
        {
            var quizBtnMenu = _$("aolQuizBtnMenu");

            quizSNS.setCallback(function()
            {
                if( quizBtnMenu != null )
                {
                    quizBtnMenu.className = "btnG menu";
                }
                var div = _$("aolQuizScoreDesc").innerHTML = "Please wait...";
                if( quiz.isLastQuestion() )
                {
                    setTimeout(submitScore, 500);
                }
                else
                {
                    setTimeout(showMenu, 500);
                }
            });
            _$("aolQuizScoreDesc").innerHTML = "Waiting for user to sign in..."
            quizSNS.signIn();
        }
    }

    function showMenu( event )
    {
        stopDefaultEvent(event ? event : window.event);
        var quizBtnMenu = _$("aolQuizBtnMenu");
        _$("aolQuizBtnNotify").className = "btnG feedback";
        if( !status && (quizBtnMenu == null || quizBtnMenu.className == "btnGOn menu") )
        {
            updateQuestion();
        }
        else if( quizBtnMenu.className == "btnG menu" )
        {
            ajax.getUserScoreResults(function( rs )
            {
                scoreResults = rs;
                var quizEndCard = _$("aolQuizEndCard");
                while( quizEndCard.hasChildNodes() )
                {
                    quizEndCard.removeChild(quizEndCard.lastChild);
                }
                showTabNavs();
                showTabScore();
            });
        }
    }

    function showNotify( event )
    {
        stopDefaultEvent(event ? event : window.event);
        _$("aolHelpBtn").className = "btnG infoBtn";
        var notifyBtn = _$("aolQuizBtnNotify");
        if( notifyBtn.className == "btnG feedback" )
        {
            notifyBtn.className = "btnGOn feedback";
            var questionContainer = _$("aolQuestionContainer");
            if( questionContainer.style.display == "none" )
            {
                questionContainer.style.display = "";
                _$("aolQuizEndCard").style.display = "none";
            }
            ajax.getUser(function( user )
            {
                if( user.loggedIn )
                {
                    while( questionContainer.hasChildNodes() )
                    {
                        questionContainer.removeChild(questionContainer.lastChild);
                    }
                    questionContainer.innerHTML =
                    "<div align=\"right\"><a href=\"#\" id=\"closeButton\">CLOSE [X]</a></div>" +
                    "<form method=\"post\" action=\"\" id=\"notifyForm\">\n" +
                    "  <strong>Send a notification about</strong><br />\n" +
                    "  <div>\n" +
                    "    <label><input type=\"radio\" name=\"error\" id=\"inapproperiate\" value=\"inapproperiate\" checked=\"checked\"/> Inappropriate Content</label>\n" +
                    "  </div>\n" +
                    "  <strong>Regarding this question or quiz</strong>\n" +
                    "  <br>\n" +
                    "    <textarea name=\"notifyComment\" id=\"sendmail_comments\" cols=\"45\" rows=\"5\" class=\"field\"></textarea>\n" +
                    "  <div id=\"captcha\">&nbsp;</div>\n" +
                    "  <input type=\"button\" class=\"btnG send\" value=\"Send\" name=\"submitBtn\" id=\"notifySubmit\"/>\n" +
                    "  <input type=\"reset\" class=\"btnG send\" value=\"Clear\" name=\"resetBtn\"/>\n" +
                    "  <input id=\"sendmail_to\" type=\"hidden\" value=\"namestotos2@aol.com\" />\n" +
                    "  <input id=\"sendmail_subject\" type=\"hidden\" value=\"Movie Quizzes Abuse Report\" />\n" +
                    "  <input id=\"sendmail_body\" type=\"hidden\" value=\"\" />\n" +
                    "  </form>";

                    addEventSimple(_$("closeButton"), "click", showNotify);
                    var sm = new AOLSendMail("notifySubmit");
                    sm.onError(function( error )
                    {
                        if( error.error != "CAPTCHA_RESPONSE" )
                        {
                            alert("There was a problem sending email. Please try again later")
                        }
                        else
                        {
                            alert("Please try typing in the correct letters that appear in the image")
                        }
                    });
                    sm.onMessageSent(function()
                    {
                        _$("notifyForm").innerHTML = '<div style="height:280px; font-size:18px">Message sent successfully.</div>';
                    })

                    sm.onBeforeSend(function()
                    {
                        _$("sendmail_body").value = generateNotifyMessage(user.user);
                    })

                }
                else
                {
                    questionContainer.innerHTML = '<div style="height:280px; font-size:18px">You must be signed in to submit notifications regarding this quiz.</div>';
                }
            });
        }
        else
        {
            notifyBtn.className = "btnG feedback";
            updateQuestion();
        }
    }

    function generateNotifyMessage( user )
    {
        return "<p><strong>Date:</strong> " + new Date() + "</p>\n" +
               "<p><strong>Country:</strong> US - English</p>\n" +
               "<p><strong>URL:</strong> " + quiz.url + "</p>\n" +
               "<p><strong>Admin Tool (Sign in as admin user):</strong> http://movies.aol.com/user-quizzes/quizzard/" + quiz.author + "</p>\n" +
               "<p><strong>Violator:</strong> " + quiz.author + "</p>\n" +
               "<p><strong>Violator IP:</strong> " + quiz.ipAddr + "</p>\n" +
               "<p><strong>Reporter:</strong> " + user + "</p>\n" +
               "<p><strong>Reporter Comments:</strong> " + _$("sendmail_comments").value + "</p>";
    }
    function showHelp( event )
    {
        stopDefaultEvent(event ? event : window.event);
        _$("aolQuizBtnNotify").className = "btnG feedback";

        var notifyBtn = _$("aolHelpBtn");
        if( notifyBtn.className == "btnG infoBtn" )
        {
            notifyBtn.className = "btnGOn infoBtn";
            var questionContainer = _$("aolQuestionContainer");
            if( questionContainer.style.display == "none" )
            {
                questionContainer.style.display = "";
                _$("aolQuizEndCard").style.display = "none";
            }
            while( questionContainer.hasChildNodes() )
            {
                questionContainer.removeChild(questionContainer.lastChild);
            }

            questionContainer.innerHTML =
            "<div id=\"quizHelp\">\n" +
            "   <div align=\"right\"><a href=\"#\" id=\"closeButton\">CLOSE [X]</a></div>" +
            "   <h1 class=\"help\">Help on Taking Quizzes</h1>\n" +
            "   Anybody can take AOL Quizzes. If you'd like us to store your scores, just " +
            "   <a href=\"https://my.screenname.aol.com/_cqr/login/login.psp?sitedomain=channel.aol.com&siteState=OrigUrl%3d" + window.location + "\" title=\"Sign In/Register\">Sign In/Register</a> before you take a quiz.<br /><br />\n" +
            "    Hang on, did you say &quot;scores&quot;?<br />\n" +
            "      <b>That's right ...</b> you get points for your correct answers AND for how quickly you make those answers.<br /><br />\n" +
            "      What are the points good for? If I load up on points can I trade them in for a new Nintendo Wii?<br />\n" +
            "      Well, no ... but it's kind of fun to watch those points pile up. You won't win any fancy prizes, but your top score may make the Leader Board. And isn't that prize enough?<br /><br />\n" +
            "   <b>Quiz Points</b>\n" +
            "   <div id=\"quizPoints\">\n" +
            "        <div class=\"header first\">Multiple Choice Questions</div>\n" +
            "        <div class=\"correct\"><i>+60</i>Correct Answers</div>\n" +
            "        <div class=\"wrong\"><i>-30</i>Incorrect Answers</div>\n" +
            "        <div class=\"header\">True or False Questions</div>\n" +
            "        <div class=\"correct\"><i>+30</i>Correct Answers</div>\n" +
            "        <div class=\"wrong\"><i>-20</i>Incorrect Answers</div>\n" +
            "        <div class=\"header\">Speed Bonus (you get bonus points for answering within the 60 second countdown)</div>\n" +
            "        <div class=\"correct noback\"><i>+60</i>60 seconds</div>\n" +
            "        <div class=\"correct noback\"><i>+59</i>59 seconds</div>\n" +
            "        <div class=\"correct noback\"><i>+58</i>58 seconds</div>\n" +
            "        <div class=\"correct noback\">...</div> \n" +
            "        <div class=\"correct noback\"><i>+23</i>23 seconds</div>\n" +
            "    </div>\n" +
            "    Don't worry. If you answer the question after the 60 second countdown ends you still get the base points.\n" +
            "</div>";

            addEventSimple(_$("closeButton"), "click", showHelp);
        }
        else
        {
            notifyBtn.className = "btnG infoBtn";
            updateQuestion();
        }
    }
    function showInfo( event )
    {
        stopDefaultEvent(event ? event : window.event);
        ajax.getUserScoreResults(function( results )
        {
            scoreResults = results;
            var quizEndCard = _$("aolQuizEndCard");
            while( quizEndCard.hasChildNodes() )
            {
                quizEndCard.removeChild(quizEndCard.lastChild);
            }
            showTabNavs();
            showTabInfo();
        });
    }

    function showTabNavs()
    {
        var questionContainer = _$("aolQuestionContainer");
        var quizEndCard = _$("aolQuizEndCard");
        var quizBot = _$("aolQuizBot");
        var btnMenu = _$("aolQuizBtnMenu");
        if( btnMenu != null )
        {
            btnMenu.style.display = "";
        }
        quizEndCard.style.display = "";

        //End Card Tab
        var quizEndCardTab = document.createElement("div");
        quizEndCardTab.setAttribute("id", "aolQuizEndCardTab");
        //End Card Text

        if( status )
        {
            var quizEndCardTabText = document.createElement("div");
            quizEndCardTabText.setAttribute("id", "quizEndCardTabTextTitle");
            quizEndCardTabText.setAttribute("style", "padding:6px 0; height: 14px");
            quizEndCardTabText.innerHTML = "You have finished the quiz!";
        }
        else
        {
            var currentQuestion = quiz.getCurrentQuestion();
            var quizEndCardTabText = document.createElement("div");
            quizEndCardTabText.setAttribute("id", "quizEndCardTabTextTitle");
            quizEndCardTabText.setAttribute("style", "padding:6px 0; height: 14px");
            var quizEndCardTabTextA = document.createElement("a");
            quizEndCardTabTextA.setAttribute("href", "#");
            quizEndCardTabTextA.innerHTML = "Return to Question #" + (quiz.getCurrentIndex() + 1);
            addEventSimple(quizEndCardTabTextA, "click", updateQuestion);
            quizEndCardTabText.appendChild(quizEndCardTabTextA);
        }


        var quizEndCardTabUl = document.createElement("ul");
        quizEndCardTabUl.className = "shadetabs";

        var quizEndCardTabLi1 = document.createElement("li");

        quizEndCardTabLi1.innerHTML = '<a href="#">Your Score</a>';
        addEventSimple(quizEndCardTabLi1, "click", showTabScore);

        var quizEndCardTabLi2 = document.createElement("li");
        quizEndCardTabLi2.innerHTML = '<a href="#">More Quizzes</a>';
        addEventSimple(quizEndCardTabLi2, "click", showTabMoreQuizzes);

        var quizEndCardTabLi3 = document.createElement("li");
        quizEndCardTabLi3.innerHTML = '<a href="#">Share</a>';
        addEventSimple(quizEndCardTabLi3, "click", showTabShare);

        var quizEndCardTabLi4 = document.createElement("li");
        quizEndCardTabLi4.innerHTML = '<a href="#">Snag</a>';
        addEventSimple(quizEndCardTabLi4, "click", showTabSnag);

        var quizEndCardTabLi5 = document.createElement("li");
        quizEndCardTabLi5.innerHTML = '<a href="#" class="last">Info</a>';
        addEventSimple(quizEndCardTabLi5, "click", showInfo);

        // remove div
        questionContainer.style.display = "none";
        if( btnMenu != null )
        {
            btnMenu.className = "btnGOn menu";
        }
        quizEndCardTab.appendChild(quizEndCardTabText);
        quizEndCardTab.appendChild(quizEndCardTabUl);
        quizEndCardTabUl.appendChild(quizEndCardTabLi1);
        quizEndCardTabUl.appendChild(quizEndCardTabLi2);
        quizEndCardTabUl.appendChild(quizEndCardTabLi3);
        //quizEndCardTabUl.appendChild(quizEndCardTabLi4);
        quizEndCardTabUl.appendChild(quizEndCardTabLi5);
        quizEndCard.appendChild(quizEndCardTab);
    }

    function showTabScore( event )
    {
        stopDefaultEvent(event ? event : window.event);
        var quizEndCard = _$("aolQuizEndCard");
        // Remove all children before updating to next question
        while( quizEndCard.childNodes.length >= 2 )
        {
            quizEndCard.removeChild(quizEndCard.lastChild);
        }

        if( status && quizEndCard )
        {
            quizEndCard.firstChild.firstChild.innerHTML = "You have finished the quiz!"
        }

        var tabs = quizEndCard.firstChild.firstChild.nextSibling.childNodes;

        for( var i = 0; i < tabs.length; i++ )
        {
            tabs[i].className = "";
        }

        tabs[0].className = "on"

        var results = quiz.getFinalTabData();

        // Clear div
        var clearDiv = document.createElement("div");
        clearDiv.className = "cl";

        var quizEndCardContent = document.createElement("div");
        quizEndCardContent.setAttribute("id", "aolQuizTabScore");

        //End Card Correct Answer CountSection
        var quizEndCardCorrectSec = document.createElement("div");
        quizEndCardCorrectSec.className = "scoreRow";

        var quizEndCardPGain = document.createElement("span");
        quizEndCardPGain.setAttribute("id", "pGain");
        quizEndCardPGain.innerHTML = results.correctPoints;

        var quizEndCardPGainDesc = document.createElement("span");
        quizEndCardPGainDesc.className = "pDesc correct";
        quizEndCardPGainDesc.innerHTML = "Correct Answers ";

        var quizEndCardPGainNum = document.createElement("span");
        quizEndCardPGainNum.setAttribute("id", "rNum");
        quizEndCardPGainNum.innerHTML = "(" + results.correctAnswers + ")";
        quizEndCardCorrectSec.appendChild(quizEndCardPGain);
        quizEndCardCorrectSec.appendChild(quizEndCardPGainDesc);
        quizEndCardCorrectSec.appendChild(quizEndCardPGainNum);


        //End Card Wrong Answer Count Section
        var quizEndCardWrongSec = document.createElement("div");
        quizEndCardWrongSec.className = "scoreRow";

        var quizEndCardPLoss = document.createElement("span");
        quizEndCardPLoss.setAttribute("id", "pLoss");
        quizEndCardPLoss.className = "minus";
        quizEndCardPLoss.innerHTML = "-" + results.wrongPoints;

        var quizEndCardPLossDesc = document.createElement("span");
        quizEndCardPLossDesc.className = "pDesc wrong";
        quizEndCardPLossDesc.innerHTML = "Incorrect Answers ";

        var quizEndCardPLossNum = document.createElement("span");
        quizEndCardPLossNum.setAttribute("id", "wNum");
        quizEndCardPLossNum.innerHTML = "(" + results.wrongAnswers + ")";
        quizEndCardWrongSec.appendChild(quizEndCardPLoss);
        quizEndCardWrongSec.appendChild(quizEndCardPLossDesc);
        quizEndCardWrongSec.appendChild(quizEndCardPLossNum);

        //End Card Bonus Count Section
        var quizEndCardBonusSec = document.createElement("div");
        quizEndCardBonusSec.className = "scoreRow";

        var quizEndCardBGain = document.createElement("span");
        quizEndCardBGain.setAttribute("id", "bGain");
        quizEndCardBGain.innerHTML = results.bonusPoints;

        var quizEndCardBGainDesc = document.createElement("span");
        quizEndCardBGainDesc.className = "pDesc time";
        quizEndCardBGainDesc.innerHTML = "Speed Bonus ";
        quizEndCardBonusSec.appendChild(quizEndCardBGain);
        quizEndCardBonusSec.appendChild(quizEndCardBGainDesc);


        //End Card Total Count Section
        var quizEndCardTotalSec = document.createElement("div");
        quizEndCardTotalSec.className = "scoreRow";

        var quizEndCardPTotal = document.createElement("span");
        quizEndCardPTotal.setAttribute("id", "pTotal");
        quizEndCardPTotal.innerHTML = results.computedScore;

        var quizEndCardPTotalDesc = document.createElement("span");
        quizEndCardPTotalDesc.className = "quizTotal";
        quizEndCardPTotalDesc.innerHTML = "Quiz Total ";

        quizEndCardTotalSec.appendChild(quizEndCardPTotal);
        quizEndCardTotalSec.appendChild(quizEndCardPTotalDesc);

        //End Card Note Section
        var quizEndCardNote = document.createElement("div");
        quizEndCardNote.setAttribute("id", "aolQuizTabScoreNote");

        if( status )
        {
            var quizEndCardCgText = document.createElement("div");
            quizEndCardCgText.setAttribute("id", "cgText");
            quizEndCardCgText.innerHTML = quiz.getScoringMessage();
            var quizEndCardLbTextDiv = document.createElement("div");
            var quizEndCardLbText = document.createElement("span");
            quizEndCardLbText.className = "lbText";
            var quizEndCardQuizStand = document.createElement("span");
            quizEndCardQuizStand.setAttribute("id", "quizStand");

            if( scoreResults.userInLeaderboard )
            {
                quizEndCardLbText.innerHTML = "You made the leader board";
                quizEndCardQuizStand.innerHTML = "<b> #" + scoreResults.userPositionInLeaderboard + " this week</b>";
                if( leaderboard != null && leaderboard.refresh != null )
                {
                    leaderboard.refresh();
                }
            }
            else
            {
                quizEndCardLbText.innerHTML = "You did not make the leader board";
                quizEndCardQuizStand.innerHTML = "";
            }


            var quizEndCardBtnDiv = document.createElement("div");
            var quizEndCardBtn = document.createElement("a");
            quizEndCardBtn.className = "btnB";
            quizEndCardBtn.setAttribute("href", "#");
            quizEndCardBtn.setAttribute("style", "margin-left:auto; margin-right:auto");
            quizEndCardBtn.innerHTML = 'Take Another Quiz';
            addEventSimple(quizEndCardBtn, "click", showTabMoreQuizzes);

            quizEndCardBtnDiv.appendChild(quizEndCardBtn);
            quizEndCardLbTextDiv.appendChild(quizEndCardLbText);
            quizEndCardLbTextDiv.appendChild(quizEndCardQuizStand);
            quizEndCardLbTextDiv.appendChild(quizEndCardBtnDiv);
            quizEndCardNote.appendChild(quizEndCardCgText);
            quizEndCardNote.appendChild(quizEndCardLbTextDiv);
        }
        else
        {
            var quizEndCardCgText = document.createElement("div");
            quizEndCardCgText.setAttribute("id", "cgText2");
            quizEndCardCgText.className = "notFinish";
            quizEndCardCgText.innerHTML = "You have not completed this quiz.";
            var quizEndCardBtn = document.createElement("a");
            quizEndCardBtn.setAttribute("href", "#");
            quizEndCardBtn.innerHTML = "Finish This Quiz";
            quizEndCardBtn.className = "btnB";
            quizEndCardBtn.setAttribute("style", "margin-left:auto; margin-right:auto");
            addEventSimple(quizEndCardBtn, "click", updateQuestion);
            var clearBr = document.createElement("br");
            clearBr.className = "noHeight";
            quizEndCardNote.appendChild(quizEndCardCgText);
            quizEndCardNote.appendChild(quizEndCardBtn);
            quizEndCardNote.appendChild(clearBr);
        }

        //End Card Result Section
        var quizEndCardResult = document.createElement("div");
        quizEndCardResult.setAttribute("id", "aolQuizTabScoreResult");

        var quizEndCardResultM = document.createElement("div");
        quizEndCardResultM.className = "endCardResultMargin";

        var quizTotalScore = document.createElement("span");
        quizTotalScore.setAttribute("id", "totalScore");
        var quizScoreDesc = document.createElement("span");

        if( scoreResults.user.loggedIn )
        {
            quizTotalScore.innerHTML = scoreResults.userInfo.totalScore;
            quizScoreDesc.innerHTML = "Your Total Score (For All Quizzes)";
        }
        else
        {
            var text1 = document.createTextNode("You must ");
            var text2 = document.createTextNode(" to save or view your quiz scores.");
            var link = document.createElement("a");
            link.setAttribute("href", "#");
            link.innerHTML = "sign in";
            addEventSimple(link, "click", signIn);
            quizScoreDesc.appendChild(text1);
            quizScoreDesc.appendChild(link);
            quizScoreDesc.appendChild(text2);
            quizScoreDesc.setAttribute("id", "aolQuizScoreDesc");
        }

        // Append the children to the right
        var rightScoreCard = document.createElement("div");
        rightScoreCard.className = "rightScoreCard";
        rightScoreCard.appendChild(quizEndCardCorrectSec);
        rightScoreCard.appendChild(quizEndCardWrongSec);
        rightScoreCard.appendChild(quizEndCardBonusSec);
        rightScoreCard.appendChild(quizEndCardTotalSec);
        
        // Append the children to the left
        var leftScoreCard = document.createElement("div");
        leftScoreCard.className = "leftScoreCard";
        leftScoreCard.appendChild(quizEndCardNote);
        
        // Clear element
        var clearElem = document.createElement("div");
        clearElem.className = "clearBlock";
        
        var brNoHeight = document.createElement("br");
        brNoHeight.className = "noHeight";
        
        quizEndCardResultM.appendChild(quizTotalScore);
        quizEndCardResultM.appendChild(quizScoreDesc);
        quizEndCardResult.appendChild(quizEndCardResultM);
        quizEndCardResult.appendChild(brNoHeight);
        quizEndCardContent.appendChild(leftScoreCard);
        quizEndCardContent.appendChild(rightScoreCard);
        quizEndCardContent.appendChild(clearElem);
        quizEndCard.appendChild(quizEndCardContent);
        quizEndCard.appendChild(quizEndCardResult);
    }

    function showTabMoreQuizzes( event )
    {
        stopDefaultEvent(event ? event : window.event);
        var quizEndCard = _$("aolQuizEndCard");
        while( quizEndCard.childNodes.length >= 2 )
        {
            quizEndCard.removeChild(quizEndCard.lastChild);
        }

        var tabs = quizEndCard.firstChild.firstChild.nextSibling.childNodes;
        for( var i = 0; i < tabs.length; i++ )
        {
            tabs[i].className = "";
        }
        tabs[1].className = "on"


        var quizTabMQ = document.createElement("div");
        quizTabMQ.setAttribute("id", "aolQuizTabMQ");
        if( scoreResults.otherQuizzes )
        {
            for( var key in scoreResults.otherQuizzes )
            {
                if( scoreResults.otherQuizzes[key].id == quiz.id )
                {
                    continue;
                }
                //Quiz Item
                var quizTabMQRow1 = document.createElement("div");
                quizTabMQRow1.className = "qRow";

                var quizTabMQRow1Img = document.createElement("div");
                quizTabMQRow1Img.className = "qImg";
                quizTabMQRow1Img.innerHTML = '<a class="qTitle" href="/user-quizzes/view-quiz/' + scoreResults.otherQuizzes[key].id + '"><img src="' + scoreResults.otherQuizzes[key].image + '" alt="" border="0"></a>';

                var quizTabMQRow1Content = document.createElement("div");
                quizTabMQRow1Content.className = "qContent";

                if( scoreResults.otherQuizzes[key].questionCount )
                {
                    quizTabMQRow1Content.innerHTML += '<a class="qTitle" href="/user-quizzes/view-quiz/' + scoreResults.otherQuizzes[key].id + '">' + scoreResults.otherQuizzes[key].title + '</a>';
                    quizTabMQRow1Content.innerHTML += '<div class="qDesc">' + scoreResults.otherQuizzes[key].description + '</div>';
                    quizTabMQRow1Content.innerHTML += '<div class="qContentL">Questions: <b>' + scoreResults.otherQuizzes[key].questionCount + '</b><br>Difficulty: <b>' + scoreResults.otherQuizzes[key].difficulty + '</b></div>';
                }

                //quizTabMQRow1Content.innerHTML += '<div class="qContentR">Rating:<br><img src="' + CDN_HOST + '/images/rating_4.gif" alt="" width="75" height="15" border="0"></div>';

                var quizTabMQRow1Cl = document.createElement("div");
                quizTabMQRow1Cl.className = "cl";

                quizTabMQRow1.appendChild(quizTabMQRow1Img);
                quizTabMQRow1.appendChild(quizTabMQRow1Content);
                quizTabMQRow1.appendChild(quizTabMQRow1Cl);

                quizTabMQ.appendChild(quizTabMQRow1);
            }
        }

        var quizTabMQSearch = document.createElement("div");
        quizTabMQSearch.setAttribute("id", "aolQuizTabMQSearch");
        quizTabMQSearch.innerHTML =
        '<a href="/user-quizzes" class="btnG browserQ">Browse All Quizzes</a>' +
        '<form class="tabMQSearch" action="/user-quizzes/hub" name="search" method="get">' +
        '<input type="text" name="q" onfocus="this.value=\'\'" value="Search Quizzes" size="20" class="quizSearchInput"/>' +
        '<input type="image" src="' + CDN_HOST + '/images/btn_submit.gif" style="vertical-align:middle" onclick="this.form.submit()"/></form>';
        quizEndCard.appendChild(quizTabMQ);
        quizEndCard.appendChild(quizTabMQSearch);
    }

    function showTabShare( event )
    {
        stopDefaultEvent(event ? event : window.event);
        var quizEndCard = _$("aolQuizEndCard");
        // Remove all children before updating to next question
        while( quizEndCard.childNodes.length >= 2 )
        {
            quizEndCard.removeChild(quizEndCard.lastChild);
        }
        var tabs = quizEndCard.firstChild.firstChild.nextSibling.childNodes;

        for( var i = 0; i < tabs.length; i++ )
        {
            tabs[i].className = "";
        }
        tabs[2].className = "on"

        var quizTabShare = document.createElement("div");
        quizTabShare.setAttribute("id", "aolQuizTabShare");

        var innerHtml = '<form class="dm_form" id="sendmail_form"><div id="errorMessage">&nbsp;</div><div class="form_wrapper"><fieldset><label class="w100 inputselect" for="to">';
        innerHtml += '<span class="wrapper"><span class="title">To:</span><input class="field" onfocus="this.value=\'\'" id="sendmail_to" name="sendmail_to" value="Enter your friend\'s email address" type="text"></span>';
        innerHtml += '</label><div class="cl"></div>';
        innerHtml += '<label class="w100 inputselect" for="subject">';
        innerHtml += '<span class="wrapper"><span class="title">Subject:</span><input class="field" id="sendmail_subject" name="sendmail_subject" type="text"></span>';
        innerHtml += '</label><div class="cl"></div>';
        innerHtml += '<label class="w100 inputselect" for="message">';
        innerHtml += '<span class="wrapper"><span class="title">Personal Message:</span><textarea class="field" id="sendmail_body" name="sendmail_body" rows="4"></textarea></span>';
        innerHtml += '</label><div class="cl"></div></fieldset>';
        innerHtml += '</div><div id="captcha">&nbsp;</div>';
        innerHtml += '<input type="submit" name="submitBtn" value="Send" class="btnG send"/> <input type="reset" name="resetBtn" value="Clear" class="btnG send"/><br/></form>';

        quizTabShare.innerHTML = innerHtml;
        quizEndCard.appendChild(quizTabShare);
        var sm = new AOLSendMail("sendmail_form");
        sm.onError(function( error )
        {
            if( error.error != "CAPTCHA_RESPONSE" )
            {
                alert("There was a problem sending email. Please try again later")
            }
            else
            {
                alert("Please try typing in the correct letters that appear in the image")
            }
        });
        sm.onMessageSent(function()
        {
            quizTabShare.innerHTML = "Message sent successfully."
        })
        sm.setDataToAppend("<br><br><a href=\"" + quiz.url + "\">" + quiz.title + "</a>")
    }

    function showTabSnag( event )
    {
        stopDefaultEvent(event ? event : window.event);
        var quizEndCard = _$("aolQuizEndCard");
        while( quizEndCard.childNodes.length >= 2 )
        {
            quizEndCard.removeChild(quizEndCard.lastChild);
        }

        var tabs = quizEndCard.firstChild.firstChild.nextSibling.childNodes;
        for( var i = 0; i < tabs.length; i++ )
        {
            tabs[i].className = "";
        }

        tabs[3].className = "on"

        var quizTabSnag = document.createElement("div");
        quizTabSnag.setAttribute("id", "aolQuizTabSnag");

        var snagHtml = '<form class="dm_form"><div class="form_wrapper">';
        snagHtml += '<fieldset><label class="w100 inputselect" for="message"><span class="wrapper"><span class="title">To embed tdhis quiz copy the code below and paste into your web site:</span><textarea class="field" id="message" rows="8"><div><object class="43423432432"><font style=">.dasdsas".....</textarea></span></label><div class="cl"></div></fieldset>';
        snagHtml += '</div></form>';
        snagHtml += '<a href="#" class="btnG copy">Copy</a>';

        quizTabSnag.innerHTML = snagHtml;
        quizEndCard.appendChild(quizTabSnag)
    }

    function showTabInfo()
    {
        var quizEndCard = _$("aolQuizEndCard");
        // Remove all children before updating to next question
        while( quizEndCard.childNodes.length >= 2 )
        {
            quizEndCard.removeChild(quizEndCard.lastChild);
        }
        var tabs = quizEndCard.firstChild.firstChild.nextSibling.childNodes;

        for( var i = 0; i < tabs.length; i++ )
        {
            tabs[i].className = "";
        }
        tabs[3].className = "on";

        var quizTabInfo = document.createElement("div");
        quizTabInfo.setAttribute("id", "aolQuizTabInfo");

        var quizTabInfoIntro = document.createElement("div");
        quizTabInfoIntro.setAttribute("id", "aolQuizTabInfoIntro");
        quizTabInfoIntro.innerHTML = '<span class="bold">About This Quiz</span><br>' + quiz.getDescription();

        var quizTabInfoMImg = document.createElement("div");
        quizTabInfoMImg.className = "mImg";
        quizTabInfoMImg.innerHTML = '<img src="' + quiz.authorPhoto + '" alt="User Photo" width="60" height="60" border="0">';

        var quizUpdatedOn = document.createElement("div");
        quizUpdatedOn.className = "mInfo";
        quizUpdatedOn.innerHTML = '<span class="mName">Quiz Updated On: </span>' + quiz.updatedOn;

        var timesTaken = document.createElement("div");
        timesTaken.className = "mInfo";
        timesTaken.innerHTML = '<span class="mName">Times This Quiz Has Been Taken: </span>' + quiz.takenCount;

        var difficulty = document.createElement("div");
        difficulty.className = "mInfo";
        difficulty.innerHTML = '<span class="mName">Average Difficulty: </span>' + quiz.difficulty;

        var highestScore = document.createElement("div");
        highestScore.className = "mInfo";
        highestScore.innerHTML = '<span class="mName">Highest Score: </span>' + quiz.highestScore + ' by ' + quiz.highestUser;

        var quizTabInfoMInfo = document.createElement("div");
        quizTabInfoMInfo.className = "mInfo";

        var quizTabInfoMember = document.createElement("div");
        quizTabInfoMember.innerHTML = '<span class="mName"><a href="/user-quizzes/quizzard/' + quiz.author + '">' + quiz.author + '</a></span>';
        quizTabInfoMInfo.appendChild(quizTabInfoMember);

        var quizTabInfoStat1 = document.createElement("div");
        quizTabInfoStat1.className = "mInfo";
        quizTabInfoStat1.innerHTML = '<span class="mName">Total Quizzes Made: </span>' + quiz.userStat.quizzesMade;
        quizTabInfoMInfo.appendChild(quizTabInfoStat1);

        var quizTabInfoStat2 = document.createElement("div");
        quizTabInfoStat2.className = "mInfo";
        quizTabInfoStat2.innerHTML = '<span class="mName">Total Quizzes Taken: </span>' + quiz.userStat.quizzesTaken;
        quizTabInfoMInfo.appendChild(quizTabInfoStat2);


        var aboutthisquizzard = document.createElement("div");
        aboutthisquizzard.innerHTML = '<br/><br/><span class="bold">About This Quizzard</span>';


        var clearDiv = document.createElement("div");
        clearDiv.className = "cl";
        quizTabInfo.appendChild(quizTabInfoIntro);
        quizTabInfo.appendChild(quizUpdatedOn);
        quizTabInfo.appendChild(timesTaken);
        quizTabInfo.appendChild(difficulty);
        quizTabInfo.appendChild(highestScore);
        quizTabInfo.appendChild(clearDiv);
        quizTabInfo.appendChild(aboutthisquizzard);
        quizTabInfo.appendChild(quizTabInfoMImg);
        quizTabInfo.appendChild(quizTabInfoMInfo);
        quizTabInfo.appendChild(clearDiv);
        quizEndCard.appendChild(quizTabInfo);
    }

    function updateQuestion( event )
    {
        stopDefaultEvent(event ? event : window.event);
        if( status )
        {
            showTabNavs();
            showTabScore();
            return;
        }

        var questionContainer = _$("aolQuestionContainer");
        questionContainer.style.display = "";

        var quizEndCard = _$("aolQuizEndCard");
        quizEndCard.style.display = "none";

        var quizBot = _$("aolQuizBot");


        // Remove all children before updating to next question
        while( questionContainer.hasChildNodes() )
        {
            questionContainer.removeChild(questionContainer.lastChild);
        }

        var btnMenu = _$("aolQuizBtnMenu");
        if( btnMenu != null )
        {
            btnMenu.className="btnG menu";
            btnMenu.style.display = "";
        }

        var currentQuestion = quiz.getCurrentQuestion();
        // Clear div
        var clearDiv = document.createElement("div");
        clearDiv.className = "cl";


        // Question div
        var question = document.createElement("div");
        question.setAttribute("id", "question");

        //Question Image
        var questionImage = null;

        if( currentQuestion.image )
        {
            question.style.width = "290px";
            questionImage = document.createElement("div");
            questionImage.setAttribute("id", "quizImgArea");
            questionImage.innerHTML = '<div class="quizImg"><img src="' + currentQuestion.image + '" alt="Image Question" border="0"/><br /></div>';
            //<div class="imgCredit">Photo Credit Here</div>'

        }

        // Question count
        var questionIndexSec = document.createElement("div");
        questionIndexSec.setAttribute("id", "aolQuestionIndexSec");
        questionIndexSec.innerHTML = "Question " + (quiz.getCurrentIndex() + 1) + " ";

        var questionIndex = document.createElement("span");
        questionIndex.setAttribute("id", "aolQuestionIndex");


        // Question total
        var questionTotal = document.createElement("span");
        questionTotal.setAttribute("id", "aolQuestionTotal");
        questionTotal.innerHTML = "of " + quiz.getTotalQuestions();

        //Append containers and children
        questionIndexSec.appendChild(questionIndex);
        questionIndexSec.appendChild(questionTotal);
        question.appendChild(questionIndexSec);

        if( questionImage )
        {
            questionContainer.appendChild(questionImage);
        }

        questionContainer.appendChild(question);
        questionContainer.appendChild(clearDiv);

        // Question text
        var questionText = document.createElement("h4");
        questionText.innerHTML = currentQuestion.text;
        question.appendChild(questionText);
        if( currentQuestion.type == "MULTIPLE" )
        {
            // Add question answers
            for( var key in currentQuestion.answers )
            {
                var answerItem = document.createElement("a");
                answerItem.setAttribute("href", "#");
                answerItem.setAttribute("id", currentQuestion.answers[key].id);
                answerItem.setAttribute("name", "aolQuizUserAnswer");
                answerItem.className = "awHighlight";
                var awNumber = document.createElement("span");
                awNumber.className = "number";
                awNumber.innerHTML = parseInt(key) + 1;
                var text = document.createTextNode(currentQuestion.answers[key].text);
                var awText = document.createElement("span");
                awText.className = "awText";
                awText.appendChild(text);
                addEventSimple(answerItem, "click", self.onUserAnswer);
                answerItem.appendChild(awNumber);
                answerItem.appendChild(awText);
                question.appendChild(answerItem);
            }
        }
        else if( currentQuestion.type == "BOOLEAN" )
        {
            // Add question answers
            for( var i = 1; i >= 0; i-- )
            {
                var answerItem = document.createElement("a");
                answerItem.setAttribute("href", "#");
                answerItem.setAttribute("id", i);
                answerItem.setAttribute("name", "aolQuizUserAnswer");
                answerItem.className = "awHighlight";
                var awNumber = document.createElement("span");
                awNumber.className = "number";
                var awText = document.createElement("span");
                awText.className = "awText";
                if( i == "1" )
                {
                    awNumber.innerHTML = "T";
                    awText.innerHTML = "True"
                }
                else
                {
                    awNumber.innerHTML = "F";
                    awText.innerHTML = "False"
                }
                addEventSimple(answerItem, "click", self.onUserAnswer);
                answerItem.appendChild(awNumber);
                answerItem.appendChild(awText);
                question.appendChild(answerItem);

            }
        }
        if( questionImage )
        {
            var answerLength = question.childNodes.length - 2;
            for( var i = 0; i < answerLength; i++ )
            {
                question.childNodes[i + 2].lastChild.style.width = "220px";
            }
        }

    }

    this.setLeaderboard = function( lb )
    {
        leaderboard = lb;
    }

    // Timer functions
    function startTimer()
    {
        self.startDate = new Date(new Date().getTime() + 61000);
        self.timerID = setInterval(updateTimer, 50);
    }

    function stopTimer()
    {
        clearInterval(self.timerID);
    }

    function getElapsedTime()
    {
        if( self.startDate )
        {
            var now = new Date();
            var diff = self.startDate.getTime() - now.getTime();
            if( diff < 0 )
            {
                diff = 0;
                stopTimer();
            }
            var timeElapsed = new Date();
            timeElapsed.setTime(diff);
            return timeElapsed;
        }
        else
        {
            var timeElapsed = new Date();
            timeElapsed.setTime(0);
            return timeElapsed;
        }
    }


    function updateTimer()
    {
        var timeElapsed = getElapsedTime();
        var seconds = timeElapsed.getMinutes() * 60 + timeElapsed.getSeconds();
        self.quizTimer.innerHTML = (seconds < 10 ? "0" + seconds : seconds);
    }
}
function AOLQuizLeaderboard( divId, id, startOnLoad )
{
    var quizContainer = null;
    var ajax = new AOLQuizAjax();
    var quiz = null;
    var scoreResults = null;
    var self = this;
    var status = false;
    var autoStart = startOnLoad != null ? startOnLoad : true;
    var quizId = (id != null ? id : getQueryVariable("quiz-id"));
    var timeframe = "week";
    this.forceTimeframe = false;

    if( autoStart )
    {
        addEventSimple(window, "load", init);
    }

    this.getTimeframe = function()
    {
        return timeframe;
    }

    this.show = function()
    {
        init();
    }

    this.remove = function()
    {
        while( quizContainer.childNodes.length > 0 )
        {
            quizContainer.removeChild(quizContainer.lastChild);
        }
    }

    this.refresh = function()
    {
        //self.remove();
        self.show();
    }

    this.changeTimeframe = function( newTimeframe )
    {
        timeframe = newTimeframe;
        self.refresh();
    }

    var addTimeframeEvent = function( obj, newTimeframe )
    {
        obj.leaderboard = this;
        addEventSimple(obj, "click", function( event )
        {
            stopDefaultEvent(event);
            self.forceTimeframe = true;
            leaderboard.changeTimeframe(newTimeframe);
        }
                );
    }

    function init()
    {
        loadQuizCSS();

        quizContainer = _$(divId);
        if( quizContainer )
        {
            if( quizId != null )
            {
                ajax.getLeaderboard(quizId, loadLeaderboard, timeframe);
            }
            else
            {
                ajax.getOverallLeaderboard(loadLeaderboard);
            }
        }
    }

    function loadLeaderboard( leaders )
    {
        if( !self.forceTimeframe && leaders.length == 0 && self.getTimeframe() != "all" )
        {
            if( self.getTimeframe() == "week" )
            {
                self.changeTimeframe("month");
            }
            else if( self.getTimeframe() == "month" )
            {
                self.changeTimeframe("all");
            }
        }
        else
        {
            self.remove();
            quizContainer.className = "leaderboard rightRailModule";

            var snag = document.createElement("a");
            snag.className = "snag";
            snag.setAttribute("href", "#");

            var snagImg = document.createElement("img");
            snagImg.setAttribute("src", CDN_HOST + "/images/icon_snag.gif");
            snagImg.setAttribute("alt", "snag");
            snag.appendChild(snagImg);

            /*quizContainer.appendChild(snag);*/

            var h3 = document.createElement("h3");
            if( quizId == null )
            {
                h3.innerHTML = "Overall Leader Boards";
            }
            else
            {
                h3.innerHTML = "Leader Board for this Quiz";
            }
            quizContainer.appendChild(h3);

            var nav = document.createElement("div");
            nav.className = "nav";

            var week = document.createElement("a");
            week.setAttribute("href", "#");
            if( timeframe == "week" )
            {
                week.className = "on";
            }
            week.innerHTML = "This Week";
            addTimeframeEvent(week, "week");
            nav.appendChild(week);

            var divider = document.createElement("span");
            divider.className = "divider";
            divider.innerHTML = "|";
            nav.appendChild(divider);

            var month = document.createElement("a");
            month.setAttribute("href", "#");
            if( timeframe == "month" )
            {
                month.className = "on";
            }
            month.innerHTML = "This Month";
            addTimeframeEvent(month, "month");
            nav.appendChild(month);

            divider = document.createElement("span");
            divider.className = "divider";
            divider.innerHTML = "|";
            nav.appendChild(divider);

            var time = document.createElement("a");
            time.setAttribute("href", "#");
            if( timeframe == "all" )
            {
                time.className = "on";
            }
            time.innerHTML = "All Time";
            addTimeframeEvent(time, "all");
            nav.appendChild(time);

            /*
            divider = document.createElement("span");
            divider.className =  "divider";
            divider.innerHTML = "|";
            nav.appendChild(divider);
            
            
            var challenges = document.createElement("a");
            challenges.setAttribute("href", "#");
            challenges.innerHTML = "Challenges";
            nav.appendChild(challenges);
            */

            quizContainer.appendChild(nav);

            var br = document.createElement("br");
            br.setAttribute("style", "clear: both");
            quizContainer.appendChild(br);

            if( self.getTimeframe() == "all" && leaders.length == 0 )
            {
                var emptyMessage = document.createElement("p");
                emptyMessage.className = "empty";
                emptyMessage.innerHTML = "Nobody has taken this quiz yet. Try it now for a shot at making the leaderboard!";
                quizContainer.appendChild(emptyMessage);
            }

            for( var i = 0; i < leaders.length; i++ )
            {
                var item = document.createElement("div");

                if( i == 0 )
                {
                    item.className = "item first";
                }
                else
                {
                    item.className = "item";
                }
                
                if( i % 2 == 0 ) {
                	item.className = item.className + " alt";
                }

                // rank
                var rank = document.createElement("div");
                rank.className = "rank";
                rank.innerHTML = (i + 1);
                item.appendChild(rank);

                // user image
                var userImage = document.createElement("div");
                userImage.className = "image firstOnly";

                var image = document.createElement("img");
                image.setAttribute("src", leaders[i].photo);
                image.setAttribute("alt", "User Image");
                image.setAttribute("width", "60");
                image.setAttribute("height", "60");
                userImage.appendChild(image);
                item.appendChild(userImage);

                // user info
                var user = document.createElement("div");
                user.className = "user";

                var userP = document.createElement("p");

                var userName = document.createElement("a");
                userName.setAttribute("href", "/user-quizzes/quizzard/" + leaders[i].user);
                userName.className = "name";
                userName.innerHTML = leaders[i].user;
                userP.appendChild(userName);

                br = document.createElement("div");
                br.className = "clearBlock firstOnly";
                br.innerHTML = "<!-- -->";
                userP.appendChild(br);

                var icon = document.createElement("img");
                icon.setAttribute("src", CDN_HOST + "/images/icon_aim.gif");
                icon.setAttribute("alt", "AIM");
                //userP.appendChild(icon);

                icon = document.createElement("img");
                icon.setAttribute("src", CDN_HOST + "/images/icon_onTv.gif");
                icon.setAttribute("alt", "On Television");
                //userP.appendChild(icon);

                user.appendChild(userP);

                userP2 = document.createElement("p");
                userP2.innerHTML = "Quizzes Taken: " + leaders[i].quizzesTaken;
                userP.appendChild(userP2);

                item.appendChild(user);

                var stats = document.createElement("div");
                stats.className = "stats";

                var score = document.createElement("p");
                score.innerHTML = leaders[i].formattedScore;
                stats.appendChild(score);

                var rankP = document.createElement("p");
                rankP.className = "firstOnly";
                var rankImage = document.createElement("img");
                rankImage.setAttribute("src", CDN_HOST + "/images/img_num1.gif");
                rankImage.setAttribute("alt", "Number One");
                rankP.appendChild(rankImage);

                item.appendChild(rankP);

                stats.appendChild(rankP);
                item.appendChild(stats);

                br = document.createElement("div");
                br.className = "clearBlock";
                br.innerHTML = "<!-- -->";
                item.appendChild(br);

                quizContainer.appendChild(item);

            }
        }
    }
}

function AOLQuizComments( divId, id, startOnLoad )
{

    var quiz = null;
    var scoreResults = null;
    var self = this;
    var status = false;
    var autoStart = startOnLoad != null ? startOnLoad : true;
    this.quizId = (id != null ? id : getQueryVariable("quiz-id"));
    this.ajax = new AOLQuizAjax();
    this.quizContainer = null;
    this.commentsPerPage = 24;

    // paging
    this.thisPage = 1;

    if( autoStart )
    {
        addEventSimple(window, "load", init);
    }

    this.show = function()
    {
        init();
    }

    this.remove = function()
    {
        while( self.quizContainer.childNodes.length > 0 )
        {
            self.quizContainer.removeChild(self.quizContainer.lastChild);
        }
    }

    this.refresh = function()
    {
        //self.remove();
        self.show();
    }

    this.changePage = function( pageNum )
    {
        self.thisPage = parseInt(pageNum);
        self.refresh();
    }

    function init()
    {
        loadQuizCSS();

        self.quizContainer = _$(divId);
        if( self.quizContainer )
        {
            start = ( self.thisPage - 1 ) * self.commentsPerPage;
            self.ajax.getComments(self.quizId, start, self.commentsPerPage, loadComments);
        }
    }

    function loadComments( comments )
    {
        // paging
        totalAvailable = comments.totalAvailable;
        totalPages = Math.ceil(totalAvailable / self.commentsPerPage);
        if( totalPages == 0 ) {
        	totalPages = 1;
        }
        
        startPage = Math.max(1, Math.min(totalPages - 4, self.thisPage - 2));
        endPage = Math.min(totalPages, Math.max(5, self.thisPage + 2));

        comments = comments.items;

        self.remove();

        self.quizContainer.className = "module moduleWide quizComments";

        var snag = document.createElement("a");
        snag.className = "snag";
        snag.setAttribute("href", "#addComment");
        snag.innerHTML = "Add Your Own Comments";
        addEventSimple(snag, "click", function( e )
        {
            stopDefaultEvent(e);
            var scrollTo = document.getElementById("addComment");
            if( scrollTo ) window.scroll(0, scrollTo.offsetTop);
        }
                );
        self.quizContainer.appendChild(snag);

        var h3 = document.createElement("h3");
        h3.innerHTML = "Recent Comments";
        self.quizContainer.appendChild(h3);

        for( var i = 0; i < comments.length; i++ )
        {
            var item = document.createElement("div");
            item.className = "item";

            var avatar = document.createElement("div");
            avatar.className = "avatar";

            var img = document.createElement("img");
            img.setAttribute("src", comments[i].photo);
            img.setAttribute("width", "48");
            img.setAttribute("height", "48");
            avatar.appendChild(img);

            item.appendChild(avatar);

            var content = document.createElement("div");
            content.className = "content";

            /*
            var report = document.createElement("a");
            report.setAttribute("title", "Report this!");
            report.className = "report";
            content.appendChild(report);
            */

            var username = document.createElement("b");
            username.className = "username";
            username.innerHTML = comments[i].author;
            content.appendChild(username);

            var time = document.createElement("span");
            time.className = "time";
            time.innerHTML = comments[i].timestamp;
            content.appendChild(time);

            var post = document.createElement("p");
            post.innerHTML = comments[i].text;
            content.appendChild(post);

            item.appendChild(content);

            var br = document.createElement("div");
            br.className = "clearBlock";
            br.innerHTML = "<!-- -->";
            item.appendChild(br);

            self.quizContainer.appendChild(item);
        }

        var hubPages = document.createElement("div");
        hubPages.setAttribute("id", "hubPages");

        var info = document.createElement("info");
        info.className = "info";
        info.innerHTML = "Total of " + totalAvailable + " comment(s)";
        hubPages.appendChild(info);

        var arrowRight = document.createElement("div");
        arrowRight.className = "arrow";

        if( self.thisPage != totalPages )
        {
            var link = document.createElement("a");
            link.setAttribute("href", "#");
            link.innerHTML = "Next &raquo;";

            addEventSimple(link, "click", function( e )
            {
                var target = e.target ? e.target : e.srcElement;
                stopDefaultEvent(e);

                self.changePage(parseInt(self.thisPage) + 1);
            }
                    );

            arrowRight.appendChild(link);
        }
        else
        {
            arrowRight.innerHTML = "Next &raquo;";
        }

        hubPages.appendChild(arrowRight);

        var pages = document.createElement("div");
        pages.className = "pages";

        for( var i = startPage; i <= endPage; i++ )
        {
            var link = document.createElement("a");
            link.setAttribute("href", "#");
            if( i == (self.thisPage) )
                link.className = "on";
            link.innerHTML = i;
            link.parentObj = self;
            addEventSimple(link, "click", function( e )
            {
                var target = e.target ? e.target : e.srcElement;
                stopDefaultEvent(e);

                self.changePage(parseInt(target.innerHTML));
            }
                    );
            pages.appendChild(link);
        }

        hubPages.appendChild(pages);

        var arrowLeft = document.createElement("div");
        arrowLeft.className = "arrow";

        if( self.thisPage != 1 )
        {
            var link = document.createElement("a");
            link.setAttribute("href", "#");
            link.innerHTML = "&laquo; Prev";

            addEventSimple(link, "click", function( e )
            {
                var target = e.target ? e.target : e.srcElement;
                stopDefaultEvent(e);

                self.changePage(parseInt(self.thisPage) - 1);
            }
                    );

            arrowLeft.appendChild(link);
        }
        else
        {
            arrowLeft.innerHTML = "&laquo; Prev";
        }

        hubPages.appendChild(arrowLeft);

        var br = document.createElement("div");
        br.className = "clearBlock";
        br.innerHTML = "<!-- -->";
        hubPages.appendChild(br);

        self.quizContainer.appendChild(hubPages);

        var post = document.createElement("div");
        post.className = "post";

        var anchor = document.createElement("a");
        anchor.setAttribute("id", "addComment");
        post.appendChild(anchor);

        var textarea = document.createElement("textarea");
        textarea.setAttribute("title", "Type your own comment here");
        textarea.setAttribute("rows", 4);
        textarea.setAttribute("cols", 75);
        textarea.setAttribute("id", "commentTextarea");
        addInputDefaultHandlers(textarea);
        post.appendChild(textarea);

        self.quizContainer.appendChild(post);

        var notes = document.createElement("div");
        notes.className = "notes";

        var clear = document.createElement("a");
        clear.className = "button";
        clear.setAttribute("href", "#");
        clear.innerHTML = "Clear";
        clear.textarea = textarea;
        addEventSimple(clear, "click", function( e )
        {
            var target = e.target ? e.target : e.srcElement;
            stopDefaultEvent(e);
            target.textarea.value = '';
        });

        notes.appendChild(clear);

        var add = document.createElement("a");
        add.className = "button";
        add.setAttribute("href", "#");
        add.innerHTML = "Add";
        addEventSimple(add, "click", self.addCommentHandler);
        notes.appendChild(add);

        var errorMessage = document.createElement("span");
        errorMessage.className = "errorMessage";
        errorMessage.setAttribute("id", "quizCommentsError");
        notes.appendChild(errorMessage);

        var tips = document.createElement("a");
        tips.setAttribute("href", "#");
        tips.innerHTML = "Tips on commenting";
        addEventSimple(tips, "mouseover", function( e )
        {
            stopDefaultEvent(e);
            _$("commentTips").style.display = "block";
        }
                );
        addEventSimple(tips, "mouseout", function( e )
        {
            stopDefaultEvent(e);
            _$("commentTips").style.display = "none";
        }
                );
        notes.appendChild(tips);

        var tipBlock = document.createElement("div");
        tipBlock.setAttribute("id", "commentTips");
        tipBlock.className = "tipBlock";
        tipBlock.innerHTML = "<p>- Enter your comments as plain text &mdash; the input form will remember line breaks, but will remove any html formatting to keep all comments uniform.</p><p>-Play nice, and be respectful of other people's comments &mdash; there are many different types of people and opinions in our community!</p>";
        notes.appendChild(tipBlock);

        var br = document.createElement("br");
        notes.appendChild(br);

        /*var characters = document.createElement("span");
        characters.innerHTML = "1000 characters maximum";
        notes.appendChild(characters);*/

        var br = document.createElement("br");
        br.setAttribute("style", "clear: both");
        notes.appendChild(br);

        self.quizContainer.appendChild(notes);
    }

    this.addCommentHandler = function( e )
    {
        stopDefaultEvent(e);
        if( _$("commentTextarea").value != _$("commentTextarea").title )
        {
            self.ajax.addComment(self.quizId, '', _$("commentTextarea").value, self.addCommentCallback);
        }
    }

    this.addCommentCallback = function( comments )
    {
        if( comments.hasError )
        {
            _$("quizCommentsError").innerHTML = comments.message;
        }
        else
        {
            loadComments(comments);
        }
    }
}

function AOLQuizScoreAnimator( element, val1, val2, val3, correct )
{
    setTimeout(function ()
    {
        element.innerHTML = val1;
        element.style.backgroundPosition = correct ? "0 -1588px" : "0 -1546px"
        setTimeout(function ()
        {
            element.innerHTML = val2;
            element.style.backgroundPosition = correct ? "0 -1588px" : "0 -1546px"
            setTimeout(function ()
            {
                element.innerHTML = val3;
                element.style.backgroundPosition = "0 -1502px";
            }, 1500);
        }, 1500);
    }, 0);
}

function AOLQuizRating( divId, quizObj )
{
    var self = this;
    var status = false;
    this.ajax = new AOLQuizAjax();
    this.ratingContainer = null;
    this.defaultRating = 0;
    this.userRating = -1;
    quizObj.addQuizLoadedCallback(function( quiz )
    {
        init();
    })


    function init()
    {
        self.ratingContainer = _$(divId);
        loadQuizCSS();

        // create elements
        var desc = document.createElement("b");
        desc.setAttribute("id", "rating-desc");
        desc.innerHTML = "AVG User Rating";
        self.ratingContainer.appendChild(desc);

        var ul = document.createElement("ul");
        ul.className = "rating";
        for( var i = 0; i < 5; i++ )
        {
            var li = document.createElement("li");

            var star = document.createElement("a");
            star.setAttribute("href", "#");
            star.setAttribute("id", "rate-" + (i + 1));

            // add events
            addEventSimple(star, "mouseover", self.rateHover);
            addEventSimple(star, "mouseout", self.rateOut);
            addEventSimple(star, "click", self.rateStar);

            li.appendChild(star);

            ul.appendChild(li);
        }
        self.ratingContainer.appendChild(ul);

        var error = document.createElement("b");
        error.setAttribute("id", "rating-error");
        error.className = "error";
        self.ratingContainer.appendChild(error);

        // load needed info
        self.ajax.getRatingForUser(quizObj.getQuiz().id, self.getRatingCallback);
        self.setDefaultRating(self.convertRating(quizObj.getQuiz().rating));

        // reset rating
        self.rateOut();
    }

    this.convertRating = function( score )
    {
        return Math.ceil(score >= 20 ? score / 20 : score);
    }

    this.getRatingCallback = function( rating )
    {
        if( !rating.hasError && rating.rating > -1 )
        {
            self.setUserRating(self.convertRating(rating.rating));
        }
    }

    this.getLevelFromId = function( id )
    {
        return parseInt(id.substring(5, 6));
    }

    this.rateHover = function( e )
    {
        var target = e.target ? e.target : e.srcElement;
        var level = self.getLevelFromId(target.id);

        if( self.userRating == -1 )
        {
            _$("rating-desc").innerHTML = "Choose Your Rating";

            for( i = 1; i <= 5; i++ )
            {
                if( i <= level )
                {
                    _$("rate-" + i).className = "ratingHover";
                }
                else
                {
                    _$("rate-" + i).className = "";
                }
            }
        }
    }

    this.rateOut = function()
    {
        if( self.userRating == -1 )
        {
            _$("rating-desc").innerHTML = "AVG User Rating";

            for( i = 1; i <= 5; i++ )
            {
                if( i <= self.defaultRating )
                {
                    _$("rate-" + i).className = "ratingDefault";
                }
                else
                {
                    _$("rate-" + i).className = "";
                }
            }
        }
    }

    this.rateStar = function( e )
    {
        stopDefaultEvent(e);
        var target = e.target ? e.target : e.srcElement;

        _$("rating-error").innerHTML = "";
        var _rating = self.getLevelFromId(target.id);

        if( self.userRating == -1 )
        {
            self.setUserRating(_rating);

            self.ajax.addRating(quizObj.getQuiz().id, _rating, self.addRatingCallback);
            //makeRequest( "?item=" + item + "&itemId=" + itemId + "&rating=" + _rating );
        }
    }

    this.addRatingCallback = function( rating )
    {
        if( rating.hasError )
        {
            _$("rating-error").innerHTML = "Please login to rate quizzes.";
            self.userRating = -1;
            self.rateOut();
        }
    }

    this.setDefaultRating = function( _rating )
    {
        self.defaultRating = _rating;
    }

    this.setUserRating = function( _rating )
    {
        self.userRating = _rating;
        _$("rating-desc").innerHTML = "Your Rating";

        for( i = 1; i <= 5; i++ )
        {
            if( i <= self.userRating )
            {
                _$("rate-" + i).className = "ratingHover";
            }
            else
            {
                _$("rate-" + i).className = "";
            }
        }
    }

}


// Helper functions
if( typeof addInputDefaultHandlers != 'function' )
{
    var addInputDefaultHandlers = function( input )
    {
        // setup default
        if( input.value.replace(/^\s+|\s+_$/g, "") == "" )
        {
            input.value = input.title;
        }

        // onfocus, remove default value
        addEventSimple(input, "focus", function( evt )
        {
            var target = evt.target ? evt.target : evt.srcElement;

            if( target.value == target.title )
            {
                target.value = "";
            }
        }
                );

        // onblur, put back default value
        addEventSimple(input, "blur", function( evt )
        {
            var target = evt.target ? evt.target : evt.srcElement;

            if( target.value.replace(/^\s+|\s+_$/g, "") == "" )
            {
                target.value = target.title;
            }
        }
                );
    }
}


if( typeof addEventSimple != 'function' )
{
    var addEventSimple = function( obj, evt, fn )
    {
        if( obj.addEventListener )
        {
            obj.addEventListener(evt, fn, false);
        }
        else if( obj.attachEvent )
        {
            obj.attachEvent("on" + evt, fn);
        }
    }
}


if( typeof removeEventSimple != 'function' )
{
    var removeEventSimple = function( obj, evt, fn )
    {
        if( obj.removeEventListener )
        {
            obj.removeEventListener(evt, fn, false);
        }
        else if( obj.detachEvent )
        {
            obj.detachEvent("on" + evt, fn);
        }
        if( evt == "click" && obj.href != "javascript:void(0)" )
        {
            obj.setAttribute("href", "javascript:void(0)")
        }
    }
}
if( typeof stopDefaultEvent != 'function' )
{
    var stopDefaultEvent = function( event )
    {
        if( event )
        {
            if( event.preventDefault )
            {
                event.preventDefault();
                event.stopPropagation();
            }
            else
            {
                event.returnValue = false;
                event.cancelBubble = true;
            }
        }
    }
}

if( typeof _$ != 'function' )
{
    var _$ = function( id )
    {
        if( typeof id == "string" )
        {
            return document.getElementById(id);
        }
        else
        {
            return id;
        }
    }
}

if( typeof getQueryVariable != 'function' )
{
    var getQueryVariable = function( variable )
    {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for( var i = 0; i < vars.length; i++ )
        {
            var pair = vars[i].split("=");
            if( pair[0] == variable )
            {
                return pair[1];
            }
        }

        return "";
    }
}

if( typeof loadQuizCSS != 'function' )
{
    var loadQuizCSS = function()
    {
        // load the css
        var headTag = document.getElementsByTagName('head')[0];
        var links = headTag.getElementsByTagName("link");
        var hasLayout = false;
        var hasSkin = false;
        var hasCss = false;

        for( var i = 0; i < links.length; i++ )
        {
            if( links[i].href.indexOf("quiz_module_layout.css") >= 0 )
            {
                hasLayout = true;
            }
            if( links[i].href.indexOf("quiz_module_skin.css") >= 0 )
            {
                hasSkin = true;
            }

            if( links[i].href.indexOf("quiz_module.css") >= 0 )
            {
                hasCss = true;
            }
        }

        /*if( !hasLayout )
        {
            var layoutCSS = document.createElement("link");
            layoutCSS.href = CDN_HOST + "/css/quiz_module_layout.css";
            layoutCSS.type = "text/css";
            layoutCSS.rel = "stylesheet";
            layoutCSS.rev = "stylesheet";
            headTag.appendChild(layoutCSS);
        }

        if( !hasSkin )
        {
            var skinCSS = document.createElement("link");
            skinCSS.href = CDN_HOST + "/css/quiz_module_skin.css";
            skinCSS.type = "text/css";
            skinCSS.rel = "stylesheet";
            skinCSS.rev = "stylesheet";
            headTag.appendChild(skinCSS);
        }*/

        if( !hasCss )
        {
            var skinCSS = document.createElement("link");
            skinCSS.href = CDN_HOST + "/css/quiz_module.css";
            skinCSS.type = "text/css";
            skinCSS.rel = "stylesheet";
            skinCSS.rev = "stylesheet";
            headTag.appendChild(skinCSS);
        }
    }
}
