﻿function RenderPoll(obj, data) {
	var poll = $(obj),
		total = data.total,
		item, percentValue, rightValue, leftValue;
	poll.empty();
	poll.append("<h2>" + data.question + "</h2>");
	poll.append("<ul class=\"poll-options\">");

	for(var i = 0; i < data.options.length; i++) {
		item = data.options[i];
		percentValue = Math.round(item.votes / total * 100);

		poll.append("<li class=\"option\" id=\"option-" + item.optionId + "\">"
		+ "<h3>" + item.text + "</h3>"
			+ "<div class=\"graph\"><img src=\""+host+"/images/poll-graph.gif\" height=\"10\" width=\"" + percentValue + "%\" /></div>"
		+ "<div class=\"values\">" + percentValue + "% (" + item.votes + " صوت)</div>"
		+ "</li>");
	}
	
	poll.append("</ul>");
	poll.append("<div class=\"total\">يوجد " + total + " صوت.</div>");
}
  $(document).ready(function() {
$(".poll form").submit(function() {

    var selection = $(this).find(":checked").val();
  
    if (selection != undefined) {
        $.post(
			site + "/poll/vote",
			{ optionId: selection },
			function(data, textStatus) {
			    SetCookie("poll_" + data.pollId, selection, 30);
			    // render the poll for the given data
			    RenderPoll($("#poll-" + data.pollId), data);
			},
			"json"
		);
    }

    return false;
});
});