
jQuery(function($){
	
	var $poll = $('#poll');
	if (!$poll.length) return;	 // abort if no poll on page
	
	var $result = $('#poll-results');
	var $results = $('#poll-results .poll-result');
	var $form = $('#poll-form');
	var $vote = $('#vote');
	var $options = $('#poll-form input:radio');
	
	// parse classes for votes and total votes (+ converts to Number)
	var total = +$result.attr('class').match(/total-(\d+)/)[1];
	var votes = $.map($results, function(el){
		return +el.className.match(/votes-(\d+)/)[1];
	});
	
	var poll_id = $form[0].pollID.value;
	var unique_id = Math.round(Math.random() * 360 * 60);
	var vote_cookie = 'nikeos.userVote';
	var poll_cookie = 'nikeos.pollId'; 
	
	var voted = $.cookie(poll_cookie) == poll_id && $.cookie(vote_cookie);
	
	if (voted){		// user already voted
		
		showResults();
	
	} else {		// user has not voted yet
		
		$vote.click(function(){
			if (voted || !$options.is(':checked')) return false;
			voted = true;
			var chosen = +$options.filter(':checked').val();	// integer
			
			var body = new SOAPObject('addAnonymousVote');
			body.ns = 'http://jivesoftware.com/webservices';
			
			body.appendChild(new SOAPObject('pollID')).val(poll_id);
			body.appendChild(new SOAPObject('index')).val(chosen);
			body.appendChild(new SOAPObject('uniqueID')).val(unique_id);
			
			var request = new SOAPRequest('/rpc/soap/PollService', body);
			SOAPClient.SOAPServer = '/rpc/soap/PollService';
			
			SOAPClient.SendRequest(request, function(response){
				if (response){
					$.cookie(vote_cookie, unique_id, { path: '/', expires: 3 });
					$.cookie(poll_cookie, poll_id,   { path: '/', expires: 3 });
				}
				showResults(chosen);
			});
			
			$options.attr('disabled', true);

			return false;
		});
		
	}
	
	function showResults(chosen){
		if (chosen != null){
			total++;
			votes[chosen]++;
		}
		
		$results.each(function(i){
			var $this = $(this);
			var percent = total ? Math.round(100 * votes[i] / total) + '%' : '0%';
			
			var $bar = $this.find('.poll-bar div').css('width', 0);
			var text = $this.find('.poll-percentage')[0];
			
			// stagger fx
			setTimeout(function(){
				$bar.animate({width: percent}, {
					easing: 'easeOutQuad',
					step: function(now, fx){
						text.innerHTML = Math.round(now) + fx.unit;
					}
				});
			}, (i + 1) * 250);
		});
		
		$form.hide();
		$result.show();
	};
	
});

jQuery.extend(jQuery.easing, {
	easeOutQuad: function(x, t, b, c, d){
		return -c *(t/=d)*(t-2) + b;
	}
});

