$(document).ready(function() {
	function renderChart(el) {
		var percents = el.find('.percent');
		var maxPercent = 1;
		for (var i=0; i<percents.length; i++) {
			maxPercent = Math.max(maxPercent, $(percents[i]).html());
		}
		
		el.find('li').each(function(index) {
			var percentEl = $(this).find('.percent');
			
			var bar = $('<span class="bar"/>');
			
			bar.css({
				width: Math.round(percentEl.html()/maxPercent*100)+'%'
			});
			$(this).find('.percent').html(Math.round($(this).find('.percent').html())+'%');
			$(this).append(bar);
		});
	}
	
	
	var polledEl = $('#content .polled').first();
	
	renderChart(polledEl.find('.results'));
	
	var form = polledEl.find('form');
	var formAction = form.attr('action');
	
	function prepareForm() {
		form.find('input[type=radio]').click(function() {
			form.submit();
		});
		form.submit(handleFormSubmit);
		
		polledEl.find('.show-results').click(function(event) {
			event.preventDefault();
			polledEl.load($(this).attr('href')+' #content .polled .inner', function() {
				renderChart(polledEl.find('.results'));
				polledEl.find('.close-results').click(function(event) {
					event.preventDefault();
					polledEl.load(formAction+' #content .polled .inner', function() {
						form = polledEl.find('form');
						prepareForm();
					});
					return false;
				});
			});
			return false;
		});
	}
	
	function handleFormSubmit(event) {
		event.preventDefault();
		var $this = $(this);
		var data = $this.serialize();
		$.post($this.attr('action'), data, function(data) {
			polledEl.load(window.location.href+' #content .polled .inner', function() {
				renderChart(polledEl.find('.results'));
			});
		});
		return false;
	}
	
	prepareForm();
});
