// Global variable definitions
// DB column numbers

var votedID;

$jq(document).ready(function(){
	$jq("#poll").submit(saveResponse); // setup the submit handler

	if ($jq("#poll-results").length > 0 ) {
		animateResults();
	}

	showQuestion();
});


function showQuestion() {
	$jq.getJSON('/all/cn/infocenter/jquerypoll/poll.php?callback=?', function(data) {
		var fieldname = 'poll_' + data.questionid;
		var fieldtype = data.fieldtype[data.questionid];
		var snippet = '<form id="poll" action="" method="post" accept-charset="utf-8">' + 
		'<h3>' + data.questionname[data.questionid] + '</h3>';
		for( i in data.choicename ){
			snippet = snippet + '<label for="opt' + i + '"><input type="' + fieldtype + '" name="poll_' + data.questionid + '" value="' + i + '" id="opt' + i + '" /> ' + data.choicename[i] + '</label><br />' + "\n";
		}
		snippet = snippet + '<input type="hidden" name="pollID" id="pollID" value="1" /><input type="hidden" name="questionID" id="questionID" value="'+data.questionid+'" />' + 
		'<input type="button" id="pollbutton" onclick="saveResponse(\'' +fieldname + '\');" />' + 
		'<div style="clear: right;"></div></form>';

		$jq('#poll-container').html(snippet);
	});
}


function saveResponse(fieldname) {
	//event.preventDefault();
	var questionID = $jq("#questionID").val();
	var validate = checkVal();
	if(false === validate){
		return false;
	} else {
		var fieldval = $jq("input[name="+fieldname+"]:checked").val();
		var pollID = $jq("#pollID").val();
		var votedID = fieldval;
		$jq("#poll-container").fadeOut("slow",function(){
			$jq(this).empty();
			$jq.getJSON('/all/cn/infocenter/jquerypoll/poll.php?callback=?&pollID='+pollID+'&questionID='+questionID+'&responseID='+fieldval,loadResults);
		    $jq.cookie('vote_id', fieldval, {expires: 365});
		    $jq.cookie('question_id', questionID, {expires: 365});
		});
		return true;
	}
}


function animateResults( container ){
	$jq( container ).each( function(){
		var percentage = $jq( this ).next().text();
		$jq( this ).css({ width: "0%" }).animate({
			width: percentage}, 'slow' );
	});
}


function loadResults(data) {
	var results_html = "<div id='poll-results'><p>\n";
	results_html = results_html + data.ResultTxt + '</p></div>\n';
  
	$jq("#poll-container").append( results_html ).fadeIn( "slow",function(){
		animateResults( "#poll-results div" );
	});
}


function checkVal(){
	var checkcount = $jq("input:checked").length;
	if(checkcount == 0){
		alert("Please select one of the answers before submitting.");
		return false;
	} else {
		return true;
	}
}

