var answer = 0;
var correct = 0;
var incorrect = 0;

$(document).ready(function(){
	setUpQuestion();
	$("#answer").keypress(function(event) {
		if (event.keyCode == '13') {
			if (answer == $("#answer").val()) correct = correct + 1;
			else incorrect = incorrect + 1;
			setUpQuestion();
		}
	});
});


function setUpQuestion() {

	/* select numbers */
	var l = 11;
	var n1 = 0;
	var n2 = 0;
	var t = 0;
	var o = " ? ";

	/* create the question and calculate the answer */
	switch(Math.floor(Math.random()*4)) {
		case 0 : 
			n1 = Math.floor(Math.random() * 100);
			n2 = Math.floor(Math.random() * 100);
			o = " + ";
			answer = n1 + n2;
			break;
		case 1 :  
			n1 = Math.floor(Math.random() * 100);
			n2 = Math.floor(Math.random() * 100);
			o = " - ";
			/* prevent negative answers */
			if (n1 < n2) {
				t = n1;
				n1 = n2;
				n2 = t;
			}
			answer = n1 - n2;
			break;
		case 2 :  
			n1 = Math.floor(Math.random() * 13);
			n2 = Math.floor(Math.random() * 13);
			o = " x ";
			answer = n1 * n2;
			break;
		case 3 :  
			o = " / ";
			/* avoid division questions with 0 in them */
			while (n1 == 0) n1 = Math.floor(Math.random() * 13);
			while (n2 == 0) n2 = Math.floor(Math.random() * 13);
			/* make sure the answer is a whole number */
			t = n1 * n2;
			answer = n1;
			n1 = t;
			break;
		default : break;
	}

	var th = n1 + " ";
	var tt = " " + n2 + " = "
	var q = th + o + tt + "<input type=\"text\" id=\"answer\"/>";
	
	/* draw question */
	$("#question").empty();
	$("#question").append(q);
	$("#answer").empty();
	
	/* draw results */
	
	var r = "correct: <span id=\"correct\">" + correct 
		+ "</span>, incorrect: <span id=\"incorrect\">" + incorrect
		+ "</span>";
	$("#results").empty();
	$("#results").append(r);
	
	$("#answer").focus();
	$("#answer").keypress(function(event) {
		if (event.keyCode == '13') {
			if (answer == $("#answer").val()) correct = correct + 1;
			else incorrect = incorrect + 1;
			setUpQuestion();
		}
	});
}

