// JavaScript Document

function animate_results(ul) {
	$(ul).children('li').each(function() {
		var pct = $(this).children('.percent').text();
		//$(this).children('.index').css("width", pct);
		$(this).children('.index').animate({ width: pct }, 1500);
	});
}

function submit_poll_vote(poll_id, poll) {
	// get the response
	var response = $(poll).children().children().children("input[name='response']:checked").val();
	
	// verify that the user selected an option
	if (response == null || response == 'undefined') {
		//alert('Oops! You forgot to choose an answer.');
		response = 'view_only';
	}
	
	var datastring = "response="+response+"&poll="+poll_id;
	$.post("components/quick-poll/process.php", datastring, function(data){
		//Data format: "[ans]:[pct],[ans]:[pct]" example: "Yes:80,No:20"
		var answers = data.split(",");
		var ans = '';
		var pct = '';
		var html = '';
		// iterate through the answers one by one
		for (var i in answers) {
			var answer = answers[i].split(":");
			ans = answer[0];
			pct = answer[1];
			html += '<li class="result"><span class="answer">'+ans+'</span> <span class="percent">'+pct+'%</span> <span class="index">'+pct+'</span></li>';
		}
		$(poll).children('.form').hide();
		$(poll).siblings('.results').children('ul').html(html);
		$(poll).siblings('.results').show();
		
		animate_results($(poll).siblings('.results').children('ul'));
	});
}

$(document).ready(function() {
	$("#poll_btn").click( function() {
		var poll_id = $(this).parents('.quick-poll').attr('id');
		var poll = $(this).parents('.poll');
		
		submit_poll_vote(poll_id, poll);
	});
	
	$(".show-poll-results").click(function() {
		var poll_id = $(this).parents('.quick-poll').attr('id');
		var poll = $(this).parents('.poll');
		
		submit_poll_vote(poll_id, poll);
	});
	$(".quick-poll .results").hide();
});