﻿// global namespaces
var Sam = Sam || {};
Sam.UI = Sam.UI || {};

var correctAnswer;
var questionData;
var userId;

var quickPollMainDiv = '#quickPoll';
var quickPollTitleId = '#quickPollTitle';
var quickPollTextId = '#quickPollText';
var quickPollAnswersId = '#quickPollAnswers';
var quickPollResultsId = '#quickPollResult';
var quickPollReferencesId = '#quickPollReferences';
var quickPollButtonId = '#quickPollButton';
var quickPollButtonClass = '.btnQuickPoll';

if (!Array.indexOf) {
    Array.prototype.indexOf = function (obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

Sam.UI.quickpoll = {

    siteId: "samsca",
    serviceUrl: "/Services/QuickPollService.svc/GetQuestionJson",
    answerUrl: "/Services/QuickPollService.svc/RecordUserAnswerJson",

    // initializes the quickpoll
    init: function () {
        Sam.UI.quickpoll.getUserId();
        Sam.UI.quickpoll.getRandomQuestion();
        $(quickPollButtonClass).die();
        $(quickPollButtonClass).live('click', Sam.UI.quickpoll.submitAnswer);
    },

    // gets the specified question from its id
    getQuestion: function (questionId) {
        $.ajax({
            url: Sam.UI.quickpoll.serviceUrl,
            dataType: 'json',
            data: { 'siteId': Sam.UI.quickpoll.siteId, 'questionId': questionId },
            success: function (data) {
                Sam.UI.quickpoll.addQuestionToCookie('seen', data.d.Id);
                questionData = data;
                Sam.UI.quickpoll.setQuestionContent(data);
            },
            error: function () { Sam.UI.quickpoll.hideQuickPolls(); }
        });
    },

    // gets a random question
    getRandomQuestion: function () {
        $.ajax({
            url: Sam.UI.quickpoll.serviceUrl,
            dataType: 'json',
            data: { 'siteId': Sam.UI.quickpoll.siteId },
            cache: false,
            success: function (data) {
                questionData = data;
                if (Sam.UI.quickpoll.idExistsInCookie('seen', data.d.Id)) {
                    Sam.UI.quickpoll.getUnseenQuestion();
                } else {
                    Sam.UI.quickpoll.addQuestionToCookie('seen', data.d.Id);
                    Sam.UI.quickpoll.setQuestionContent(data);
                }
            },
            error: function () { Sam.UI.quickpoll.hideQuickPolls(); }
        });
    },

    setQuestionContent: function (data) {
        Sam.UI.quickpoll.setTitle(data.d.Title);
        Sam.UI.quickpoll.setText(data.d.Text);
        Sam.UI.quickpoll.setAnswers(data.d.Answers);
        Sam.UI.quickpoll.setSubmitButton();
        Sam.UI.quickpoll.setTracking(data.d.Id, 'Show');

        //hack alert!  they want to show references at the question level if the question has a reference number in it.
        //so, since there's nothing in the service telling me so, i'm just looking for the sup tag.
        if (data.d.Text.indexOf('<sup>') > -1) {
            Sam.UI.quickpoll.setReferences();
            $(quickPollReferencesId).show();
        }
    },

    setTitle: function (title) {
        $(quickPollTitleId).html('<h3>' + title + '</h3>');
    },

    setText: function (text) {
        $(quickPollTextId).html('<p>' + text + '</p>');
    },

    setAnswers: function (questions) {
        $(quickPollAnswersId).html('');
        $.each(questions, function (index, value) {
            $(quickPollAnswersId).append('<span><input type="radio" name="quickPollAnswers" id = "' + value.Id + '" value="' + value.Text + '"> ' + value.Text + '</span>');
            if (value.IsCorrect) {
                correctAnswer = value.Text;
            }
        });
    },

    setSubmitButton: function () {
        $(quickPollButtonId).html('<input type="image" name="submit" id="submit" src="/images/btn_submit_quickpolls.png" class="btnQuickPoll"/>');
    },

    setTracking: function (questionId, type) {
        //example:  _gaq.push(['_trackEvent', 'QuickPoll', '/page_name', 'Q1_Show']);
        _gaq.push(['_trackEvent', 'QuickPoll', window.location.pathname, 'Q' + questionId + '_' + type]); // ga tag
    },

    // submits an answer
    submitAnswer: function () {
        var answerId = $('input[name=quickPollAnswers]:checked').attr('id');
        Sam.UI.quickpoll.addQuestionToCookie('answered', questionData.d.Id);
        $.ajax({
            url: Sam.UI.quickpoll.answerUrl,
            dataType: 'json',
            data: { 'userId': userId, 'answerId': answerId }
        });
        Sam.UI.quickpoll.hideAnswers();
        Sam.UI.quickpoll.showResults();
        Sam.UI.quickpoll.setResult();
        Sam.UI.quickpoll.setReferences();
        Sam.UI.quickpoll.setResetButton();
        Sam.UI.quickpoll.setTracking(questionData.d.Id, 'Answer');
        $(quickPollButtonClass).die();
        $(quickPollButtonClass).live('click', Sam.UI.quickpoll.getNewQuestion);
    },

    hideAnswers: function () {
        $(quickPollAnswersId).hide();
    },

    showAnswers: function () {
        $(quickPollAnswersId).show();
    },

    //in case of catastrophic failure...
    hideQuickPolls: function () {
        $(quickPollMainDiv).hide();
    },

    setResult: function () {
        $(quickPollResultsId).html('');
        var selectedAnswer = $('input[name=quickPollAnswers]:checked').val();
        var references = '';
        if (questionData.d.References.length > 1) {
            $.each(questionData.d.References, function (index, value) {
                if (index != 0) {
                    references = references + ',' + value.Id;
                } else {
                    references = value.Id;
                }
            });
        }
        if (selectedAnswer == correctAnswer) {
            $(quickPollResultsId).append('<div class="resultLeft"><img src="/images/quick_poll_correct.png" alt="Correct" /></div>');
            if (questionData.d.References.length > 1) {
                $(quickPollResultsId).append('<div class="resultRight correct"><h2>Correct</h2><p>Correct answer is: <strong>' + correctAnswer + '</strong><sup>' + references + '</sup><br /><a href="' + questionData.d.RelatedLink + '">Learn More</a> &raquo;</p></div>');
            } else {
                $(quickPollResultsId).append('<div class="resultRight correct"><h2>Correct</h2><p>Correct answer is: <strong>' + correctAnswer + '</strong><br /><a href="' + questionData.d.RelatedLink + '">Learn More</a> &raquo;</p></div>');
            }
        } else {
            if (questionData.d.References.length > 1) {
                $(quickPollResultsId).append('<div class="resultRight incorrect"><h2>Incorrect</h2><p>Correct answer is: <strong>' + correctAnswer + '</strong><sup>' + references + '</sup><br /><a href="' + questionData.d.RelatedLink + '">Learn More</a> &raquo;</p></div>');
            } else {
                $(quickPollResultsId).append('<div class="resultRight incorrect"><h2>Incorrect</h2><p>Correct answer is: <strong>' + correctAnswer + '</strong><br /><a href="' + questionData.d.RelatedLink + '">Learn More</a> &raquo;</p></div>');
            }
        }
    },

    setReferences: function () {
        $(quickPollReferencesId).html('');
        if (questionData.d.References.length > 1) {
            $(quickPollReferencesId).append('<span class="hdr">References</span>');
        }
        else {
            $(quickPollReferencesId).append('<span class="hdr">Reference</span>');
        }

        $(quickPollReferencesId).append('</span>: ');

        $.each(questionData.d.References, function (index, value) {
            if (questionData.d.References.length > 1) {
                $(quickPollReferencesId).append('<span class="hdr">' + value.Id + '.</span> ' + value.Text + ' ');
            } else {
                $(quickPollReferencesId).append(value.Text);
            }
        });
    },

    setResetButton: function () {
        $(quickPollButtonId).html('<input type="image" name="" id="submit" src="/images/btn_shownext_quickpolls.png" class="btnQuickPoll" />');
    },

    getNewQuestion: function () {
        Sam.UI.quickpoll.hideResults();
        Sam.UI.quickpoll.showAnswers();
        Sam.UI.quickpoll.init();
        return false;
    },

    hideResults: function () {
        $(quickPollResultsId).hide();
        $(quickPollReferencesId).hide();
    },

    showResults: function () {
        $(quickPollResultsId).show();
        $(quickPollReferencesId).show();
    },

    addQuestionToCookie: function (cookieName, questionId) {
        var currentCookieValue = $.cookie(cookieName);
        var newCookieValue;
        if (currentCookieValue) {
            newCookieValue = currentCookieValue + ',' + questionId;
        } else {
            newCookieValue = questionId;
        }
        $.cookie(cookieName, newCookieValue);
    },

    idExistsInCookie: function (cookieName, questionId) {
        var cookieValue = $.cookie(cookieName);
        if (cookieValue) {
            var cookieIds = cookieValue.split(',');
            return ($.inArray(questionId, cookieIds) != -1);
            //return (cookieIds.indexOf(questionId) != -1);
        } else {
            return false;
        }
    },

    //gets a question that has not been seen yet by the user
    getUnseenQuestion: function () {
        var seenQuestions = $.cookie('seen');
        if (seenQuestions) {
            var seenArray = seenQuestions.split(',');

            var unseenQuestions = Sam.UI.quickpoll.getDifference(questionData.d.AllQuestionIds, seenArray);

            if (unseenQuestions.length == 0) {
                Sam.UI.quickpoll.getUnansweredQuestion();
            } else {
                Sam.UI.quickpoll.getQuestion(Sam.UI.quickpoll.getRandomArrayItem(unseenQuestions));
            }
        }
        else {
            //i'm not sure if this can happen, but if it does, start over.
            Sam.UI.quickpoll.clearAllCookies();
            Sam.UI.quickpoll.init();
        }
    },

    //gets a question that has not been answered by the user.
    //by rule, we won't get here until all the questions have been SEEN first.
    getUnansweredQuestion: function () {
        var answeredQuestions = $.cookie('answered');
        if (answeredQuestions) {
            var answeredArray = answeredQuestions.split(',');

            var unansweredQuestions = Sam.UI.quickpoll.getDifference(questionData.d.AllQuestionIds, answeredArray);

            if (unansweredQuestions.length == 0) {
                //all questions have been seen and answered, start over
                Sam.UI.quickpoll.clearAllCookies();
                Sam.UI.quickpoll.init();
            } else {
                //if we're here in this method, the user has already seen all questions.
                //the requirement now is for to user to see all the unanswered questions again, before seeing any one unanswered question repeated.
                //so, to help that along, once here, we'll constantly match the SEEN questions with the ANSWERED questions.
                $.cookie('seen', answeredQuestions);
                Sam.UI.quickpoll.getQuestion(Sam.UI.quickpoll.getRandomArrayItem(unansweredQuestions));
            }
        }
        else {
            //this will happen if you've SEEN every question, but never answered any.
            //so, time to start over.
            Sam.UI.quickpoll.clearAllCookies();
            Sam.UI.quickpoll.init();
        }
    },

    getDifference: function (superset, subset) {
        var difference = [];

        if (subset.length == superset.length) {
            // do nothing
        } else {
            $.each(superset, function (index, value) {
                if ($.inArray(value, subset) == -1) {
                    difference.push(value);
                }
            });
        }

        return difference;
    },

    clearAllCookies: function () {
        $.cookie('seen', null);
        $.cookie('answered', null);
    },

    getRandomArrayItem: function (array) {
        var from = 0;
        var to = array.length - 1;
        var randomIndex = Math.floor(Math.random() * (to - from + 1) + from);
        return array[randomIndex];
    },

    getUserId: function () {
        if ($.cookie('samscaUserId') == null) {
            userId = Sam.UI.quickpoll.uid();
            $.cookie('samscaUserId', userId);
        } else {
            userId = $.cookie('samscaUserId');
        }
    },

    uid: function () {
        var result = '';
        for (var i = 0; i < 32; i++)
            result += Math.floor(Math.random() * 16).toString(16).toUpperCase();
        return result;
    }
};
