$(function(){
	var loader=$('#loader-poll');
	var pollcontainer=$('#pollcontainer-poll');
	loader.fadeIn();
	if (typeof(idpoll)=='undefined') {idpoll=0;}
	//Load the poll form
	$.get('/s-poll/', 'p='+idpoll, function(data, status){
		pollcontainer.html(data);
		animateResults(pollcontainer);
		pollcontainer.find('#viewresult-poll').click(function(){
			//if user wants to see result
			loader.fadeIn();
			$.get('/s-poll/', 'result=1&p='+idpoll, function(data,status){
				pollcontainer.fadeOut(1000, function(){
					$(this).html(data);
					animateResults(this);
				});
				loader.fadeOut();
			});
			//prevent default behavior
			return false;
		}).end()
		.find('#pollform').submit(function(){
			var selected_val=$(this).find('input[name=poll]:checked').val();
			if(selected_val!=''){
				//post data only if a value is selected
				loader.fadeIn();
				$.post('/s-poll/', $(this).serialize(), function(data, status){
					$('#formcontainer').fadeOut(100, function(){
						$(this).html(data);
						animateResults(this);
						loader.fadeOut();
					});
				});
			}
			//prevent form default behavior
			return false;
		});
		loader.fadeOut();
	});
	
	function animateResults(data){
		$(data).find('.bar-poll').hide().end().fadeIn('slow', function(){
							$(this).find('.bar-poll').each(function(){
								$(this).show();
								var bar_width=$(this).css('width');
								$(this).css('width', '0').animate({ width: bar_width }, 1000);
							});
						});
	}
	
});
