/**
 * Dynamic PHP/jQuery Poll Plugin
 *
 * A dynamic poll plugin that combines the functionality of php
 * with some neat jQuery animation effects.
 *
 * @author			Jonathan Rudenberg
 * @link				http://net.tutsplus.com/tutorials/javascript-ajax/creating-a-dynamic-poll-with-jquery-and-php/
 *
 * Modified by Barry Harley 2011
 *
 */

// Global variable definitions
// DB column numbers
var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;

var votedID;

/**
 * Poll Plugin Load
 * Determine whether to show poll form or results on page load.
 *
 * @return 	void
 */
$(document).ready(function() {
	// poll submit handler
	$("#poll").submit(formProcess); 
  
	// if results are already showing then animate them
	if ($("#poll_results").length > 0 ) animateResults();

	//$.cookie('vote_id', '');
	// what if user has already voted?
	if ($.cookie('vote_id')) // jump straight to results
	{
		// delete the poll form
		$("#poll_container form").empty();
		votedID = $.cookie('vote_id'); // get vote id
		// grab the results from php
		$.getJSON("/poll/get_results",loadResults);
	}
});

/**
 * Submit Vote
 * Peforms the task of submitting a poll vote.
 *
 * @param	Event Object
 * @return 	void
 */
function formProcess(event)
{
	// prevent the form from doing a normal submit
	event.preventDefault();
	
	// find out which option was checked
	var id = $("input[@name='poll']:checked").attr("value");
	id = id.replace("opt",'');
	
	// fade out the poll form
	$("#poll_container").fadeOut("slow", function() {
		// delete poll form
		$(this).find('form').remove();
    
		votedID = id;

		// send the vote off to the php and grab the results
		$.getJSON("/poll/vote/"+id,loadResults);
		
		// set a cookie so we know the user has voted
		$.cookie('vote_id', id, {expires: 365});
    });
}

/**
 * Animate Poll Results
 *
 * @return 	void
 */
function animateResults() {
	$("#poll_results div").each(function(){
		// use percentage to determine width
		var percentage = $(this).next().text();
		// animate graph bars
		$(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
	});
}

/**
 * Load Results
 * Formats and shows poll results.
 *
 * @param	Event Object
 * @return 	void
 */
function loadResults(data) 
{
	
	var total_votes = 0;
	var percent;
  
	// calculate total cotes
	for (id in data) total_votes = total_votes+parseInt(data[id][OPT_VOTES]);

	// start building the HTML for poll results
	var results_html = "<div id='poll_results'><dl class='graph'>";

	// calculate percentages and create HTML for graph bars
	for (id in data) 
	{
		percent = Math.round((parseInt(data[id][OPT_VOTES])/parseInt(total_votes))*100);
		if (data[id][OPT_ID] !== votedID) 
		{
			results_html = results_html+"<dt class='bar_title'>"+
				data[id][OPT_TITLE]+
			"</dt><dd class='bar_container'><div id='bar"+
			// set all width to 0% so we can animate them
			data[id][OPT_ID]+"'style='width:0%;'>&nbsp;</div><strong>"+
			percent+"%</strong></dd>";
		} 
		else // highlight current vote bar
		{
		results_html = results_html+"<dt class='bar_title'>"+
			data[id][OPT_TITLE]+
			"</dt><dd class='bar_container'><div id='bar"+
			data[id][OPT_ID]+
			"'style='width:0%;' class='current'>&nbsp;</div><strong>"+
			percent+"%</strong></dd>";
		}
	}

	results_html = results_html+
		"</dl><p class=\"total_votes\">Total Votes: "+
		total_votes+"</p></div>";
	
	// show results on page
	$("#poll_container").append(results_html).fadeIn("slow",function(){
	animateResults();
	});
}
