jQuery(function($) {
	if (fpglobals.loggedIn == false) {
		//If the user is not logged in, update the poll immediately.
		update();		
	}
	
	function hideMessages()
	{
		//Remove all errors and alerts for the poll.
			$('#poll')
				.parent()
				.find('.error, .messageAlert')
				.remove();
	}
	
	function ShowAfterUpdate()
	{
		//The function to call after the poll results have been loaded via ajax.
		$('.option_percent').each(function(){
			//Storage the percent value.
			var percent = $(this).text();
		
			//Traverse to the target. 
			var TargetBar = $(this).parent().next().find('img');
			
			//Set its width to zero.
			TargetBar.css('width','0');
		
			//Now animate the bar to its target percent value.
			TargetBar.animate({width: percent}, {duration: 2000, easing: "swing", queue: false});
		
		});
		
			
		
	}
	
	function DoBeforeUpdate(form){

		
	}
	
	function update(callback)
	{
		var form = $('#poll_form');
		DoBeforeUpdate(form);
		
		if (form.length > 0) {
			//Split apart the form action and isolate the poll id.
			var urlPieces = form.attr('action').split('vote/');
				 urlPieces = urlPieces[1].split('/');
			var pollId = urlPieces[0];
			
			if (callback === undefined) {
				
				//Define a callback function to be performed after ajax query.
				callback = function (data, textStatus) {
					//Scoop out the form element from the response. 
					var UpdatedPoll = $(data).find('form');
					//Inject it into the #poll layer.
					$('#poll').html(UpdatedPoll);
					
					ShowAfterUpdate();
				};
			}
			
			
			
			//Override the action url.			
			var CacheBuster = (new Date()).getTime();
			var url = '/ajax/poll/view/' + pollId + '/?nocache=' + CacheBuster;
			
			$.get(url, null, callback);
		}
	}
	
	//submit form
	$('#poll_form .button').live('click', function() {
		//Placeholder
		var jThis = $(this).parents('form:first');
		
		//Override the form's default action link.
		var action = jThis.attr('action').substr(fpglobals.baseurl.length);
		var ActionWasntOverridden = action.substr(0, 5) !== '/ajax';
		
		if (ActionWasntOverridden == true) {
			var AjaxAction = fpglobals.baseurl + 'ajax/' + action;
		}else{
			//Just a fail safe.  It can't ever  be NOT overridden. 
		}
		
		var SubmitButton = jThis.find('.button');
		
		//Disable the submit button to prevent double submit
		SubmitButton.attr('disabled','true');

		jThis.ajaxSubmit({
			url: AjaxAction,
			resetForm: true,
			beforeSubmit:function(formData, jqForm, options){
				//Display an ajax loader gif.
				jThis.before('<img width="32" height="32" id="ajax-loader" alt="Loading..." src="/images/ajax-loader.gif"/>');
				
			
				return true; 
			},			
			success: function(text) {					
				var ThereIsAnError = text.search('error') > -1;
				
				function ShowMessage(){
						//Remove linebreaks from the response text to be cleanly.
						text = text.replace(/[\n]/g,'');
						
						var Message = $(text);
	
						//Hide prior messages.
						hideMessages();
						
						//Insert this message before the Poll.
						$('#poll').before(Message);												
				}
				
				if (ThereIsAnError == false) {					
					//Show thank you message...
					ShowMessage();
					
					//And display the results of this poll.					
					update();
					
				} else {
					// There is an error.
					ShowMessage();
					
					//And, once again, display the results of this poll.
					update();
					
				}
				
				//Enable the submit button
				SubmitButton.attr('disabled','');
				
				
				//Remove the ajaxloader gif.
				jThis.parent().find('#ajax-loader').remove();
			}
		});

		return false;
	});
	
});
