window.addEvent('domready', function()
{
	var toggleEnabled = false;
	if($('poll-submit') != null)
	{
		$('poll-submit').addEvents
		(
			{
				click: function()
				{
					var optVal = $$('input[name="vote"]:checked');
					if(optVal == '')
					{
						$('poll-error').set('html', 'Please select an option');
					}
					else
					{
						var optionValue = optVal.get('value');
						var request = new Request.JSON
						(
							{
								url: '/json/poll/vote/' + optionValue,
								onComplete: function(jsonObj)
								{
									if(jsonObj.poll)
									{
										$('poll-body').setStyle('height', $('poll-body').getProperty('height')).empty();
										var pTag = new Element('p', {'class': 'strong', 'text': jsonObj.poll.title});
										$('poll-body').adopt(pTag);
										if(jsonObj.Error == 1)
										{
											var pTag = new Element('div', {'class': 'notice', 'html': jsonObj.ErrorMsg});
											$('poll-body').adopt(pTag);
										}
										var totalVotes = jsonObj.poll.totalVotes;
										jsonObj.options.each(function(obj) {
											var roundedWidth = Math.round((parseInt(obj.votes) / parseInt(totalVotes)) * 100);
											var divEl = new Element('div', {'class': 'option-resultstext', 'text': obj.value + ': ' + roundedWidth + '%'});
											$('poll-body').adopt(divEl);
											var divEl = new Element('div', {'class': 'option-resultsbar'});
											var resultWidth = (roundedWidth == 0) ? '1px' : roundedWidth + '%';
											divEl.setStyle('width', resultWidth);
											$('poll-body').adopt(divEl);
										});
									}
								}
							}
						).send();
						//$('poll-body').empty();
					}
	
					return false;
				}
			}
		);
	}
});