$(function(){
	
	
	var serverScript = SERVER_DATA['__URLPATH__']+"/modules/polls/polls.php";
	var $polls = $(".poll");
	
	var showResults = function($poll,stats) {
		var minWidth = 30;
		var maxWidth =  $poll.find(".poll-answers").width() / 2.5;
		
		var vote_count_set = false;;
		for (var id in stats) {
			if (!vote_count_set) {
				$poll.find(".poll-vote-count").addClass("active").html("Broj glasova: <strong>"+stats[id].total+"</strong>");
				vote_count_set = true;
			}
			var $perc = $poll.find("#poll-answer-"+id+" .poll-vote-percentage");
			var $input = $poll.find("#poll-answer-"+id+" input:first");
			if ($perc.length > 0) {
				var percentage = stats[id].percentage;
				$perc.html(percentage+'%');
				$perc.width(minWidth+percentage/100*maxWidth);
				$perc.show();
				// $input.attr("disabled",true);
			}
		}
	}
	
	$polls.each(function() {
		
		var $poll = $(this);
		/*
		if ($poll.find("[name=voted]").val() > 0) {
			$poll.find(".poll-vote").addClass("disabled");
			$poll.find("input").attr("disabled",true);
		}
		*/
		
		$(this).find(".poll-results:first").click(function(){
			var $poll = $(this).closest(".poll");
			var id_poll = $poll.find("[name=id_poll]").val();
			$.post(serverScript,{action:'get_stats',id_poll:id_poll},function(data) {
					if (typeof data == 'object' ) {
						// $poll.find(".poll-answer input").hide();
						showResults($poll,data);
					} else if (data.error) {
						alert("Greška!");
					}
				},'json');
			
		});
		
		$(this).find(".poll-vote:first").click(function() {
			var $poll = $(this).closest(".poll");
			var id_poll = $poll.find("[name=id_poll]").val();
			var hash = $poll.find("[name=hash]").val();
			
			$answers = $poll.find("[name=answer]");
			if ($answers.length > 0) {
				var answerlist = [];
				$checked = $answers.filter(function() { return $(this).attr("checked"); });
				$checked.each(function() {
					answerlist.push( $(this).val() );
				});
				answerlist = answerlist.toString();
				$.post(serverScript,{action:'vote',id_poll:id_poll,hash:hash,ids:answerlist},function(data) {
					if (data.success) {
						// $poll.find(".poll-answer input").hide();
						
						showResults($poll,data.stats);
						
					} else if (data.error) {
						alert(data.message);
					}
				},'json');
			}
		});
	});
});
