﻿function InitializePoll(pollID, radioName, contentID, webServiceUrl)
{
    var poll = $('#' + pollID);
    var radioButtons = poll.find("input:radio[name=" + radioName + "]");
    var numOptions = radioButtons.length;
    poll.find(".VoteButton").click( function () {
        var selectedVal = radioButtons.filter(":checked").val();
        if (selectedVal != null)
        {
            CastVote(poll, numOptions, selectedVal, contentID, webServiceUrl);
        }
        return false;
    });
    poll.find(".ViewResults").click( function () {
        CastVote(poll, numOptions, -1, contentID, webServiceUrl); //gets results without voting
        return false;
    });
}

function CastVote(poll, numOptions, selectedVal, contentID, webServiceUrl)
{
    $.ajax({
        type: "POST",
        url: webServiceUrl,
        contentType: "application/json; charset=utf-8",
        data: "{'ContentID':'" + contentID + "','SelectedVal':'" + selectedVal + "','NumOptions':'" + numOptions +"'}",
        dataType: "json",
        success: CastVote_Success,
        error:
            function (XMLHttpRequest, textStatus, errorThrown)
            {
                alert(textStatus + ' ' + errorThrown);
            }
    });
    
    function CastVote_Success(result, textStatus)
    {
        //Get base values
        var voteResults = poll.find(".VoteResult");
        var maxWidth = poll.width();
        var total = 0;
        for (var i = 0; i < result.d.length; i++)
        {
            total += result.d[i];
        }
        //Set bar lengths for results display
        for (var j = 0; j < result.d.length; j++)
        {
            var width = 0;
            if (result.d[j] > 0)
            {
                width = (result.d[j] / total) * maxWidth - 5; //removes padding of 5px
            }
            width = Math.max(width, 8);
            voteResults.eq(j).css("width", width);
            voteResults.eq(j).text(result.d[j]);
        }
        //change display
        voteResults.show();
        poll.find(".RadioContainer").hide();
        poll.find(".Buttons").hide();
    }
}

function SetResultBarWidths(jResultDivs, maxWidth)
{
    var votes = 0, 
        totalVotes = 0,
        width;
    
    jResultDivs.each( function (i) {
        totalVotes += parseInt($(this).text(), 10);
    });
    
    totalVotes = Math.max(totalVotes, 1); //prevent divide by zero errors :)
    jResultDivs.each( function (i) {
        votes = parseInt($(this).text(), 10);
        width = (votes / totalVotes) * maxWidth - 5;
        width = Math.max(width, 8);
        $(this).css("width", width);
    });
}
