/*********************************
Javascript Document for Kenny BrandMuse
©2008 cisforculture. All rights reserved. Forget it, we'd sue!!!
Scope: Poll page

************
META-DATA
************
@ date created :: 26 Apr 2008
@ last modified :: 26 Apr 2008
@ description :: Contains client-side logic for the Polls page :)
*/
$(document).ready(function(){
		
		var animating = false;
		
		$("input#submit_btn").click(function(){
										
										var answer = $("input[type='radio'][checked]").val();
										
										if(!answer)
											alert('Select an option');
										else{
											hide();
											submitVote(answer);
										}
									});
	
		function hide(){
			
			animating = true;
			$("#answers-holder").slideUp("slow", function(){$(this).html("<p>&nbsp;</p><p class='yellow'><img src='/assets/images/icons/busy.gif' class='imgLeft' /> Submitting your vote...</p>")}).slideDown("slow");
		}
		
		function submitVote(answer){
			
			//Instantiate new XMLHttpRequest Object
			xhr = new XMLHttpRequest();
			xhr.open("POST","/extensions/poll.php?cb="+Math.random(),true);
			xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			
			if(xhr.overrideMimeType)
				xhr.setRequestHeader("Connection","close");
				
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					var obj = eval("("+xhr.responseText+")");
					onSubmitVoteResult(obj);
					
					//Avoid memory leaks
					xhr = null;
				}
				
			}
			xhr.send("value="+answer);
			
		}
		
		function onSubmitVoteResult(obj){
			
			
			
			if(obj.status == "true"){
				
				if(animating){
					
					setTimeout(function(){
					$("#answers-holder").html("<p>&nbsp;</p><p>Thanks for sending in your vote. <a href='/pages/poll.results.php'>Click here to view poll results</a></p>");
										},2000);
				}

				//return;
				//document.location.href = "/pages/current.poll.php";
			}
				
			else{
				alert(obj.message);
				document.location.href = "/pages/current.poll.php";
			}
		}
		
		
		var interval = 1000;
		var pollResultsWidth = parseInt($("#poll-results").css("width"));
		
		$(".poll-bar").each(function(i){
								
								//Recompute width in pixels
								var widthPixels = (parseInt($(this).css("width")) / 100) * pollResultsWidth;
								
								//Hide and Set the width in pixels
								$(this).css("visibility","hidden").css("width", widthPixels+"px");
								
								//Obtain initial width
								var initWidth = $(this).css("width");
								
								//set width to 0 and show	
								var thisObj = $(this).css("width","0px").css("visibility","visible");
																
								setTimeout(function(){
												//console.dir(this);
												thisObj.animate({width:initWidth},1000);
											},
											interval
											);
								
								interval += 1000;
								
							});
		
						   
});
