﻿var contestantsperpage = 21;

function ProcessLevel10Vote(gameID, identifier, userID, voteLinkId, votingLinkId, voteAgainLinkId)
{
    //Look for a sort by control to sort results -- this will be present on the Level10 page, but not on any of
    //the other pages. The control is a select element with an id containing the text "Level10Gallery" and 
    //ending with "ddlSortBy". IF THIS CONTROL IS RENAMED, THIS WON'T WORK ANYMORE.
    //var sortByControlWrappedSet = $("select[id*=Level10Gallery][id$=ddlSortBy]");

    /*
    var sortByControlWrappedSet;
    
    //HACK: Make sure we get dropdownlist and its options
    for (var i = 0; i < 5; i++)
    {
    sortByControlWrappedSet = $("select[id*=Level10Gallery][id$=ddlSortBy]");
    if (sortByControlWrappedSet != null && sortByControlWrappedSet.length > 0 && sortByControlWrappedSet[0].options.length > 0)
    break;
    }

    if (sortByControlWrappedSet == null || sortByControlWrappedSet.length == 0 && sortByControlWrappedSet[0].options.length == 0)
    return; //Couldn't get drop down list or its options
    */


    //alert(sortByControlWrappedSet[0].options.length);

    //Hide VOTE link and show VOTING message
    $(voteLinkId).css("display", "none");
    $(votingLinkId).css("display", "");

    //alert("Submitting vote for " + identifier);
    //SubmitLevel10Vote(gameID, identifier, userID, sortByControlWrappedSet);
    setTimeout("SubmitLevel10Vote(" + gameID + ", '" + identifier + "', '" + userID + "', '" + votingLinkId + "')", 500);

    //Hide VOTING message
    //$(votingLinkId).css("display", "none");

    /*
    PROBLEM WITH THIS LINE OF CODE: If the order of the items switches, the "VOTE AGAIN" link will be shown for a 
    contestant other than the one the user voted for. We are addressing this in the methods that update the 
    controls after getting results so that the identifier of the contestant the user voted on is being used 
    to update the correct control.
    $(voteAgainLinkId).css("display", "");
    */
}


//function SubmitLevel10Vote(gameID, identifier, userID, sortByControlWrappedSet, votingLinkID)
function SubmitLevel10Vote(gameID, identifier, userID, votingLinkID)
{

    var sortByControlWrappedSet;

    //HACK: Make sure we get dropdownlist and its options
    for (var i = 0; i < 35; i++)
    {
        sortByControlWrappedSet = $("select[id*=Level10Gallery][id$=ddlSortBy]");
        if (sortByControlWrappedSet != null && sortByControlWrappedSet.length > 0 && sortByControlWrappedSet[0].options.length > 0)
            break;
    }

    //if (sortByControlWrappedSet == null || sortByControlWrappedSet.length == 0 && sortByControlWrappedSet[0].options.length == 0)
    //Modified 1/8/2010 to handle intermittent problem in IE8
    if (sortByControlWrappedSet == null || sortByControlWrappedSet.length == 0 || sortByControlWrappedSet[0].options == null || sortByControlWrappedSet[0].options.length == 0)
    {
        //May not have the sort by control if you AREN'T ON THE LEVEL10 page!
        //$(votingLinkID).css("display", "none");
        //return; //Couldn't get drop down list or its options
    }


    //Submit vote
    $.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: "AJAXServices/InteractivityService.svc/AddSubmittal",
                data: '{ "Identifier": "' + identifier + '", "UserId": "' + userID + '", "Text": "", "ImageId": "", "SubmitterURI": "" }',
                processData: true,
                async: true
            });

    var sServiceURLToCallForGrid;
    var sServiceURLToCallForIAC;

    var IACRankLabels = $("td[id*=LEVEL10InteActv][id$=tdRank]");

    //If Level 10 is in the IAC, get the URL for getting results for the grid
    if (IACRankLabels != null && IACRankLabels.length > 0)
    {
        sServiceURLToCallForIAC = "AJAXServices/GamesService.svc/GetGameResultSortByRank";
    }
    //else
    //alert("No IAC");

    //If we have the grid, get the URL to get results for items in the grid
    if (sortByControlWrappedSet != null && sortByControlWrappedSet.length > 0)
    {
        //Get selected option
        switch (sortByControlWrappedSet[0].value)
        {
            case "Rank":
                sServiceURLToCallForGrid = "AJAXServices/GamesService.svc/GetGameResultSortByRank";
                break;

            case "Artist":
                sServiceURLToCallForGrid = "AJAXServices/GamesService.svc/GetGameResultSortByArtist";
                break;

            case "Video":
                sServiceURLToCallForGrid = "AJAXServices/GamesService.svc/GetGameResultSortByVideoTitle";
                break;

            default:
                //alert("hi");
                sServiceURLToCallForGrid = "AJAXServices/GamesService.svc/GetGameResultSortByRank";
                break;
        }
    }
    //else
    //sServiceURLToCall = "AJAXServices/GamesService.svc/GetGameResult";

    //alert(sServiceURLToCall);


    //If sorting by same method in grid and IAC, we only need one call to get results
    if (sServiceURLToCallForGrid == sServiceURLToCallForIAC)
    {
        $.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: sServiceURLToCallForGrid,
                data: '{ "GameID": "' + gameID + '"}',
                processData: true,
                async: true,
                success: function(msg)
                {
                    var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg);
                    //alert(msgWithoutEnvelope);
                    UpdateLevel10IACControls(msgWithoutEnvelope, identifier);
                    //UpdateLevel10GridControls(15, msgWithoutEnvelope, identifier);
                    UpdateLevel10GridControls(contestantsperpage, msgWithoutEnvelope, identifier);

                    //Hide VOTING message
                    $(votingLinkID).css("display", "none");
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error occurred getting game results for grid and IAC!\nError = " + errorThrown + "\nTextStatus = " + textStatus + "\nXMLHttpRequest = " + XMLHttpRequest); }
            });
    }
    else
    {
        //alert(sServiceURLToCallForIAC);
        if (sServiceURLToCallForIAC != null)
        {
            //IAC
            $.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: sServiceURLToCallForIAC,
                data: '{ "GameID": "' + gameID + '"}',
                processData: true,
                async: true,
                success: function(msg)
                {
                    var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg);
                    //alert(msgWithoutEnvelope);
                    UpdateLevel10IACControls(msgWithoutEnvelope, identifier);

                    //Hide VOTING message
                    //$(votingLinkID).css("display", "none");
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error occurred getting game results for IAC!\nError = " + errorThrown + "\nTextStatus = " + textStatus); }
            });
        }

        //Grid
        if (sServiceURLToCallForGrid != null)
        {
            $.ajax
            ({
                type: "POST",
                contentType: "application/json",
                url: sServiceURLToCallForGrid,
                data: '{ "GameID": "' + gameID + '"}',
                processData: true,
                async: true,
                success: function(msg)
                {
                    var msgWithoutEnvelope = RemoveMSJSONEnvelope(msg);
                    //UpdateLevel10GridControls(15, msgWithoutEnvelope, identifier);
                    UpdateLevel10GridControls(contestantsperpage, msgWithoutEnvelope, identifier);

                    //Hide VOTING message
                    $(votingLinkID).css("display", "none");
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) { alert("Error occurred getting game result for grid!\nError = " + errorThrown + "\nTextStatus = " + textStatus); }
            });
        }
        else
            $(votingLinkID).css("display", "none"); //Hide VOTING message
    }

    //Hide VOTING message
    //$(votingLinkID).css("display", "none");
    //MOVED THIS TO THE AJAX CALLS ABOVE TO DISPLAY CONTROLS PROPERLY NOW THAT CALLS ARE ASYNC

}

/*
function GetLevel10Results()
{
//TODO: Get results
UpdateLevel10IACControls(null);
UpdateLevel10GridControls(null);
}
*/

function UpdateLevel10IACControls(results, selectedContestantIdentifier)
{
    //alert("Updating IAC controls");

    /*
    Select labels, images, and hidden fields via selectors.
    
    In the IAC, these are named as follows:
    Rank Labels = *LEVEL10InteActv*tdRank
    Artist Name Labels = *LEVEL10InteActv*tdArtistName
    Video Title Labels = *LEVEL10InteActv*tdVideoTitle
    Total Votes Labels = *LEVEL10InteActv*tdTotalVotes
    Images = *LEVEL10InteActv*imgThumbnail
    Hidden Table Cells w/Contestant Identifiers = *LEVEL10InteActv*hdnContestantIdentifier
    Vote Again Links = *LEVEL10InteActv*lbtnVoteAgain
    */

    //Make sure we got results
    if (results == null || results.Contestants == null || results.Contestants.length == 0)
    {
        //TODO: Remove alert before we go live
        //alert("Results were null or contained no contestant data. Please check results.\n(We will remove this alert before SWRV goes live)");
        //alert(GetResultsErrorMsg(results) + "(IAC) Please check results.\n(We will remove this alert before SWRV goes live)");
        return;
    }

    var rankLabels = $("td[id*=LEVEL10InteActv][id$=tdRank]");
    var artistNameLabels = $("td[id*=LEVEL10InteActv][id$=tdArtistName]");
    var videoTitleLabels = $("td[id*=LEVEL10InteActv][id$=tdVideoTitle]");
    var images = $("img[id*=LEVEL10InteActv][id$=imgThumbnail]");
    //var identifierCells = $("td[id*=LEVEL10InteActv][id$=hdnContestantIdentifier]");
    var identifierCells = $("td[id*=LEVEL10InteActv][id$=tdContestantIdentifier]");
    var voteLinks = $("a[id*=LEVEL10InteActv][id$=lbtnVote]");
    var votingLinks = $("a[id*=LEVEL10InteActv][id$=imgWait]");
    var voteAgainLinks = $("a[id*=LEVEL10InteActv][id$=lbtnVoteAgain]");

    if (rankLabels.length > 0)
    {

        var iMetadataIndex;

        for (var i = 0; i < 10; i++)
        {
            //iMetadataIndex = GetMetadataIndex(results.Contestants[i].Identifier);
            //Attempt to get metadata index 100 times to deal with an odd bug that only occurs in IE
            for (var x = 0; x < 1000; x++)
            {
                iMetadataIndex = GetMetadataIndex(results.Contestants[i].Identifier);
                if (iMetadataIndex != -1)
                    break;
            }

            if (iMetadataIndex == -1)
            {
                /*
                rankLabels[i].innerHTML = "?";
                artistNameLabels[i].innerHTML = "UNKNOWN";
                //videoTitleLabels[i].innerHTML = "UNKNOWN";
                //Modified 1/15/2010 to display the identifier in question when it could not be found in the
                //metadata, but existed in the results
                videoTitleLabels[i].innerHTML = "'" + results.Contestants[i].Identifier + "'";
                images[i].src = "";
                identifierCells[i] = "";
                voteLinks[i].style.display = "";     //Show VOTE link
                */
            }
            else
            {
                rankLabels[i].innerHTML = results.Contestants[i].Rank;
                artistNameLabels[i].innerHTML = ScrubString(Contestants[iMetadataIndex].ArtistName);
                videoTitleLabels[i].innerHTML = ScrubString(Contestants[iMetadataIndex].SongTitle);
                images[i].src = Contestants[iMetadataIndex].ArtistImage;
                identifierCells[i].innerHTML = Contestants[iMetadataIndex].Identifier;

                if (results.Status == 1) //Added this check to see if game still open, 12/16/2009
                {
                    //If this is the contestant the user voted for, their "VOTE AGAIN" link should be shown
                    if (Contestants[iMetadataIndex].Identifier == selectedContestantIdentifier)
                    {
                        //Show VOTE AGAIN link
                        voteAgainLinks[i].style.display = "";

                        //Explicitly hide VOTE link due to some strange behavior we were seeing
                        voteLinks[i].style.display = "none";
                    }
                    else
                    {
                        //Show VOTE link
                        voteLinks[i].style.display = "";

                        //Hide VOTE AGAIN link
                        voteAgainLinks[i].style.display = "none";
                    }
                }
                else
                {
                    //Game is closed. Hide VOTE and VOTE AGAIN links
                    voteLinks[i].style.display = "none";
                    voteAgainLinks[i].style.display = "none";
                }

            }

            votingLinks[i].style.display = "none";
        }
    }
} //UpdateLevel10IACControls


function UpdateLevel10GridControls(numberOfControlsPerPage, results, selectedContestantIdentifier)
{
    //alert("Updating Grid controls - # of contestants = " + results.Contestants.length);

    /*
    Select labels, images, and hidden fields via selectors.
    
    In the grid, these are named as follows:
    Rank Labels = *LEVEL10NonInteActv*tdRank
    Artist Name Labels = *LEVEL10NonInteActv*tdArtistName
    Video Title Labels = *LEVEL10NonInteActv*tdVideoTitle
    Total Votes Labels = *LEVEL10NonInteActv*tdTotalVotes
    Images = *LEVEL10NonInteActv*imgThumbnail
    Hidden Table Cells w/Contestant Identifiers = *LEVEL10*hdnContestantIdentifier
    Vote Again Links = *LEVEL10NonInteActv*lbtnVoteAgain
    
    To get the selected page, the following selector can be used:
    *Level10Gallery*hdnSelectedPage
    */

    //Make sure we got results
    if (results == null || results.Contestants == null || results.Contestants.length == 0)
    {
        //TODO: Remove alert before we go live
        //alert("Results were null or contained no contestant data. Please check results.\n(We will remove this alert before SWRV goes live)");
        //alert(GetResultsErrorMsg(results) + "(GRID) Please check results.\n(We will remove this alert before SWRV goes live)");
        return;
    }


    //TODO: Get total number of items
    //var iTotalItems =
    var iSelectedPage = $("input[id*=Level10Gallery][id$=hdnSelectedPage]")[0].value;
    if (iSelectedPage == "")
        iSelectedPage = 1;

    //alert("Selected Page = " + iSelectedPage);

    var iFirstItemToShow = (iSelectedPage * numberOfControlsPerPage) - numberOfControlsPerPage;

    //alert("First item to show = " + iFirstItemToShow);


    //Get all grid controls
    //NOTE: The sortByID function is in the jQueryCustomFunctions.js file, which must also be referenced by 
    //whichever page is being used to reference THIS one
    var rankLabels = $("td[id*=LEVEL10NonInteActv][id$=tdRank]").sort(sortByID);
    var artistNameLabels = $("td[id*=LEVEL10NonInteActv][id$=tdArtistName]").sort(sortByID);
    var videoTitleLabels = $("td[id*=LEVEL10NonInteActv][id$=tdVideoTitle]").sort(sortByID);
    var images = $("img[id*=LEVEL10NonInteActv][id$=imgThumbnail]").sort(sortByID);
    //var identifierCells = $("td[id*=LEVEL10NonInteActv][id$=hdnContestantIdentifier]");
    var identifierCells = $("td[id*=LEVEL10NonInteActv][id$=tdContestantIdentifier]").sort(sortByID);
    var voteLinks = $("a[id*=LEVEL10NonInteActv][id$=lbtnVote]").sort(sortByID);
    var votingLinks = $("a[id*=LEVEL10NonInteActv][id$=imgWait]").sort(sortByID);
    var voteAgainLinks = $("a[id*=LEVEL10NonInteActv][id$=lbtnVoteAgain]").sort(sortByID);

    //alert(identifierCells.length);

    /*
    for (var i = 0; i < rankLabels.length; i++)
    {
    alert("i = " + i.toString() + ", ID = " + rankLabels[i].id);
    }
    */

    if (rankLabels.length > 0)
    {

        var bFoundOne;
        var iTotalItems = results.Contestants.length;
        var iMetadataIndex = 0;


        //Loop through contestants in result and update the controls which are visible
        //(i.e. the ones on the selected page)
        var iControlIndex = 0;
        for (var i = iFirstItemToShow; (i < iFirstItemToShow + numberOfControlsPerPage) && (i < iTotalItems); i++)
        {
            bFoundOne = true;

            //Get metadata for this result based on identifier
            //alert(Contestants[i].ArtistName);

            //Update controls with metadata //////////////////

            /*
            Get the index in our collection of metadata for this contestant in our results.
            Example: result[12].Contestant.Identifier = "COHEED", which is the identifier of Contestants[23]
            */
            //iMetadataIndex = GetMetadataIndex(results.Contestants[i].Identifier);
            //Attempt to get metadata index 100 times to deal with an odd bug that only occurs in IE
            for (var x = 0; x < 1000; x++)
            {
                iMetadataIndex = GetMetadataIndex(results.Contestants[i].Identifier);
                if (iMetadataIndex != -1)
                    break;
            }


            //alert("Metadata Index = " + iMetadataIndex);

            if (iMetadataIndex == -1)
            {
                /*
                //alert("No metadata found for contestant " + results.Contestants[i].Identifier);
                rankLabels[iControlIndex].innerHTML = "?";
                artistNameLabels[iControlIndex].innerHTML = "UNKNOWN";
                //videoTitleLabels[iControlIndex].innerHTML = "UNKNOWN";
                //Modified 1/15/2010 to display the identifier in question when it could not be found in the
                //metadata, but existed in the results
                videoTitleLabels[iControlIndex].innerHTML = "'" + results.Contestants[i].Identifier + "'";

                images[iControlIndex].src = "";
                identifierCells[iControlIndex] = "";
                voteLinks[iControlIndex].style.display = "";  //Show VOTE link
                */
            }
            else
            {
                //alert(Contestants[iMetadataIndex].Identifier + ' artistNameLabels.length = ' + artistNameLabels.length);

                //if (iControlIndex == 0 && Contestants[iMetadataIndex].ArtistName == "Incubus")
                //  alert("Got it!");

                images[iControlIndex].src = Contestants[iMetadataIndex].ArtistImage;
                identifierCells[iControlIndex].innerHTML = Contestants[iMetadataIndex].Identifier;
                rankLabels[iControlIndex].innerHTML = results.Contestants[i].Rank;
                artistNameLabels[iControlIndex].innerHTML = ScrubString(Contestants[iMetadataIndex].ArtistName);
                //videoTitleLabels[iControlIndex].innerHTML = Contestants[iMetadataIndex].SongTitle + '(' + Contestants[iMetadataIndex].Identifier + ')';
                videoTitleLabels[iControlIndex].innerHTML = ScrubString(Contestants[iMetadataIndex].SongTitle);

                /*
                $('#' + identifierCells[iControlIndex].id).text(Contestants[iMetadataIndex].Identifier);
                $('#' + rankLabels[iControlIndex].id).text(results.Contestants[i].Rank);
                //$('#' + artistNameLabels[iControlIndex].id).text(Contestants[iMetadataIndex].ArtistName);
                //artistNameLabels[iControlIndex].removeChild(artistNameLabels[iControlIndex].firstChild);
                //artistNameLabels[iControlIndex].appendChild(document.createTextNode(artistNameLabels[iControlIndex].firstChild));
                artistNameLabels[iControlIndex].innerHTML = 'hi';
                alert(artistNameLabels[iControlIndex].innerHTML);
                $('#' + videoTitleLabels[iControlIndex].id).text(Contestants[iMetadataIndex].SongTitle);
                */

                //alert(artistNameLabels[iControlIndex].innerHTML + " index = " + iMetadataIndex);

                if (results.Status == 1) //Added this check to see if game still open, 12/16/2009
                {
                    //If this is the contestant the user voted for, their "VOTE AGAIN" link should be shown
                    if (Contestants[iMetadataIndex].Identifier == selectedContestantIdentifier)
                    {
                        //alert("SELECTED CONTESTANT " + selectedContestantIdentifier + " -- showing VOTE AGAIN link");

                        //Show VOTE AGAIN link
                        voteAgainLinks[iControlIndex].style.display = "";

                        //Explicitly hide VOTE link due to some strange behavior we were seeing
                        voteLinks[iControlIndex].style.display = "none";
                    }
                    else
                    {
                        //alert(Contestants[iMetadataIndex].Identifier);

                        //alert("Showing VOTE link for contestant " + identifierCells[iControlIndex].innerHTML);
                        //Show VOTE link
                        voteLinks[iControlIndex].style.display = "";

                        //Hide VOTE AGAIN link
                        voteAgainLinks[iControlIndex].style.display = "none";
                    }
                }
                else
                {
                    //Game is closed. Hide VOTE and VOTE AGAIN links
                    voteLinks[iControlIndex].style.display = "none";
                    voteAgainLinks[iControlIndex].style.display = "none";
                }

            }

            votingLinks[iControlIndex].style.display = "none";
            iControlIndex++;
        }

        if (!bFoundOne)
        {
            //How to handle this? Something has occurred so that the selected page is empty.
        }
    }
} //UpdateLevel10GridControls


function ResetLevel10Controls(voteLinkId, votingLinkId, voteAgainLinkId)
{
    $(voteLinkId).css("display", "");
    $(votingLinkId).css("display", "none");
    $(voteAgainLinkId).css("display", "none");
}


function GetMetadataIndex(identifier)
{
    //NOTE: The Contestants array is defined in the hosting webpage, not this file
    for (var i = 0; i < Contestants.length; i++)
    {
        if (Contestants[i].Identifier == identifier)
            return i;
    }

    //Still here? Contestant not found -- return -1.
    return -1;
}



