var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;
var votedID;

$(document).ready(function() {
	var questionID = $("input#questionID").val();
	var checkVote = $("input#voted").val();
	var didVote = false;
	
  	$("#poll").submit(formProcess); // setup the submit handler
  
	if ($("#poll-results").length > 0 ) {
		animateResults();
	}
	
	if(checkVote == "true") didVote = true;
	if($.cookie('answer'+questionID)) didVote = true;
  
	if(didVote) {
		$("#poll-container").empty();
	
		$.getJSON("/wwwadmin/globals/templates/9937/scripts/poll.cfm?vote=none&questionID="+questionID, loadResults);
	}
});

function formProcess(event) {
	event.preventDefault();
	
	var id = $("input[@name='poll']:checked").attr("value");
	id = id.replace("opt",'');
	var questionID = $("input#questionID").val();
	
	$("#poll-container").fadeOut("slow",function(){
		$(this).empty();
		
		votedID = id;
		$.getJSON("/wwwadmin/globals/templates/9937/scripts/poll.cfm?vote="+id+"&questionID="+questionID, loadResults);
		
		$.cookie('answer'+questionID, id, {expires: 365});
	});
}

function animateResults(){
	$("#poll-results div").each(function(){
		var percentage = $(this).next().text();
		
		if(percentage == "0%") percentage = "1%";
		
		$(this).css({width: "0%"}).animate({
			width: percentage}, 'slow');
	});
}

function loadResults(data) {
	var total_votes = data.totalvotes;
	var numAnswers = data.numAnswers;
	var questiontext = data.questiontext;
	var percent;
	var currentID;
	
	var results_html = "<div id='poll-results'><span style='font-weight:bold;'>Poll Results</span><br><br>"+questiontext+"<dl class='graph'>\n";
	
	for(var i=1; i<=numAnswers; i++) {
		currentID = parseInt(eval("data.result" + i));
		percent = Math.round((parseInt(eval("data.answer" + currentID))/parseInt(total_votes))*100);
		if(isNaN(percent)) percent = 0;
		results_html = results_html+"<dt class='bar-title'>"+eval("data.title" + currentID)+"</dt><dd class='bar-container'><div id='bar"+currentID+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
	}
	
	results_html = results_html+"</dl><p>Total Votes: "+total_votes+"</p></div>\n";
  	
	$("#poll-container").hide().append(results_html).fadeIn("slow",function(){
    	animateResults();});
}
