function doVote(voteURL) {
    $("#matchups").ajaxSubmit({
        url: 'doVote.jsp',
        method: 'GET',
        dataType: 'json',
        success:  displayResults
    });
}

function formatPercent(numerator, total) {
    return total > 0? Math.round(100*(numerator/total))+"%" : "NA";
}

function displayResults(resultMatchups) {
	var data = $("#matchups").formSerialize();
	if (data.length > 0) {
		var myDate = new Date();
		myDate.setMilliseconds(myDate.getMilliseconds()+(24*60*60*1000));
		document.cookie = "gcf="+resultMatchups.setID+"; expires="+myDate.toGMTString();
	}
    $.each(resultMatchups.pairings, function(index, pair) {
        var myTotal = pair.A.tally+pair.B.tally;
        var idSelector = "@id = '"+pair.nextSlot+"'";
        var myDiv = $("#matchups div["+idSelector+"]");
        
        $(":checkbox[@value = 'A']", myDiv).after("<span class=\"pctA\"></span>").remove();
        $(":checkbox[@value = 'B']", myDiv).after("<span class=\"pctB\"></span>").remove();
        $(myDiv).find("span.pctA").text(formatPercent(pair.A.tally, myTotal)).end().find("span.pctB").text(formatPercent(pair.B.tally, myTotal));
        drawLeader(myDiv, pair);
        $(".compareLink a", myDiv).text("Compare these cars");
        $(".compareLink", myDiv).find("span").remove().end().append("<span>Total votes:  "+formatTally(myTotal.toString())+"</span>");
    });
    $("#voteSubmit").find("span").remove(); //Addresses IE bad behavior
    $("#voteSubmit").remove();
}

function formatTally(tally, formatted) {
    if (typeof formatted == "undefined") formatted = "";
    if (tally.length <= 3)
        return tally+formatted;
    
    formatted = ","+tally.substr(tally.length-3)+formatted;
    return formatTally(tally.substr(0, tally.length-3), formatted);
}

function drawLeader(divContext, pair) {
    var leaderDiv = "B";
    var trailerDiv = "A";
    if (pair.B.tally > pair.A.tally) {
        leaderDiv = "B";
        trailerDiv = "A";
    }
    else if (pair.A.tally > pair.B.tally) {
        leaderDiv = "A";
        trailerDiv = "B";
    }
    else if (pair.B.seed < pair.A.seed) {
        leaderDiv = "B";
        trailerDiv = "A";
    }
    else {
        leaderDiv = "A";
        trailerDiv = "B";
    }
    $("div.car"+leaderDiv, divContext).attr("class", "car"+leaderDiv+" leader");
    $("div.car"+trailerDiv, divContext).attr("class", "car"+trailerDiv);
}

function getLabel(car) {
    return "No. "+car.seed+" "+car.make+" "+car.model;
}

function getCalendarLabel(roundNumber, set, incompleteCounter) {
    var myLink = "";
    if (/*set.isCompleted*/true) {
        myLink = "results.jsp?round="+(roundNumber-1)+"&set="+set.ID;
    }
    else if (incompleteCounter == 1) {
        myLink = "/go/great-car-faceoff/";
    }
    return myLink.length > 0? "<a href=\""+myLink+"\">"+set.title+"</a>" : set.title;
}

function writeCalendar() {
    var incompleteCounter = 0;
    $.each(calendar.rounds, function(index, thisRound) {
        var roundNumber = thisRound.ordinal;
        $.each(thisRound.sets, function(index, set) {
            if (!set.isCompleted) incompleteCounter++;
            
            var myItem = document.createElement("li");
            $(myItem).append("<span class=\"calendarDate\">"+set.date+":  </span>").append("<span class=\"calendarTitle\">"+getCalendarLabel(roundNumber, set, /*incompleteCounter*/0)+"</span>");
            if (set.ID == matchupSet.setID) {
                $(myItem).attr("class", "active");
            }
            else if(!set.isCompleted && incompleteCounter > 1) {
                $(myItem).attr("class", "inactive");
            }
            $("#calendar").append(myItem);
        })
    });
    $("#calendar").append("<li><span class=\"calendarDate\">April 3:  </span><span class=\"calendarTitle\"><a href=\"/go/great-car-faceoff/\">The Winner</a></span></li>");
}

function getPairingTemplate() {
    var pairingDiv = document.createElement("div");
    $(pairingDiv).attr("class", "pairing");
    $(pairingDiv).append("<div class=\"carA\"><div class=\"input\"></div><img width=\"110\" height=\"73\" /><p class=\"carTitle\"></p><p class=\"blurb\"></p><div class=\"compareLink\"></div></div>");
    $(pairingDiv).append("<div class=\"carB\"><div class=\"input\"></div><img width=\"110\" height=\"73\" /><p class=\"carTitle\"></p><p class=\"blurb\"></p><div style=\"clear:both\">&nbsp;</div></div>");
    return pairingDiv;
}

function emailToFriend() {
    window.pgtitle = "Great Car Faceoff";
    window.ref = "advice";
    window.frmpg = "";
    window.storybody = "";
    window.varstr = "";
    window.iscache =  "";
    var roundTitle = $("#roundInfo").find("h1").text();
    pgtitle = pgtitle+" - "+roundTitle;
    var popupWin = window.open('/go/email/mailerPopUp.jsp', "mailpopup", "width=425,height=600,top=50,left=50");
    if (null != popupWin) popupWin.focus();
}

