var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;
var votedID;
var t =  new Date().getTime();
$(function(){
  //$("#poll").submit(formProcess); // setup the submit handler
  $(".votingsubmit").click(function(){	
    //formProcess();
	var poll_container = "#poll-container" + $(this).attr("rel");
	var pollid = $(this).attr("rel");
    var id = $("" + poll_container + " input[@name='poll" + pollid + "']:checked").attr("id");
	if (id==null) 
	{
		return;
	}
    id = id.replace("opt",'');
    votedID = id;
//    $.getJSON("/DigitvisionModule/Digitvision.Portal.Voting/Voting.ashx?PollChoiceId=" + id + "&t=" + t + "",loadResults);    
    $.getJSON("/DigitvisionModule/Digitvision.Portal.Voting/Voting.ashx?PollChoiceId=" + id + "&t=" + t + "",
			 	function(data){
					// an div ket qua
					if ($("#poll-results"+pollid+""))
					 {
						$("#poll-results").remove();
					 }
					 // an div chua cau tra loi
					 if ($(poll_container))
					 {
						$(poll_container).remove();
					 }
					 
					 var total_votes = 0;
					 var percent;
					  
					 for (id in data) {
						total_votes = total_votes+parseInt(data[id][OPT_VOTES]);
					 }
					 var results_html = "<div id='#poll-results"+pollid+"' class='poll-results'>";
					  for (id in data) {
						var r = Math.floor(Math.random()*256);
 						var g = Math.floor(Math.random()*256);
 						var b = Math.floor(Math.random()*256);
						percent = Math.round((parseInt(data[id][OPT_VOTES])/parseInt(total_votes))*100);
						if (data[id][OPT_ID] !== votedID) {
						  results_html = results_html+"<p class='bar-title'>"+data[id][OPT_TITLE]+"</p><div class='bar-container'><div id='bar"+data[id][OPT_ID]+"' class='_garh' style='width:"+ percent +"%;background-color:" + getHex(r,g,b) + ";'>&nbsp;</div><span class='percent'>("+percent+"%)</span></div>\n";
						} else {
						  results_html = results_html+"<p class='bar-title'>"+data[id][OPT_TITLE]+"</p><div class='bar-container'><div id='bar"+data[id][OPT_ID]+"' class='_garh' style='width:"+ percent +"%;background-color:#0066cc;'>&nbsp;</div><span class='percent'>("+percent+"%)</span></div>\n";
						}
					  }
					  
					  results_html = results_html+"<p class='totalvotes'>Total: "+total_votes+"</p></div>\n";
					  
					  $("#poll" + pollid +"").append(results_html).fadeIn("slow",function(){
//						  animateResults()
					   });
				}
			 );    
   }); 
});

function animateResults(){
  $("#poll-results div").each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
  });
}
 function getHex(r, g, b){
 	return '#'+intToHex(r)+intToHex(g)+intToHex(b); 
 }
 function intToHex(n){
 	n = n.toString(16);
 	// eg: #0099ff. without this check, it would output #099ff
 	if( n.length < 2) 
 		n = "0"+n; 
 	return n;
 }
 