// $Id: index.js 76 2009-01-06 13:12:39Z csl $

function newRound()
{
	$('#beta').html("Press <b>ENTER</b> to pass a question.");
}

function resetQuestions()
{
	q = null;
	score = {'correct': 0, 'total': 0};
	updateScore();
}

function questionsFinished()
{
	var text = 'You have completed the quiz!';
	text += '<p>You scored ' + score.correct + ' out of ' + score.total + '</p>';
	$('#questionText').html(text);
	$('#questionText').show('fast');
	$('#answerText').val('');

	resetQuestions();
	$('#score').text('');
	$('#beta').html("Press <b>ENTER</b> to start a new round.");
}

function passQuestion()
{
	// todo: write correct answer
	nextQuestion();
}

function updateScore()
{
	var no = ( q != undefined ) ? 1 + q.index : 1;
	var  s = 'Question ' + no + ' of ' + score.total;
	    s += ' &mdash; ' + score.correct + ' points';
	$('#score').html(s);
}

function nextQuestion()
{
	$('#questionText').slideUp('fast', function() {
		$.getJSON('json/jsonGetQuestion.php', function(e) {
			q = e;
			score.total = q.total;

			if ( q.index >= q.total ) {
				questionsFinished();
				return;
			}

			if ( q.index == 0 ) {
				newRound();
			}

			updateScore();

			$('#questionText').html(q.question.text);

			$('#questionText').show('fast', function() {
				$('#answerText').val('');
				$('#answerText').focus();
			});
		});
	});
}

function correctAnswer()
{
	score.correct += 1;
	updateScore();

	var answer = q.question.answers[0];
	$('#answerText').val(answer);

	nextQuestion();
}

function normalizeString(s)
{
	return s.toLowerCase().replace(new RegExp("[^a-z0-9]", "g"), "");
}

function compareAnswersLoosely(p, q)
{
	return normalizeString(p) == normalizeString(q);
}

// this is the main driver
$(document).ready(function()
{
	nextQuestion();

	$('#answerText').bind('keyup', function(e)
	{
		var answer = $('#answerText').val();

		var key = (e) ? e.which : e.keyCode;

		// pass question on ENTER
		if ( answer.length == 0 && (key == 13 || key == 10) ) {
			nextQuestion();
			return;
		}

		if ( answer.length == 0 ) {
			return;
		}

		var lastChar = answer.charAt(answer.length - 1).toLowerCase();
		var keyChar  = String.fromCharCode(key).toLowerCase();

		if ( lastChar != keyChar ) {
			// When user hits two keys almost simultaneously,
			// we have the two keys in var answer, but TWO
			// key events to process.  With this check, we
			// throw away the first keyup event, so we won't
			// jump over questions.
			return;
		}

		for ( var i=0; i < q.question.answers.length; ++i ) {
			var question = q.question.answers[i];

			if ( compareAnswersLoosely(answer, question) ) {
				correctAnswer();
				return;
			}
		}
	});
});

resetQuestions();
