﻿function ProcessVote(
    gameID,
    userID,
    radioButtonIds,
    tallyLabelIds,
    voteButtonID,
    voteImg,
    votingImg,
    voteAgainButtonID,
    imageIds,
    addtlControlsToHideIfGameClosed,
    winnerLabelIds,
    winnerCSS,
    breakAfterScore)
{
    //alert("In ProcessVote and imageIds = " + imageIds);

    //alert(winnerLabelIds);

    //Get the selected radio button
    var selectedRadioButton = GetSelectedRadioButton(radioButtonIds);

    //If a radio button was selected, process a vote for the selected contestant
    if (selectedRadioButton != null)
    {
        //alert("Got selected button");

        //Set vote button image to the VOTING image
        //$("#" + voteButtonID).attr("src", votingImg);
        UpdateImage(voteButtonID, votingImg);
        $("#" + voteButtonID).attr('disabled', 'disabled');

        //Submit a vote for the selected contestant. This in turn will call another function, which will call
        //another, etc. I don't like this approach, but don't have time to figure out a way to do it which will
        //keep function calls 1 level deep.
        /*
        SubmitVote(
        gameID,
        userID,
        radioButtonIds,
        tallyLabelIds,
        selectedRadioButton.value,
        voteButtonID,
        voteImg,
        voteAgainButtonID,
        imageIds,
        addtlControlsToHideIfGameClosed,
        winnerLabelIds,
        winnerCSS,
        breakAfterScore);
        */
        //Need to do it this way so the VOTING button will appear right away in IE
        //alert('yo');
        setTimeout("SubmitVote(" + gameID + ",'" + userID + "','" + radioButtonIds + "','" + tallyLabelIds + "','" + selectedRadioButton.value + "','" + voteButtonID + "','" + voteImg + "','" + voteAgainButtonID + "','" + imageIds + "'," + (addtlControlsToHideIfGameClosed != null ? "'" + addtlControlsToHideIfGameClosed + "'" : "null") + ", " + (winnerLabelIds != null ? "'" + winnerLabelIds + "'" : "null") + ", " + (winnerCSS != null ? "'" + winnerCSS + "'" : "null") + ", " + breakAfterScore + ")", 100);
    }
}


function GetSelectedRadioButton(radioButtonIds)
{
    if ($(radioButtonIds).filter(":checked").size() > 0)
        return $(radioButtonIds).filter(":checked").get(0);
    else
        return null;
}


function SubmitVote(
    gameID,
    userID,
    radioButtonIds,
    tallyLabelIds,
    selectedContestantIdentifier,
    voteButtonID,
    voteImg,
    voteAgainButtonID,
    imageIDs,
    addtlControlsToHideIfGameClosed,
    winnerLabelIds,
    winnerCSS,
    breakAfterScore) 
    {

    //Call AJAX function to submit vote.
    //On Success, show results and VOTE AGAIN button.
    //On Error, reset voting controls to allow for new vote
    //alert('SubmitVote - Selected Contestant = ' + selectedContestantIdentifier);
    //alert('hi');
    $.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: "AJAXServices/InteractivityService.svc/AddSubmittal",
                data: '{ "Identifier": "' + selectedContestantIdentifier + '", "UserId": "' + userID + '", "Text": "", "ImageId": "", "SubmitterURI": "" }',
                processData: true,
                async: true
            });

    if (tallyLabelIds != null)
    {
        /*
        GetResult(
        gameID,
        radioButtonIds,
        tallyLabelIds,
        voteButtonID,
        voteAgainButtonID,
        imageIDs,
        addtlControlsToHideIfGameClosed,
        winnerLabelIds,
        winnerCSS,
        breakAfterScore);
        */

        //12/29/2009 - Per Stu, introduce a brief pause here
        setTimeout("GetResult(" + gameID + ", " +
                    "'" + radioButtonIds + "', " +
                    (tallyLabelIds != null ? "'" + tallyLabelIds + "'" : "null") + ", " +
                    "'" + voteButtonID + "', " +
                    "'" + voteAgainButtonID + "', " +
                    (imageIDs != null ? "'" + imageIDs + "'" : "null") + ", " +
                    (addtlControlsToHideIfGameClosed != null ? "'" + addtlControlsToHideIfGameClosed + "'" : "null") + ", " +
                    (winnerLabelIds != null ? "'" + winnerLabelIds + "'" : "null") + ", " +
                    (winnerCSS != null ? "'" + winnerCSS + "'" : "null") + ", " +
                    breakAfterScore + ")", 100);
    }
    else
        UpdateVotingControls(
            gameID,
            null,
            radioButtonIds,
            tallyLabelIds,
            voteButtonID,
            voteAgainButtonID,
            imageIDs,
            addtlControlsToHideIfGameClosed,
            winnerLabelIds,
            winnerCSS,
            breakAfterScore);
}


function ResetVotingControls(radioButtonIds, tallyLabelIds, voteButtonID, voteImg, voteAgainButtonID)
{
    $(radioButtonIds).css("display", "");
    $("#" + voteButtonID).attr("src", voteImg);
    $("#" + voteButtonID).css("display", "");
    $("#" + voteAgainButtonID).css("display", "none");
    $(tallyLabelIds).css("display", "none");
    $("#" + voteButtonID).attr('disabled', '');
}


function GetResult(
    gameID,
    radioButtonIds,
    tallyLabelIds,
    voteButtonID,
    voteAgainButtonID,
    imageIds,
    addtlControlsToHideIfGameClosed,
    winnerLabelIds,
    winnerCSS,
    breakAfterScore)
{
    //alert("In GetResult, imageIds = " + imageIds);

    //Original, working test code
    /*
    $.ajax
    ({
    type: "GET",
    contentType: "application/json",
    url: "TestGamesService/TestGamesService.svc/GetResult",
    processData: false,
    success: function(msg)
    {
    var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg)
    //alert("Got it! " + msgWithoutEnvelope.Contestant1Percentage);
    UpdateVotingControls(
    msgWithoutEnvelope,
    radioButtonIds,
    tallyLabelIds,
    voteButtonID,
    voteAgainButtonID,
    imageIds, 
    addtlControlsToHideIfGameClosed,
    winnerLabelIds,
    winnerCSS,
    breakAfterScore);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error Occurred! " + errorThrown); }
    });
    */

    //alert("GameID = " + gameID);

    jQuery.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: "AJAXServices/GamesService.svc/GetGameResult",
                data: '{ "GameID": "' + gameID + '" }',
                processData: true,
                async: true,
                success: function (msg) {
                    var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg)

                    //alert('Status = ' + msg.Status);
                    //alert('Status = ' + msgWithoutEnvelope.Status);
                    /*
                    for (var propertyName in msg.d) {
                        // propertyName is what you want
                        // you can get the value like this: myObject[propertyName]
                        alert(propertyName);
                    }
                    */
                    /*
                    for (var propertyName in msgWithoutEnvelope) {
                        // propertyName is what you want
                        // you can get the value like this: myObject[propertyName]
                        alert(propertyName);
                    }
                    */

                    //alert("Got it! " + msgWithoutEnvelope.Contestant1Percentage);
                    UpdateVotingControls(
                        gameID,
                        msgWithoutEnvelope,
                        radioButtonIds,
                        tallyLabelIds,
                        voteButtonID,
                        voteAgainButtonID,
                        imageIds,
                        addtlControlsToHideIfGameClosed,
                        winnerLabelIds,
                        winnerCSS,
                        breakAfterScore);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Error Occurred! " + errorThrown); }
            });

}


function UpdateVotingControls(
    gameID,
    result,
    radioButtonIds,
    tallyLabelIds,
    voteButtonID,
    voteAgainButtonID,
    imageIds,
    addtlControlsToHideIfGameClosed,
    winnerLabelIds,
    winnerCSS,
    breakAfterScore)
{
    //alert('UpdateVotingControls');
    //alert(voteAgainButtonID);
    //alert(result.toString());
    //alert(result.Status);
    //alert(result.Contestants.length);

    //Hide all of the radio buttons
    $(radioButtonIds).css("display", "none");
    //alert('Result name = ' + result.Type);
    /*
    for (var propertyName in result) {
        // propertyName is what you want
        // you can get the value like this: myObject[propertyName]
        alert(propertyName);
    }
    */

    var tallylabels;
    var radiobuttons;

    //alert(result.toString());

    //if (result != null)
    if (result != null && result.Contestants != null && result.Contestants.length > 0)
    {
        //Update radio button labels with results
        //var tallylabels = $(tallyLabelIds).sort(sortByID);
        tallylabels = $(tallyLabelIds).sort(sortByID);

        //Added 11/19/2009 -- we need the radio buttons to check their values -- they have the identifiers
        //var radiobuttons = $(radioButtonIds).sort(sortByID);
        radiobuttons = $(radioButtonIds).sort(sortByID);

        //The sorted radio buttons and labels should correspond (i.e., radiobuttons[0] should be the 
        //radio button for tallylabels[0])

        //Added 12/29/2008 -- if page has updated, these controls might not be around anymore
        if (radiobuttons != null && radiobuttons.length > 0)
        {
            for (var i = 0; i < tallylabels.length; i++)
            {
                //Added 11/19/2009 -- get the contestant for this identifier
                var contestant = GetContestantByIdentifier(result.Contestants, radiobuttons[i].value);

                //Original code
                /*            
                var pct = result.Contestants[i].ScorePercent + "%";

            //$("label[for='" + radioButtons[i].id + "']").text(pct);
                if (breakAfterScore)
                tallylabels[i].innerHTML = pct + "<br />";
                else
                tallylabels[i].innerHTML = pct;

            tallylabels[i].style.display = "";
                */

                if (contestant != null)
                {
                    var pct = contestant.ScorePercent + "%";

                    //$("label[for='" + radioButtons[i].id + "']").text(pct);
                    if (breakAfterScore)
                        tallylabels[i].innerHTML = pct + "<br />";
                    else
                        tallylabels[i].innerHTML = pct;

                    tallylabels[i].style.display = "";
                }
            }
        }
    }
    else
    {
        //TODO: Remove alert before we go live
        //alert("Result was null or there was no contestant data in result. Please check return value (and we will remove this alert before SWRV goes live!");
        alert(GetResultsErrorMsg(result) + " Please check return value (and we will remove this alert before SWRV goes live!");
        return;
    }

    //Hide the vote button
    $("#" + voteButtonID).css("display", "none");

    //If the game is still open, show the Vote Again button.
    //Otherwise, indicate the winner and don't show voting controls.
    //var gameisopen = IsGameOpen(gameID);
    //var gameclosed = !IsGameOpen(gameID);

    //alert('gameisopen = ' + gameisopen);
    //alert('gameclosed = ' + gameclosed);


    //if (gameclosed)
    //if !IsGameOpen didn't work. Assigning the return value ot gameclosed with ! didn't work.
    //if (IsGameOpen(gameID) == false)
    //JavaScript is funny with boolean types -- using strings just to be safe

    if (IsGameClosed(result) == "true")
    {
        //alert('GAME IS CLOSED!');
        if (result != null)
        {
            var iWinnerIndex = GetIndexOfWinner(result);

            //Get images so we can highlight the winner's image
            if (imageIds != null && imageIds != "")
            {
                var images = $(imageIds);

                for (i = 0; i < images.length; i++)
                {
                    if (i == iWinnerIndex)
                    {
                        images[i].style.borderColor = "Yellow";
                        images[i].style.borderWidth = "1px";
                        images[i].style.borderStyle = "solid";
                    }
                    else
                    {
                        images[i].style.borderWidth = "0px";
                        images[i].style.borderStyle = "none";
                    }
                }
            }

            if (winnerLabelIds != null && winnerLabelIds != "")
            {
                //alert("Using specialized WINNER logic, winner index = " + iWinnerIndex);
                var winnerlabels = $(winnerLabelIds);
                //alert("winnerlabels length = 

                winnerlabels[iWinnerIndex].style.display = "";

                //alert(winnerlabels[iWinnerIndex].id);

                if (winnerCSS != null && winnerCSS != "")
                    winnerlabels[iWinnerIndex].innerHTML = "<div class=\"" + winnerCSS + "\">WINNER</div>";
                else
                    winnerlabels[iWinnerIndex].innerHTML = "WINNER";
            }
            else
            {
                if (tallylabels != null && tallylabels.length > 0)
                {
                    if (winnerCSS != null && winnerCSS != "")
                        tallylabels[iWinnerIndex].innerHTML = "<div class=\"" + winnerCSS + "\">WINNER</div>" + tallylabels[iWinnerIndex].innerHTML;
                    else
                    {
                        //Different games indicate the winner differently. This is the way Big Top Hits and Retrograde do it.
                        //tallylabels[iWinnerIndex].innerHTML = "WINNER<br />" + tallylabels[iWinnerIndex].innerHTML;
                        //1/4/2010 - Added this if condition because Anita was seeing the WINNER text repeating, and it could only
                        //have happened here
                        /*
                        if (tallylabels[iWinnerIndex].innerHTML.indexOf("WINNER<br />", 0) != 0)
                        tallylabels[iWinnerIndex].innerHTML = "WINNER<br />" + tallylabels[iWinnerIndex].innerHTML;
                        */

                        if (tallylabels[iWinnerIndex].innerHTML.indexOf("WINNER", 0) != 0)
                        {
                            //This seems like a little much, but at least we'll be sure the WINNER text won't be
                            //repeated
                            tallylabels[iWinnerIndex].innerHTML = tallylabels[iWinnerIndex].innerHTML.replace(/WINNER<br>/gi, "");
                            tallylabels[iWinnerIndex].innerHTML = tallylabels[iWinnerIndex].innerHTML.replace(/WINNER/gi, "");
                            tallylabels[iWinnerIndex].innerHTML = "WINNER<br />" + tallylabels[iWinnerIndex].innerHTML;
                        }
                    }
                }
            }
        }

        //If there are any other controls we should hide when the game is closed, do so now
        if (addtlControlsToHideIfGameClosed != null && addtlControlsToHideIfGameClosed != "")
        {
            $(addtlControlsToHideIfGameClosed).css("display", "none");
        }
    }
    else
    {
        //alert("This game is still open, so we will now display the VOTE AGAIN button.");
        $("#" + voteAgainButtonID).css("display", "");
    }



    //TODO: Highlight image of the winner

}


//Gets the index of the contestant in the results object with the lowest rank number (i.e., the winner)
function GetIndexOfWinner(results)
{
    //TODO: Check for null or empty results

    var iHighestRankedIndex = 0;
    var iHighestRank = results.Contestants.length + 1; //Set highest rank to whatever the lowest rank could be

    //Loop through all contestants    
    for (var i = 0; i < results.Contestants.length; i++)
    {
        //If this contestant has a rank higher (a lower number) than the current champ, he takes the lead
        if (results.Contestants[i].Rank < iHighestRank)
        {
            iHighestRankedIndex = i;
            iHighestRank = results.Contestants[i].Rank;
        }
    }

    return iHighestRankedIndex;
}


function RemoveMSJSONEnvelope(jsonObject) 
{
    if (jsonObject.d != null) 
    {
        //alert("Found D!");
        return jsonObject.d;
    }

    if (jsonObject.toString().match("^{\"d\":") == "{\"d\":")
    {
        //alert('JSON envelope found');
        return eval('(' + jsonObject.toString().substring(5, (jsonObject.length - 1)) + ')');
    }
    else
    {
        //alert('NO JSON envelope found');
        return jsonObject.toString();
    }
}


function ProcessVoteShowMessageAfter(
    gameID,
    userID,
    radioButtonIDs,
    tallyLabelIDs,
    voteButtonID,
    votingImg,
    voteAgainButtonID,
    voteContentBodyID,
    messageLabelID,
    thankYouMsg,
    thankYouMsgCSSClass,
    gameOverMsg,
    gameOverMsgCSSClass,
    voteImg)
{
    //Get selected value
    var selectedRadioButton = GetSelectedRadioButton(radioButtonIDs);
    if (selectedRadioButton == null || selectedRadioButton.length == 0)
        return;

    //Switch vote button image to VOTING image
    UpdateImage(voteButtonID, votingImg);

    setTimeout("SubmitVoteShowMessageAfter(" +
        "'" + userID + "'," +
        (tallyLabelIDs != null ? "'" + tallyLabelIDs + "'" : "null") + "," +
        gameID + ",'" +
        radioButtonIDs + "','" +
        voteButtonID + "','" +
        voteAgainButtonID + "','" +
        voteContentBodyID + "','" +
        messageLabelID + "','" +
        gameOverMsgCSSClass + "'," +
        (gameOverMsg != null ? "'" + gameOverMsg + "'" : "null") + "," +
        (thankYouMsgCSSClass != null ? "'" + thankYouMsgCSSClass + "'" : "null") + "," +
        (thankYouMsg != null ? "'" + thankYouMsg + "'" : "null") + ",'" +
        voteImg + "')", 250);
}


function SubmitVoteShowMessageAfter(
    userID,
    tallyLabelIDs,
    gameID,
    radioButtonIDs,
    voteButtonID,
    voteAgainButtonID,
    voteContentBodyID,
    messageLabelID,
    gameOverMsgCSSClass,
    gameOverMsg,
    thankYouMsgCSSClass,
    thankYouMsg,
    voteImg)
{
    //alert(gameOverMsg);
    //This was required to allow IE to show VOTING button before vote is submitted.
    //I...hate...IE...
    //Submit vote

    //Get selected value
    var selectedRadioButton = GetSelectedRadioButton(radioButtonIDs);
    if (selectedRadioButton == null || selectedRadioButton.length == 0)
        return;

    $.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: "AJAXServices/InteractivityService.svc/AddSubmittal",
                data: '{ "Identifier": "' + selectedRadioButton.value + '", "UserId": "' + userID + '", "Text": "", "ImageId": "", "SubmitterURI": "" }',
                processData: true,
                async: true
            });

    //Get latest results for this game if applicable
    if (tallyLabelIDs != null)
        GetResultsAndUpdateTallyLabels(gameID, radioButtonIDs, tallyLabelIDs);

    //Determine if game is still open
    //TODO: Implement
    //var bGameClosed = !IsGameOpen(gameID);

    //I HATE JAVASCRIPT -- using booleans shouldn't require this -- it didn't like !IsGameOpen()
    //var bGameClosed = (IsGameOpen(gameID) == false);
    var gameclosed = (IsGameOpen(gameID).toString() == "false");
    /*
    var gameclosed;
    var gameopen = IsGameOpen(gameID);
    alert("gameopen in submit: " + gameopen);
    gameclosed = (gameopen == "true");
    */
    //bGameClosed = !bGameClosed;

    //Update controls ////////////////////

    //Hide vote button
    $("#" + voteButtonID).css("display", "none");

    //Hide content body
    if (tallyLabelIDs == null)
        $("#" + voteContentBodyID).css("display", "none");
    else
        $(radioButtonIDs).css("display", "none");

    //Remove any classes applied to the message label
    $("#" + messageLabelID).removeClass();

    //if (bGameClosed)
    if (gameclosed)
    {
        //Hide vote again button
        $("#" + voteAgainButtonID).css("display", "none");

        //Set game over message and apply style
        $("#" + messageLabelID).addClass(gameOverMsgCSSClass).css("display", "");
        $("#" + messageLabelID).html(gameOverMsg);
    }
    else
    {
        //Show vote again button
        $("#" + voteAgainButtonID).css("display", "");

        //Set thank you message and apply style
        $("#" + messageLabelID).css("display", ""); //ACH -- Added this 10/27/2009 to accomodate SWRVdown
        $("#" + messageLabelID).addClass(thankYouMsgCSSClass);

        $("#" + messageLabelID).html(thankYouMsg);
    }

    //alert(voteImg);
    UpdateImage(voteButtonID, voteImg);
}


function UpdateImage(imageCtrl, imageUrl)
{
    document.getElementById(imageCtrl).src = imageUrl;
    return;
}


function ProcessVoteNoResultsShowMessageAfter(
    gameID,
    userID,
    radioButtonIDs,
    voteButtonID,
    votingImg,
    voteAgainButtonID,
    voteContentBodyID,
    messageLabelID,
    thankYouMsg,
    thankYouMsgCSSClass,
    gameOverMsg,
    gameOverMsgCSSClass,
    voteImg)
{
    //ProcessVoteShowMessageAfter(gameID, userID, radioButtonIDs, null, voteButtonID, votingImg, voteAgainButtonID, voteContentBodyID, messageLabelID, thankYouMsg, thankYouMsgCSSClass, gameOverMsg, gameOverMsgCSSClass, voteImg);

    //TODO: Finish work on the code below to prevent video stream from freezing in IE when we check to 
    //see if the game is still open
    var selectedRadioButton = GetSelectedRadioButton(radioButtonIDs);
    if (selectedRadioButton == null || selectedRadioButton.length == 0)
        return;

    //Switch vote button image to VOTING image
    UpdateImage(voteButtonID, votingImg);

    //Submit vote
    setTimeout("AddSubmittal('" + selectedRadioButton.value + "', '" + userID + "', '', '', '')", 250);

    //Find out if game is still open and update controls accordingly
    $.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: "AJAXServices/GamesService.svc/IsGameOpen",
                data: '{ "GameID": "' + gameID + '" }',
                processData: true,
                async: true,
                success: function(msg)
                {
                    var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg)
                    //alert(msgWithoutEnvelope);
                    UpdateVotingControlsWithMessage(
                        msgWithoutEnvelope,
                        voteButtonID,
                        voteAgainButtonID,
                        voteImg,
                        null,
                        voteContentBodyID,
                        radioButtonIDs,
                        messageLabelID,
                        gameOverMsgCSSClass,
                        gameOverMsg,
                        thankYouMsgCSSClass,
                        thankYouMsg);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error Occurred! " + errorThrown); }
            });

}


function UpdateVotingControlsWithMessage(
    gameopen,
    voteButtonID,
    voteAgainButtonID,
    voteImg,
    tallyLabelIDs,
    voteContentBodyID,
    radioButtonIDs,
    messageLabelID,
    gameOverMsgCSSClass,
    gameOverMsg,
    thankYouMsgCSSClass,
    thankYouMsg)
{
    //Hide vote button
    $("#" + voteButtonID).css("display", "none");

    //Hide content body
    if (tallyLabelIDs == null)
        $("#" + voteContentBodyID).css("display", "none");
    else
        $(radioButtonIDs).css("display", "none");

    //Remove any classes applied to the message label
    $("#" + messageLabelID).removeClass();

    //if (bGameClosed)
    if (!gameopen)
    {
        //Hide vote again button
        $("#" + voteAgainButtonID).css("display", "none");

        //Set game over message and apply style
        $("#" + messageLabelID).addClass(gameOverMsgCSSClass).css("display", "");
        $("#" + messageLabelID).html(gameOverMsg);
    }
    else
    {
        //Show vote again button
        $("#" + voteAgainButtonID).css("display", "");

        //Set thank you message and apply style
        $("#" + messageLabelID).css("display", ""); //ACH -- Added this 10/27/2009 to accomodate SWRVdown
        $("#" + messageLabelID).addClass(thankYouMsgCSSClass);

        $("#" + messageLabelID).html(thankYouMsg);
    }

    //alert(voteImg);
    UpdateImage(voteButtonID, voteImg);

}


function GetResultsAndUpdateTallyLabels(gameID, radioButtonIDs, tallyLabelIDs)
{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json",
        url: "AJAXServices/GamesService.svc/GetGameResult",
        data: '{ "GameID": "' + gameID + '" }',
        processData: true,
        async: false,
        success: function(msg)
        {
            //alert('Got game result: ' + msg);

            var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg)
            //alert('msgWithoutEnvelope = ' + msgWithoutEnvelope);
            //alert("Got it! " + msgWithoutEnvelope.Contestant1Percentage);
            UpdateTallyLabels(msgWithoutEnvelope, radioButtonIDs, tallyLabelIDs);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error occurred getting game results: " + errorThrown); }
    });
}


function UpdateTallyLabels(results, radioButtonIDs, tallyLabelIDs)
{
    //alert('yo yo yo');
    if (results == null || results.Contestants == null || results.Contestants.length == 0)
        return;
    else
    {
        //alert('hey - radioButtonIDs = ' + radioButtonIDs + ', tallyLabelIDs = ' + tallyLabelIDs);
        var radiobuttons = $(radioButtonIDs);
        var tallylabels = $(tallyLabelIDs);

        if (radiobuttons.length == 0) return;

        //Loop through contestants in results.
        //Match contestant identifier with radio button value -- if equal, assign label at same index the
        //value of the result.
        var contestant;
        for (contestant = 0; contestant < results.Contestants.length; contestant++)
        {
            var i;
            for (i = 0; i < radiobuttons.length; i++)
            {
                if (radiobuttons[i].value == results.Contestants[contestant].Identifier)
                {
                    tallylabels[i].innerHTML = results.Contestants[contestant].ScorePercent + "%";
                    break;
                }
            }
        }

        //Make sure tally labels are visible
        $(tallyLabelIDs).css("display", "");
    }
}


function ResetControlsNoResults(
    controlsToShow,
    controlsToHide,
    messageLabelID,
    messageLabelText,
    messageLabelCSSClass)
{
    $(controlsToShow).css("display", "");
    $(controlsToHide).css("display", "none");

    if (messageLabelID != null)
    {
        //Remove any classes applied to the message label
        $("#" + messageLabelID).removeClass();

        //Set message label text and class    
        $("#" + messageLabelID).text(messageLabelText).addClass(messageLabelCSSClass);
    }
}


function SubmitGameComment(
    identifier,
    userID,
    firstNameControlID,
    stateControlID,
    commentControlID,
    controlsToHide,
    controlsToShow,
    validatorControls)
{
    var commentText;

    if (validatorControls != null)
    {
        //Process validator controls -- if any fail, return
        if (!ProcessValidators(validatorControls))
            return;
    }

    commentText = "FirstName=" + $("#" + firstNameControlID)[0].value +
        "|Location=" + $("#" + stateControlID).val() +
        "|Comment=" + $("#" + commentControlID)[0].value;

    SubmitComment(identifier, userID, commentText, controlsToHide, controlsToShow, validatorControls, commentControlID);
}


function SubmitComment(identifier, userID, commentText, controlsToHide, controlsToShow, validatorControls, commentControlID)
{
    //5/26/2010 - Changed $ to jQuery due to $ being broken by a 3rd party module

    //Process validator controls -- if any fail, return
    if (validatorControls != null)
    {
        if (!ProcessValidators(validatorControls))
            return;
    }

    //Submit comment
    //$.ajax
    jQuery.ajax
    ({
        type: "POST",
        contentType: "application/json",
        url: "AJAXServices/InteractivityService.svc/AddSubmittal",
        data: '{ "Identifier": "' + identifier + '", "UserId": "' + userID + '", "Text": "' + ScrubString(commentText) + '", "ImageId": "", "SubmitterURI": "" }',
        processData: true,
        async: false,
        success: function(msg)
        {
            /*
            var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg)
            //alert("Got it! " + msgWithoutEnvelope.Contestant1Percentage);
            UpdateVotingControls(
            msgWithoutEnvelope,
            radioButtonIds,
            tallyLabelIds,
            voteButtonID,
            voteAgainButtonID,
            imageIds,
            addtlControlsToHideIfGameClosed,
            winnerLabelIds,
            winnerCSS,
            breakAfterScore);
            */
            //alert("Submitted!");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error occurred while attempting to submit comment. Error = " + errorThrown); }
    });

    //Hide/show appropriate controls
    ToggleControls(controlsToShow, controlsToHide);

    //Clear the comment control's text for next time
    jQuery("#" + commentControlID).val("");
}


function ToggleControls(controlsToShow, controlsToHide)
{
    //5/26/2010 - Replaced $ syntax with jQuery because a FileUpload module we are now using killed the $ shortcut

    //Hide/show appropriate controls
    if (controlsToHide != null)
        jQuery(controlsToHide).css("display", "none");

    if (controlsToShow != null)
        jQuery(controlsToShow).css("display", "");
}


function ResetControls(
    gameID,
    radioButtonIDs,
    tallyLabelIDs,
    controlsToShowIfGameOpen,
    controlsToHideIfGameOpen,
    controlsToShowIfGameClosed,
    controlsToHideIfGameClosed,
    messageLabelID,
    messageLabelCSSClass,
    messageLabelGameClosedText)
{
    var gameopen;
    gameopen = IsGameOpen(gameID);

    if (gameopen.toString() == "true")
    {
        ToggleControls(controlsToShowIfGameOpen, controlsToHideIfGameOpen);
    }
    else
    {
        //Game is CLOSED. Get the latest results, update controls, then show and hide appropriate controls.
        GetResultsAndUpdateTallyLabels(gameID, radioButtonIDs, tallyLabelIDs);
        ToggleControls(controlsToShowIfGameClosed, controlsToHideIfGameClosed);

        if (messageLabelID != null)
        {
            //Set message label text and class, and make it visible
            if (messageLabelCSSClass != null)
            {
                $("#" + messageLabelID).removeClass();
                $("#" + messageLabelID).addClass(messageLabelCSSClass);
            }

            $("#" + messageLabelID).html(messageLabelGameClosedText);
        }
    }
}


function ProcessValidators(validatorSelectors)
{
    var validationOK = true;

    //Get all validator controls
    //var validators = $(validatorSelectors);
    //5/26/2010 - Changed due to $ being broken by a 3rd party module
    var validators = jQuery(validatorSelectors);

    //Loop through validators and process each one
    if (validators.length > 0)
    {
        for (var index = 0; index < validators.length; index++)
        {
            ValidatorValidate(validators[index]);
            validationOK = validationOK & (validators[index].style.visibility == "hidden");
        }
    }

    //Return final validation status
    return validationOK;
}


function ProcessPollSubmission(userID, voteButtonID, voteImg, votingImg, radioButtonIDs, controlsToHide, controlsToShow)
{
    //Get value of selected radio button
    var selectedOption = GetSelectedRadioButton(radioButtonIDs);

    //if (identifier != null && identifier != "")
    if (selectedOption != null)
    {
        //Disable voting button
        $("#" + voteButtonID).attr('disabled', 'disabled');

        //Show VOTING image
        setTimeout("UpdateImage('" + voteButtonID + "', '" + votingImg + "')", 100);

        //Submit poll
        setTimeout("AddSubmittal('" + selectedOption.value + "', '" + userID + "', '', '', '')", 250);

        //Hide and show specified controls
        setTimeout("ToggleControlsAndSetButtonImage('" + controlsToShow + "', '" + controlsToHide + "', '" + voteButtonID + "', '" + voteImg + "')", 250);

        //Re-enable voting button
        $("#" + voteButtonID).attr('disabled', '');
    }
    else
    {
        return; //No selected option. Do nothing.
    }

}

function ToggleControlsAndSetButtonImage(controlsToShow, controlsToHide, buttonID, buttonImg)
{
    ToggleControls(controlsToShow, controlsToHide);
    $("#" + buttonID).attr("src", buttonImg);
}


function AddSubmittal(identifier, userID, commentText, imageId, submitterURI)
{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json",
        url: "/swrv/AJAXServices/InteractivityService.svc/AddSubmittal",
        data: '{ "Identifier": "' + identifier + '", "UserId": "' + userID + '", "Text": "' + commentText + '", "ImageId": "' + imageId + '", "SubmitterURI": "' + submitterURI + '" }',
        processData: true,
        async: true
    });
}


function IsGameOpen(gameID)
{
    var msgWithoutEnvelope = "";

    //TODO: CLEAN UP!!!!

    //$.ajax
    //5/26/2010 - Changed from $.ajax to jQuery.ajax due to the new FileUpload module that kills the use of 
    //the $ shortcut
    jQuery.ajax    
    ({
        type: "POST",
        contentType: "application/json",
        url: "AJAXServices/GamesService.svc/IsGameOpen",
        data: '{ "GameID": "' + gameID + '" }',
        processData: true,
        async: false,
        success: function(msg)
        {
            msgWithoutEnvelope = RemoveMSJSONEnvelope(msg);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error Occurred! " + errorThrown); msgWithoutEnvelope = null; }
    });

    return msgWithoutEnvelope;
}


function IsGameClosed(results)
{
    /*
    if (results == null)
    return true;
    else
    return (results.Status == 2);
    */

    //After having oodles of issues with JavaScript and boolean types, I converted all return values to 
    //strings, just to be safe.

    if (results == null)
        return "true";
    else
    {
        //alert(results.Status);

        if (results.Status == 2)
            return "true";
        else
            return "false";
    }
}


function GetContestantByIdentifier(contestants, identifier)
{
    for (var i = 0; i < contestants.length; i++)
    {
        if (contestants[i].Identifier == identifier)
            return contestants[i];
    }

    //Still here? Contestant not found.
    return null;
}

function SubmitVoteNoResults(contestantId, userId, gameId, votebuttonImageId, controlId, votingImageURL, voteAgainImageURL, controlsToHideIfClosedSelector) 
{
    var control = document.getElementById(controlId);
    var originalOnClick = control.onclick;

    control.onclick = null;

    //Show VOTING image
    UpdateImage(votebuttonImageId, votingImageURL);

    //Submit vote
    setTimeout("AddSubmittal('" + contestantId + "', '" + userId + "', '', '', '')", 200);

    //Find out if game is still open and update controls accordingly
    jQuery.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: "AJAXServices/GamesService.svc/IsGameOpen",
                data: '{ "GameID": "' + gameId + '" }',
                processData: true,
                async: true,
                success: function (msg) {
                    var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg)

                    if (true) {
                        //Game is still OPEN
                        //Hide and show specified controls
                        setTimeout("ToggleControlsAndSetButtonImage(null, null, '" + votebuttonImageId + "', '" + voteAgainImageURL + "')", 100);

                        //Re-enable voting button
                        control.onclick = originalOnClick;
                    }
                    else {
                        //Game is CLOSED
                        setTimeout("ToggleControlsAndSetButtonImage(null, '" + controlsToHideIfClosedSelector + "', null, null)", 100);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Error Occurred! " + errorThrown); }
            });
}


function SubmitVoteViaLinkNoResults(contestantId, userId, gameId, voteLinkId, votingText, voteAgainText, controlsToHideIfClosedSelector) {
    var voteLinkControl = document.getElementById(voteLinkId);
    var originalOnClick = voteLinkControl.onclick;

    voteLinkControl.onclick = null;

    //Show VOTING image
    //alert('voteLinkId = ' + voteLinkId);
    $("#" + voteLinkId).text(votingText);
    //alert($("#" + voteLinkId).length);
    //alert($("#" + voteLinkId)[0].innerHTML);

    //Submit vote
    setTimeout("AddSubmittal('" + contestantId + "', '" + userId + "', '', '', '')", 200);

    //Find out if game is still open and update controls accordingly
    $.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: "AJAXServices/GamesService.svc/IsGameOpen",
                data: '{ "GameID": "' + gameId + '" }',
                processData: true,
                async: true,
                success: function (msg) {
                    var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg)

                    if (true) {
                        //Game is still OPEN
                        setTimeout("$(\"#" + voteLinkId + "\").text(\"" + voteAgainText + "\");" , 100);

                        //Re-enable voting link
                        voteLinkControl.onclick = originalOnClick;
                    }
                    else {
                        //Game is CLOSED
                        //setTimeout("$(\"#" + voteLinkId + "\").text(\"" + voteAgainText + "\");", 100);
                        setTimeout("ToggleControlsAndSetButtonImage(null, '" + controlsToHideIfClosedSelector + "', null, null)", 100);
                    }

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Error Occurred! " + errorThrown); }
            });
}



function Nothing()
{
    return;
}
