var OPT_VOTES = 0;
var OPT_TITLE = 1;
var OPT_PERCENT = 2;

function vote(poll_id) {
	if (poll_id > 0) {
		// if poll id > 0 then send request to poll.php
		 var vote_id = $("input[@name='poll_vote_"+poll_id+"']:checked").val();
		 if (vote_id > 0) {
			$("#poll_res_"+poll_id).fadeOut("slow",function(){ 
				$(this).empty();
				$.getJSON("/poll.php?vote_id="+vote_id+"&poll_id="+poll_id, loadResults);
				$.cookie('poll_id_'+poll_id, poll_id, {expires: 365});
				$("#vote_btn_"+poll_id).hide();
				$("#vote_thx_"+poll_id).show();
			}); 
		 } else {
			alert("select your option"); 
		 }
	} else {
		alert('internal poll error');
	}
}

$(document).ready(function(){
  
	$(".poll-container").each(function() {
		// for each poll check session and display results if not voted
		var poll_id = $(this).attr('id');
		poll_id = poll_id.replace("poll_",'');
		
		if ($.cookie('poll_id_'+poll_id)) {
			$("#poll_res_"+poll_id).empty();
			poll_id = $.cookie('poll_id_'+poll_id);
			$("#vote_btn_"+poll_id).hide();
			$("#vote_thx_"+poll_id).show();
			$.getJSON("/poll.php?poll_id="+poll_id+"",loadResults);
		}
	});
  
  if ($("#poll-results").length > 0 ) {
    animateResults();
  }
});


function animateResults(){
  $(".poll_results_chart_graph").each(function(){
      var percentage = $(this).children('span').text()+'%';
      $(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
  });
}

function loadResults(data) {
  var qNumber = data['data'].length;
  var results_html = '<div class="poll_results_chart"><div class="poll_results_chart_inner">';
  var poll_id = data['poll']['id'];

  if (qNumber > 0) {
	  for (var i = 0; i < qNumber; i++) {
		 var votes = data['data'][i]['votes'];
		 var title = data['data'][i]['name'];
		 var percent = parseInt(data['data'][i]['percent']);
		 
		 results_html += "<div class='poll_results_chart_option'><div class='poll_results_perc'>"+percent+"%</div><div class='poll_results_chart_graph_wrapper'><div class='poll_results_chart_graph'><span>"+percent+"</span></div></div><div class='poll_results_chart_graph_desc'>"+votes+" votes</div></div>";
	  }
	  results_html += "</div></div>";
  }

  	$("#poll_res_"+poll_id).html(results_html).fadeIn("slow",function(){
  		animateResults();
 	});
}


$(document).ready(function(){ 
	$("#navigation li.parents:not(:last-child)").append("<span></span>"); 
	$("#navigation li.drop").mouseover(function() { 
		$(this).find("ul.subnav").show(); 
 
		$(this).hover(function() {
		}, function(){
			$(this).find("ul.subnav").hide('fast');  
		});

		}).hover(function() {
			$(this).addClass("subhover");
		}, function(){	
			$(this).removeClass("subhover");
	});

});  

