
var POINTS_GOOD = -1;
var POINTS_BAD  = -1;
var POINTS_HALL = 1;

var testLength = -1;
var questions;  // Contains array of base data about questions
var question;   // Contains current question
var qidx = -1;

var hallMessageShown = 0;

function startGame() {
	var testUrl = 'data/' + TEST_NAME + '/xml/test.xml';
	$.ajaxSetup({
		type: "GET",
		timeout: 30000
	});

	$.ajax({
		url: testUrl,
		dataType: "xml",
		error: function(xml, stat, err) {
			errorMessage( 'No se puede comenzar el test debido a un error interno', 'No se pudo cargar el fichero con las preguntas desde ' + testUrl );	
		},
		success: function(xml, stat ) {
			var credits = $("credits > *", xml);
			$("#dfooter").html( jq2html(credits) );

			var title = $("title", xml).text();
			$("#dtitle").html( title );
			POINTS_HALL = $("hall", xml).text();
			POINTS_GOOD = $("good", xml).text();
			POINTS_BAD  = $("bad", xml).text();
			$("#dtopsmall").html( '<p>Meta: ' + numFormat(POINTS_HALL) + ' puntos para el <a href="top.php?' + TEST_NAME + '">salón de la fama</a></p>' );

			testLength = $("question:last", xml).attr("num");
			questions = new Array(testLength+1);
			for( var i=1; i<=testLength; i++ ) {
				questions[i] = $("question:eq("+(i-1)+")", xml );
				questions[i].attr( "state", "unanswered" );
			}

			pickQuestion();
		}
	});

	$(window).keydown(function(event){
		switch( event.keyCode ) {
			case 65:
				if( qidx != -1 && questions[qidx].attr("state") == "unanswered" ) {
					doAnswer('A');
				}
				break;
			case 66:
				if( qidx != -1 && questions[qidx].attr("state") == "unanswered" ) {
					doAnswer('B');
				}
				break;
			case 67:
				if( qidx != -1 && questions[qidx].attr("state") == "unanswered" ) {
					doAnswer('C');
				}
				break;
			case 68:
				if( qidx != -1 && questions[qidx].attr("state") == "unanswered" ) {
					doAnswer('D');
				}
				break;
			case 13:
				if( qidx != -1 && questions[qidx].attr("state") != "unanswered" ) {
					pickQuestion();
				}
				break;
		}
	});

}

function randomQid() {
	return Math.floor(Math.random()*testLength+1);
}

function pickQuestion() {
	qidx = randomQid();
	while( questions[qidx].attr( "state" ) != "unanswered" ) {
		qidx = randomQid();
	}
	var question = questions[qidx];
	var qid = questions[qidx].attr("id");
	var qUrl = 'data/' + TEST_NAME + '/xml/' + (qid) + '.xml';


	$.ajax({
		async: false,
		url: qUrl,
		dataType: "xml",
		error: function(xml, stat, err) {
			errorMessage( 'Hubo un problema momentáneo al recuperar la pregunta.\nReintenta en algunos segundos', 'No se pudo cargar la pregunta desde ' + qUrl );	
			$("#nextQuestion").unbind( "click" );
			$("#nextQuestion").click( function() {
				$("#nextQuestion").unbind( "click" );
				pickQuestion();
			});
		},
		success: function(xml, stat ) {
			askQuestion( xml);
		}
	 });

	$("#dcomments").html( '<p>Haz click sobre tu respuesta.</p>' );
}
function askQuestion( qdata ) {
	question = qdata;
	var qtitle = $("question > title", question ).text();
	var qhtml = '<p class="qtitle">' + qtitle + '</p>';
	qhtml += '<ol class="answers">';
	var aletter = 'A';
	$("question > answer", question).map( function(idx) {
		var atitle = $("title", this).text();
		qhtml += '<li class="atitle" id="answer' + aletter + '" onclick="doAnswer(\'' + aletter + '\')">' + atitle + '</li>';
		aletter = String.fromCharCode( aletter.charCodeAt(0) + 1 );
	});
	qhtml += '</ol>';
	$("#dquestion").fadeOut( "fast", function() {
			$("#dquestion").html( qhtml );
			$("#dquestion").fadeIn("fast");
			var qimg = $("question > image", question ).text();
			if( qimg.length > 0 ) {
				$("#danswer").html( '<img class="qimg" src="img/' + TEST_NAME + '/' + qimg + '"/>' );
			} else {
				$("#danswer").html( ' ' );
			}
	});
}
function doAnswer( uletter ) {
	var chtml = '';
	var uhtml = '';

	var ctitle = '';
	var utitle = '';

	var isCorrect = 0;
	$("question > answer", question).map( function(idx) {
		var aletter = $("letter", this).text();
		var atype = $("type", this).text();
		var ans = $("#answer" + aletter);
		ans.css( { cursor: "text" } );
		ans.attr( "onclick", "" );

		if( atype == "G" ) {
			ans.css( { color: "green", textDecoration: "none" } );
		} else {
			ans.css( { color: "red", textDecoration: "line-through" } );
		}
		if( aletter == uletter ) {
			ans.css( { fontWeight: "bold" } );
		}
		if( atype == "G" && aletter == uletter ) {
			isCorrect = 1;
		}
		if( atype == "G" ) {
			ctitle = $("title", this).text();
			chtml  = $("content > *", this);
		} else if( uletter == aletter ) {
			utitle = $("title", this).text();
			uhtml  = $("content > *", this);
		}
	});

	$("#danswer").html( jq2html(chtml) );

	var ahtml = '';
	if( isCorrect ) {
		$("#danswer").prepend( '<p class="agood">¡Correcto! ' + ctitle + '</p>' );
	} else {
		$("#danswer").prepend( '<p class="arealgood">Respuesta: ' + ctitle + '</p>' );
		if( uhtml.length > 0 ) {
				$("#danswer").prepend( "<hr/>" );
				$("#danswer").prepend( jq2html(uhtml) );
				$("#danswer").prepend( '<p class="abad">Incorrecto: ' + utitle + '</p>' );
		} else {
				$("#danswer").prepend( '<p class="abad">Incorrecto</p>' );
		}
	}
	$("#danswer").fadeIn("fast");

	countScore( qidx, uletter, isCorrect );

	if( qgood + qbad < testLength ) {
		if( isCorrect ) {
				$("#dquestion").append('<p id="nextQuestionWrap"><a id="nextQuestion" class="nqgood">Siguiente &raquo;</a></p>');
		} else {
				$("#dquestion").append('<p id="nextQuestionWrap"><a id="nextQuestion" class="nqbad">Siguiente &raquo;</a></p>');
		}
	} else {
		$("#dquestion").html( '<p>Haz contestado las ' + testLength + ' preguntas disponibles, obteniendo en total <span class="agood">' + qgood + '</span> respuestas correctas y <span class="abad">' + qbad + '</span> incorrectas.</p>' );
	}
	$("#nextQuestion").click( function() {
		$("#nextQuestion").unbind( "click" );
		pickQuestion();
	});
}
var qgood = 0;
var qbad = 0;
function countScore( qid, answer, isCorrect ) {
	questions[qid].attr("answer", answer );
	questions[qid].attr("state", isCorrect );
	if( isCorrect ) {
		qgood++;
	} else {
		qbad++;
	}
	score = (POINTS_GOOD * qgood) + (POINTS_BAD * qbad);
	$("#dtopbox").html( '<p class="score">Puntos: ' + numFormat(score) + ' puntos</p>' );
	$("#dcomments").html( '<p>' + (testLength-qgood-qbad) + ' preguntas disponibles. Respuestas correctas: ' + qgood + ', incorrectas: ' + qbad + '.</p>' );

	if( score >= POINTS_HALL ) {
		$("#dtopsmall").html( '<p><strong>¡FELICITACIONES!<br/>Ya puedes <a id="dtopbtn" href="#">entrar al salón de la fama</a></strong></p>' );
		$("#dtopbtn").click( save );
		if( !hallMessageShown ) {
			alert( 'Ya tienes suficientes puntos para entrar al salón de la fama.\nPuedes seguir contestando preguntas para mejorar tu puntaje.');
			hallMessageShown = 1;
		}
	} else {
		$("#dtopsmall").html( '<p>Meta: ' + numFormat(POINTS_HALL) + ' puntos para el <a href="top.php?' + TEST_NAME + '">salón de la fama</a></p>' );
	}
}
function numFormat( nStr ) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + '.' + '$2');
	}
	return x1 + x2;
}
function save() {
	var astr = '';
	for( var i=1; i<=testLength; i++ ) {
		if( questions[i].attr("answer") ) {
			astr += questions[i].attr("answer").charAt(0);
		} else {
			astr += "0";
		}
	}
	$("#tanswer").val(astr);
	$("#ttest").val(TEST_NAME);
	$("#tlen").val(testLength);
	$("#fsave").get(0).submit();
}
function errorMessage( msgSimple, msgFull ) {
	$("#dcomments").html( '<p class="error">' + msgSimple + '.</p><p class="errordebug">' + msgFull + '</p>' );
	alert( msgSimple );
}
function simpleDOMSerialize( xml ) {
	if( xml.nodeType == 3 ) {
		return xml.nodeValue;
	} else if( xml.nodeType == 1 ) {
		var str = '<' + xml.nodeName;
		var attrs = xml.attributes;
		for( var i=0; i<attrs.length; i++ ) {
			str += ' ' + attrs[i].name + '="' + attrs[i].value + '"';
		}
		str += '>';
		var children = xml.childNodes;
		for( var i=0; i<children.length; i++ ) {
			str += simpleDOMSerialize( children[i] );
		}
		str += '</' + xml.nodeName + '>';
		return str;
	}
}
function jq2html( jq ) {
	var str = '';
	for( var i=0; i<jq.size();i++ ) {
		str += simpleDOMSerialize( jq.get(i) );	
	}
	return str;
}



