$(document).ready(function() {
	
	$("input[id^='submitPoll_']").click(function(){
		var arrUId = this.id.split("_");
		var uId = arrUId[1];
		var vote = $("input[id^='pollVote_"+uId+"_']:checked");
		if(!vote.length) {
			$("#pollNoSelection_"+uId).show();
		} else {
			$("#pollQuestionContent_"+uId+", #pollNoSelection_"+uId).hide();
			$("#pollRecordingVote_"+uId).show();
			poll.vote(uId,vote.val());
		}
		return false;
	});
});// end $(document).ready()

poll = {
	pollID:0,
	vote:function(pollID,answerID) {
		this.pollID = pollID;
		$.ajax({
	        url: "/poll/Poll.cfc",
	        data: ({method:"vote", pollID:pollID, answerID:answerID, returnResults:1}),
	        success: function(response) {
				if(response.ERRORNO == 0) {
					poll.updateResults(response.RESULTS);
					//$("#pollThanks_"+pollID).show();
				} else {
					$("#pollRecordingVote_"+pollID).hide();
					$("#pollError_"+pollID).html("<p>"+response.ERRORMESSAGE+"</p>").show();
				}
	        },
	        error: function(XMLHttpRequest, textStatus) {
	        	$("#pollRecordingVote_"+pollID).hide();
	        	$("#pollError_"+pollID).html("<p>There has been a problem and we can't record your vote at this moment. Please try again later.</p>").show();
	        },
	        dataType: "json"
	    });
	},
	updateResults:function(results) {
		var answersLength = results.ANSWERS.length;
		for (i=0;i<answersLength;i++) {
			var answer = results.ANSWERS[i];
			$("#pollResultPercent_"+this.pollID+"_"+answer.ANSWERID).text(answer.PERCENT);
			//$("#pollResultTotal_"+this.pollID+"_"+answer.ANSWERID).text(answer.VOTES);
			$("#pollResultBar_"+this.pollID+"_"+answer.ANSWERID).attr("style","width:"+answer.PERCENT+"%");
		}
		/*if(results.TOTAL < 100)
			$("#pollTotalContainer_"+this.pollID).hide();
		else
			$("#pollTotal_"+this.pollID).text(results.TOTAL);*/
		$("#pollTotal_"+this.pollID).text(results.TOTAL);
		this.showResults();
	},
	showResults:function(){
		$("#pollQuestionContent_"+this.pollID+", #pollRecordingVote_"+this.pollID).hide();
		$("#pollResultContent_"+this.pollID).show();
	},
	resetDisplay:function() {
		$("#pollResultContent_"+this.pollID).hide();
		$("#pollQuestionContent_"+this.pollID).show();
	}
}
