var Poll = new Class({
	
	pollForm : null,
	pollDiv  : null,
	
	initialize: function()
	{
		this.pollDiv  = $('poll');
		if($defined(this.pollDiv))
		{
			this.pollForm = this.pollDiv.getElement('form#poll-form');
		}
	},
	
	addFormBehaviour : function()
	{
		if (this.pollForm == null) return false;
		voteButton = this.pollForm.getElement('#vote');
		if (voteButton != null)
		{
			voteButton.addEvent('click', function(event) 
			{
				event.stop();
				
				answerID = null;
				this.pollForm.getElements('input[name=answer]').each(function(el) {
					if (el.get('checked'))
					{
						answerID = el.get('value');
						return;
					}
				});
				
				profileID = null;
				checkAnonymous = this.pollForm.getElement('input[name=anonymous]');
				if (checkAnonymous != null && !checkAnonymous.get('checked'))
				{
					profileID = this.pollForm.getElement('input[name=profileid]').get('value');
				}
				
				this.vote(answerID, profileID)
			}.bind(this));
		}
	},

	vote : function(answerID, profileID)
	{
		if (answerID == null)
		{
			return;
		}
		
		this.oJsonRequest = new Request.JSON({url: '/phplib/dataservice/poll/castvote.php', 
			onFailure: function()
			{
			},
			onSuccess: function(oJson) 
			{
				if (oJson.error != null && oJson.error.length > 0)
				{
					alert(oJson.error);
					return;
				}
				this.pollDiv.set('html', oJson.results);
			}.bind(this)
		}).send('data='+JSON.encode({'answerID' : answerID, 'profileID' : profileID }));
	}
});