jQuery(document).ready(function() {
	var path_to_items = '#poll_content #poll_body input[name="poll_' + poll_pk + '"]';
	var body = jQuery('#poll_body');
	
	function showResults(data) {
		var all_points = 0, total = 0, biggest = 0;
		
		body.hide('slow', complete=function() {
			body.empty();
			jQuery.each(data, function(index, value) {
				if(index != 'total') {
					if(data[index]['count'] > biggest) {
						biggest = data[index]['count'];
					}
					all_points += data[index]['count'];
				}
			});
			
			jQuery.each(data, function(index, value) {
				if(index == 'total') {
					total = value;
				} else {
					var percentage = (data[index]['count'] * 100) / all_points;
					var bar_class = 'normal_bar';
					
					if(data[index]['count'] == biggest) {
						bar_class = 'max_bar';
					}
					
					var points_txt = '';
					if(show_points) {
						points_txt = '<sup>(' + data[index]['count'] + ')</sup>'; 
					}
					
					body.append('<dl id="poll_item_dl">');
					body.append('<dt>' + data[index]['title'] + ': <strong>' + (Math.round(percentage*100)/100) + '%</strong>' + points_txt + '</dt>');
					body.append('<dd><div id="bar" class="' + bar_class + '" style="width: ' + percentage + '%;"></div></dd>');
					body.append('</dl>');
				}
			});
			
			var total_points_txt = '';
			if(show_points) {
				total_points_txt = '<sup>(' + all_points + ')</sup>'; 
			}
			
			body.append('<div id="voters_count">' + trans_total_voters + ': <span id="total">' + total + '</span> ' + total_points_txt + '</div>');
		}).show('slow');
	}
	
	function RecognizeAndPrepare() {
		var result = '';
		
		jQuery(path_to_items).map(function() {
			if((this.type == 'checkbox' || this.type == 'radio') && this.checked) {
				result += '"' + this.id + '": ' + '"' + this.type + '",';
			}
			if(this.type == 'text' && this.value != '') {
				result += '"' + this.id + '": ' + '"' + this.value + '",';
			}
		})
		
		if(result.length > 0)
			if(result[result.length - 1] == ',')
				result = result.substring(0, result.length - 1);
		
		return '{' + result + '}';
	}
	
	jQuery(path_to_items).bind('focusin click', function() {
		if(poll_type == 'single') {
			var selected = this;
			
			jQuery(path_to_items).map(function() {
				if(this != selected) {
					if((this.type == 'checkbox' || this.type == 'radio') && this.checked) {
						this.checked = false;
					}
					if(this.type == 'text' && this.value != '') {
						this.value = '';
					}
				} 
			});
		}
	});
	
	function doResults() {
		jQuery.get(result_url, function(data) {
			showResults(jQuery.parseJSON(data));
		});
	}
	
	jQuery("#sendvote").click(function() {
		var result = RecognizeAndPrepare();
		
		if(result == '{}') {
			alert(trans_select_something);
		} else {
			body.hide('slow', complete=function() {
				jQuery.get(vote_url, {'chosen_items': result}, function() {
					doResults();
				});
			});
		}
	});
	
	jQuery("#showresults").click(function() {
		doResults();
	});
});
