$(function(){

	$.fn.ipoll = function(c) {
		var elm = $(this);
		
		$('.poll_opt_result_line').each( function() {
			var width = $(this).width() - 
						$(this).find('.poll_opt_result_label').width() - 
						$(this).find('.poll_opt_result_perc').width() - 
						20;
					
			if (width<=10) width = 175;
			
			var p = (width/100);
			var barwidth = Math.floor($(this).find('.poll_opt_result_bar').attr('rel') / p);
			
			var speed = (1500 - barwidth);
			
			$(this).find('.poll_opt_result_bar').animate({
				width: barwidth
			}, { duration: speed, queue: false});
		});
	};
	
	$.fn.savepoll = function(c) {
		var elm = $(this);
		var frm = elm.find('form');
		var poststr = '';
		
		frm.submit( function(e){
			e.preventDefault();
			
			frm.find('input[type!=submit][type!=radio][type!=checkbox], input[type=radio]:checked, input[type=checkbox]:checked, select, textarea').each( function(i){
				poststr += $(this).attr('name') + '=' + $(this).val() + '&';
			});
			
			poststr = poststr.substr(0, poststr.length-1);
			
			c.poststr = poststr;
			elm.savepoll_send(c);
		});
			
	};
	
	$.fn.savepoll_send = function(c) {
		var elm = $(this);
		c.poststr		= (c.poststr!==undefined) ? c.poststr : '' ;
		
		$.ajax({
			url: 'http://www.x-mo.nl/module/ajax/nl/polls_save?pid=' + c.cnt,
			dataType: 'json',
			data: c.poststr,
			type: 'POST',
			success: function(data){
				
				var result_html = '<div class="poll_opt_result" id="' + c.id + '">';
				
				$.each( data.items.votes, function(x, vote){
					var percentage = (vote.votes / (data.items.total / 100));
					
					result_html += 	'<div class="poll_opt_result_line">' + 
								'<div class="poll_opt_result_label">' + vote.title + '</div>' + 
								'<div class="poll_opt_result_bar" rel="' + Math.floor(percentage) + '"></div>' + 
								'<div class="poll_opt_result_perc">' + Math.floor(percentage) + '%</div>' + 
								'</div>';
				});
				
				result_html += '</div>';
				
				elm.children().remove();
				$(result_html).appendTo(elm);
				
				$('#' + c.id).ipoll({});
			}
		});
	};
});	
