$(document).ready(function(){
	$("#poll").submit(formProcess); // setup the submit handler
  
	if ($("#poll-results").length > 0 ) {
		animateResults();
	}

	//alert('cookie: ' + $.cookie("pipe_enquete")) ;	
  
	if ($.cookie('pipe_enquete')) {
  
		$.get('enquete/pegaidenquete.php',       			// Retorna valor da enquete ativa 
			function(retorno){
				if($.cookie('pipe_enquete') == retorno) {  	// O cookie eh desta enquete
					$("#poll-container").empty();
					$.getJSON('enquete/poll.php', {'vote' : 'none', 'idenquete':retorno}, loadResults);
				}
				
			});
	
	}

 
});

	
function formProcess(event){
  event.preventDefault();
  
  var id = $("input[@name='poll']:checked").attr("value");
  id = id.replace("opt",'');
  
  $("#poll-container").fadeOut("slow",function(){
    $(this).empty();
    
    votedID = id;
    $.getJSON("enquete/poll.php?vote="+id,loadResults);
    // O cookie estah sendo setado no php
    //$.cookie('pipe_enquete', id, {expires: 365});
    });
}


function animateResults(){
  $("#poll-results div").each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
  });
}

function loadResults(data) {
	var total_votes = 0;
	var percent;
	var pergunta;
  
	for (id in data) 
	{
    total_votes = total_votes+parseInt(data[id].valor);
	pergunta = data[id].pergunta ;
	}
  
  
	var results_html = "<div id='poll-results'><h3>" + pergunta  + "</h3>\n<dl class='graph'>\n";
	for (id in data) 
	{
		percent = Math.round((parseInt(data[id].valor)/parseInt(total_votes))*100);
		results_html = results_html+"<dt class='bar-title'>"+data[id].nome+"</dt><dd class='bar-container'><div id='bar"+data[id].idenqueteopcoes+"'style='width:0%;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
		//  results_html = results_html+"<dt class='bar-title'>"+data[id][OPT_TITLE]+"</dt><dd class='bar-container'><div id='bar"+data[id][OPT_ID]+"'style='width:0%;background-color:#0066cc;'>&nbsp;</div><strong>"+percent+"%</strong></dd>\n";
	}
  
	results_html = results_html+"</dl><p>Total de votos: "+total_votes+"</p></div>\n";
  
	$("#poll-container").append(results_html).fadeIn("slow",function(){
		animateResults();});
}