function vote( iPollId, iAnswerId, oParent ) {
	if( iAnswerId > 0 && iPollId > 0 ) {
		$.ajax({
			type : 'POST',
			url : '/poll/vote',
			dataType : 'json',
			data : {id_poll:iPollId, id_answer:iAnswerId},
			success : function(json){
				if( json.code == 0 ) {
					alert( 'Już brałeś udział w tej ankiecie' );
				} else {
					updatePoll( oParent, json );
				}
			}
		});
	} else {
		alert( 'Nie wybrałeś odpowiedzi' );
	}
}

function updatePoll( oObject, json ) {
	oPollContainer = oObject.find( 'div.poll ul' );
	oPollContainer.find( 'li.ans' ).each(function(i){
		oAnswer = json.poll.answers[ i ];
		$( this ).empty();
		$( this ).html(
			'<span>' + oAnswer.answer + ', <ins>' + oAnswer.pct + '% (' + oAnswer.votes + ' głosy)</ins></span><p><span class="bar"></span></p>'
		);
		$( this ).find( 'span.bar' ).hide().animate( {width: oAnswer.pct + '%'}, 1500 );
	});
	oObject.find( 'div.poll ul button' ).remove();
	oObject.find( 'li.votes span' ).text( json.poll.vote_count );
}

$( document ).ready( function(){
	/**
	 * Bind an onclick event to every poll submit button on the page
	 **/
	$( '.poll button' ).bind( 'click', function(){
		oParent = $( $( this ).parents( 'form' ) );
		iPollId = parseInt( oParent.find( 'input[type="hidden"]' ).val() );
		iAnswerId = parseInt( oParent.find( ':radio:checked' ).val() );
		if( iAnswerId > 0 && iPollId > 0 ) {
			vote( iPollId, iAnswerId, oParent );
		}
		return false;
	});
});