// 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) {
		$('#polls .poll-results-box').show();
		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;
		$('#polls .poll-results li').each(function(i) {
			$(this).children('.poll-percent').html(poll_percent[i] + '%');
			$(this).children('.poll-result-bar').children('div').css({ width: '0%' }).animate({ width: poll_relative_percent[i] + '%' }, 750, 'swing');
		});
		return true;
	});
}

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).html('');
			$('.poll-show-results').show();
			get_poll_results(box_id);
		});
	}
}

$(document).ready(function() {
	
	$('.poll-box form').submit(function() {
		form_id = $(this).attr('id');
		answer = $('#' + form_id + ' select[name=answer]').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;
	});
	
	$('.poll-results-box .close').click(function() {
		$(this).parent().hide();
		return false;
	});
	
	$('.poll-show-results').click(function() {
		
		form_id = $(this).parent().attr('id');
		form_id = form_id.replace('poll_box_', '');
		get_poll_results(form_id)
		return false;
	});
	
});
