Poll = {
	pollContainer: null,

	pollForm: null,

	init: function () {
		Poll.pollContainer = $('poll');
		if (Poll.pollContainer) {
			Poll.pollForm = Poll.pollContainer.getElement('form');
			if (Poll.pollForm) {
				Poll.pollForm.addEvent('submit', function(e) {
					e.stop();

					vote = Poll.pollForm.getElement('input[name="pollresult"][checked]');
					if (vote) {						
						Poll.sendVote(vote.value);
					} else {
						alert('Please select your vote');
					}
				})
			}
		}
	},

	sendVote: function (optionId) {
		new Request.JSON({
			url: "/polls/vote/option/" + optionId + "/",
			onSuccess: function (data, text) {
				if (data.valid) {
					// get rid of the form
					Poll.pollForm.destroy();

					var barColours = new Array();
					barColours[0] = "red";
					barColours[1] = "green";
					barColours[2] = "blue";
					barColours[3] = "orange";
					barColours[4] = "purple";

					var graph = new Element('dl');
					var colourIndex = 0;
					
					for (var resultIndex in data.results.options) {
						var result = data.results.options[resultIndex];

						if (colourIndex >= barColours.length) {
							colourIndex = 0;
						}

						graph.adopt(
							new Element('dt', {
								'text': result.title
							}),
							new Element('dd', {
								'class': barColours[colourIndex],
								'style': 'width: ' +result.percentage + 'px'
							}).adopt(
								new Element('span', {
									'text': result.percentage + '%'
								})
							)
						);

						colourIndex++;
					}
					
					Poll.pollContainer.getElement('div.internal').adopt(graph);
				}
			}
		}).get();
	},

	updateResults: function () {
		
	}
};

window.addEvent('domready', Poll.init);
