/**
 * FileName: survey.js
 * Version: 1.0 
 * Creation Date: 2011/06/14 - 16:14
 * Description: Create graphics and events.
 * Author: hcamargo 
 **/
 
$(document).ready(
	function() {		
		var _answer = '';
		var _survey = '';
		//Submit answer
		$('input[type=button][name=vote]').click(
			function() {
				var cont = 0;
				$('input[type=radio]').each(function (idx){
					if ($(this).is(':checked')){
						cont = 1;
						_answer = $(this).val();
						_survey = $('input[type=hidden][name=id_survey]').val();
						$('input[type=hidden][name=id_answer]').val($(this).val());
					}
				});
				if(cont == 0){
					alert("Debe seleccionar una respuesta");
					return false;
				}else{					
					var _frm = $(this).parents('form').get(0);		
					var _height = $("#poll-container").height();
					$("#poll-container").css("height",_height);
					$("#poll-container").empty();
					$.ajax({ 
						url: '/cgi-bin/survey.pl',
						async: false, 
						data: $(_frm).serialize(),
						type: 'POST', 
						cache: false, 
						success: function(data, textStatus) {
							//$("#poll-container").empty();
							$("#poll-container").append(data).fadeIn("slow",function(){
    								animateResults();
    								//Create cookies(name,value,expires)
 								$.cookie('Answer', _answer, {expires: 365});
 								$.cookie('Survey', _survey, {expires: 365});
							});
						} 
					});					 							
				}
			}
		);
});

function animateResults(){
  var tSize = 0;
  var grap = 0;
  var percentage = 0;
  var arraySizes = [];
  var count = 0;
  //Each to get % or votes and saved in an arrar
  $("#poll-results div").each(function(){
  $("poll-results").css('height','200px');
      percentage = parseInt($(this).next().text());
	if(percentage > tSize){
		tSize = percentage;
	}
	arraySizes[count] = percentage;
	count++;
  });
  //Each to put size of the bar with % or votes
  var count_ = 0;
  $("#poll-results div").each(function(){
	grap = (arraySizes[count_] * 95) / tSize;
      $(this).css({width: "0%"}).animate({width: grap}, 'slow');
      count_++;
  });
}
