var votedId = null;
var width = 100;
$(document).ready(function() {
	$("#poll_vote").click(formProcess);
});

function formProcess(event) {
	
	$("#poll-container").hide(1100, function(){
		var id = $("input[name='option']:checked").val();
		votedId = id;
		$.getJSON("/poll/process/" + id, function(data){
			
			$(this).empty();
		
			var resultHtml = "<div id='poll-results'><h3 id='poll-heading'>Poll Results</h3>\n<table class='graph'>\n";  
			for (i in data.results) {  
				if(data.total > 0){
					percent = Math.round((parseInt(data.results[i]['count'])/parseInt(data.total))*100);	
				} else {
					percent = 0;
				}
				
				if(data.results[i]['id'] !== votedId){		  
					resultHtml = resultHtml+"<tr><td class='bar-title'>"+data.results[i]['name']+"</td><td class='bar-container'><div title='"+(width*(percent/100))+"' id='bar"+data.results[i]['id']+"' style='width:0%;'>&nbsp;</div><strong >"+percent+"%</strong></td></tr>\n";  
				} else {
					resultHtml = resultHtml+"<tr><td class='bar-title'>"+data.results[i]['name']+"</td><td class='bar-container'><div title='"+(width*(percent/100))+"' id='bar"+data.results[i]['id']+" 'style='width:0%;background-color:#0066cc;'>&nbsp;</div><strong >"+percent+"%</strong></td></tr>\n";
				}
			}  
			resultHtml = resultHtml+"</table><p>Total Votes: "+data.total+"</p></div>\n";  
			$("#poll-container").html(resultHtml).show(1100,function(){  
				animateResults();
			});
			
			$.cookie('vote_id', id, {
		        expires: 365
		    });
		});
	});
}
function animateResults(){
	$("#poll-results div").each(function(){
		var percentage = $(this).attr('title');
		$(this).css({width: "0%"}).animate({width: percentage}, 'slow');
	});
}
