// add functionality to Array
Array.prototype.sum = function()
{
  return (! this.length) ? 0 : this.slice(1).sum() +
      ((typeof this[0] == 'number') ? this[0] : 0);
};

Array.prototype.max = function()
{
	var max = this[0];
	var len = this.length;
	for (var i = 1; i < len; i++) if (this[i] > max) max = this[i];
	return max;
}

// set cookie function
function set_cookie(c_name, value, expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function get_poll_results(poll_box)
{
	id = poll_box.replace('poll_box_', '');
	$.getJSON('/tools/poll_results.php', 'id=' + id, function(data) {
		poll_counts = data[0];
		for (i=0; i<poll_counts.length; i++)
		{
			poll_counts[i] = parseInt(poll_counts[i]);
		}
		total_votes = poll_counts.sum();
		if (total_votes == 0)
		{
			total_votes = 1;
		}
		poll_max = poll_counts.max();
		poll_percent = [];
		poll_relative_percent = [];
		for (i=0; i<poll_counts.length; i++)
		{
			poll_percent[i] = Math.round((poll_counts[i] / total_votes) * 100);
			poll_relative_percent[i] = Math.round((poll_counts[i] / poll_max) * 100);
		}
		i = 0;
		$('#poll_box_' + data[1] + ' .poll-results li').each(function(i) {
			$(this).children('.poll-percent').html(poll_percent[i] + '%');
			$(this).children('.poll-result-bar').children('div').animate({ width: poll_relative_percent[i] + '%' }, 750, 'swing');
		});
	});
}

function submit_poll(form_id, answer)
{
	if (answer)
	{
		box_id = form_id.replace('poll_', '');
		params = 'box=' + box_id + '&answer=' + answer;
		$.post('/tools/poll_submit.php', params, function(data) {
			if (data != 'Error')
			{
				set_cookie('answered_polls', data, 180);
			}			
			$('#' + form_id + ' .poll-submit').attr('disabled', 'disabled');
			if (answer == 'none')
			{
				$('#' + form_id + ' .poll-message').html('View the results above.');
			}
			else
			{
				$('#' + form_id + ' .poll-message').html('Thank you for voting!');
			}
			$('#' + form_id + ' .poll-options').hide();
			$('#' + form_id + ' .poll-results-template').addClass('poll-results').removeClass('poll-results-template');
			get_poll_results(box_id);
		});
	}
}

$(document).ready(function() {
	
	$('.poll-box').each(function() {
		get_poll_results($(this).attr('id'));
	});
	
	$('.poll-box form').submit(function() {
		form_id = $(this).attr('id');
		answer = $('#' + form_id + ' input[name=answer]:checked').val();
		submit_poll(form_id, answer);
		return false;
	});
	
	$('.poll-view-results').click(function() {
		form_id = $(this).parent().parent().attr('id');
		answer = 'none';
		submit_poll(form_id, answer);
		return false;
	});
	
});
