// Global variable definitions
// DB column numbers
var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;

var votedID;
var poll_show_results = 0;

$(document).ready(function(){
  // setup the submit handler
  $(".poll_form").submit(poll_form_process); 

 /*
 if ($.cookie('vote_id')) {
    $("#poll-container").empty();
    votedID = $.cookie('vote_id');
    $.getJSON("poll.php?vote=none",loadResults);
  }
*/
});

function poll_form_process(event){
  event.preventDefault();

  $form = $(this);

  var poll_id = $form.find("input[name='pollid']").attr("value");
  var option_id = $form.find("input[name='optionid']:checked").attr("value");  
  if (option_id || poll_show_results) {
    $("#poll_wrapper_" + poll_id).slideUp("slow", function() {
      var params = $form.serialize();
      $form.empty();
  
      $.ajax({
        type: "POST", 
        url: lang_prefix + "/ajax/poll-vote", 
    	  data: params, 
    	  dataType: "json",
    	  success: function(json){ 
      		if(json.type == 'success') {
      		  $('#poll_wrapper_' + poll_id).html(json.html).slideDown();
      		  poll_animate_results();
          } else if(json.type == 'error') {
            alert(json.message); 
          }
    		} 
    	});	
      
      //$.cookie('vote_id', id, {expires: 365});
      });
  }
  return false;
}

function poll_results(form) {
	poll_show_results = 1;
	$('#' + form).submit();
}


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