// Archivo JScript
function Quiz(oQuiz)
{
	// Variables
	var oQuiz;
	var correctCount;			// Contador de respuestas correctas
	var incorrectCount;			// Contador de respuestas incorrectas
	var page;					// Pagina de pregunta actual
	var pageTotal;			    // Paginas de preguntas totales
	var cantidadPreguntas;		// Cantidad de preguntas
	var responseAnswer;         // Variable correcta/incorrecta
	var quizQuestionValueTotal; // Valor de cada pregunta respondida
	var quizQuestionValue;      // Valor de cada pregunta respondida

	this.oQuiz = oQuiz;
	this.pageTotal;						// Paginas de preguntas totales
	this.cantidadPreguntas;				// Cantidad de preguntas
	this.quizTitulo = this.oQuiz.title;
	this.quizSubTitulo = this.oQuiz.description;
	this.page = 0;						// Puntero
	this.correctCount = 0;				// Contador de respuestas correctas
	this.incorrectCount = 0;			// Contador de respuestas incorrectas
	this.quizQuestionValue = 10;		// Valor de cada pregunta respondida
	this.quizQuestionValueTotal = 0;	// Valor sumatoria de las preguntas respondidas

   this.crear();
}

Quiz.prototype.crear = _crearRespuestas;
Quiz.prototype.checkPosition = _checkPosition;
Quiz.prototype.html = _html;
Quiz.prototype.siguiente = _siguiente;
Quiz.prototype.checkSelected = _checkSelected;
Quiz.prototype.countAnwser = _countAnwser;
Quiz.prototype.showMessageNext = _showMessageNext;
Quiz.prototype.siguienteMsg = _siguienteMsg;
Quiz.prototype.endMessageShow = _endMessageShow;

// Crear respuestas

function _crearRespuestas() {

	if (this.checkPosition())
	{
		var listAnswers;
		var listAnswers = "";
		var answerPage = this.page+1 + '/' + this.pageTotal;

		// Recorro respuestas y los guardo en var para luego hacer innerHtml
		var totalAnswers = this.oQuiz.questions[this.page].answers.length;
		for(var i = 0 ; i < totalAnswers ; i++)
		{
			listAnswers = listAnswers + '<div class="items" >';
			listAnswers = listAnswers + '	<label><input type="radio" value="'+this.oQuiz.questions[this.page].answers[i].id+'" name="pregunta" id="respuesta_'+this.oQuiz.questions[this.page].answers[i].id+'"/></label>';
			listAnswers = listAnswers +	'	<span class="respuesta" for="respuesta_'+this.oQuiz.questions[this.page].answers[i].id+'" id="label_respuesta_'+this.oQuiz.questions[this.page].answers[i].id+'">'+this.oQuiz.questions[this.page].answers[i].description+'</span>';
			listAnswers = listAnswers + '</div>';

		}
		// exec html print total
		this.html(this.quizTitulo, this.quizSubTitulo, this.oQuiz.questions[this.page].image_file, this.oQuiz.questions[this.page].description, listAnswers, answerPage);
	}else{
		// Fin de encuesta
		this.endMessageShow();
	}
}

// Funcion para crear html
function _html(quizTiulo, quizSubTiulo, quizImg, titleAnswer, listAnswers, answerPage){

	var body;
    body =          '';
    body = body +   '<div id="fichas"><br/><br/><br/>';
    body = body + 	'	<div class="test">';
    body = body +       '<span class="pregunta" >'+titleAnswer+'</span><br/><br/><br/>';
    body = body +       '<span id="responseAnswer"></span>';
    body = body +       '<div id="listAnswer">' + listAnswers + '</div>';
	body = body +   '<center><span id="nextBtnID"><button type="button" onclick="quiz.siguienteMsg();" value="" style="border:0;background:none" class="buttonRed"><img src="/images/siguiente.gif" alt="" /></button></span></center>';
    body = body +   '</div>';
    body = body +   '<div class="footer">';
    body = body +       '<!-- <p><strong>Puntaje:</strong> '+ this.quizQuestionValueTotal +'</p> -->';
    body = body +   '</div>';
	document.getElementById("quiz").innerHTML = body;
}

// Funcion de movimiento de datos
function _siguiente(){
	this.page++; // Sumo la pagina
	quiz.crear(); // Cargo nueva pregunta
}

// Funcion de movimiento de datos
function _siguienteMsg(){
	if (this.checkSelected())
	{
		this.countAnwser(); // Cargo respuesta
		//quiz.crear(); // Cargo nueva pregunta
		//this.showMessageNext(); // Muestro message
		quiz.siguiente(); //siguiente pregunta
	}
}

// Funcion de movimiento de datos
function _showMessageNext(){
	if (this.oQuiz.questions[this.page].correct_text != '')
	{
		document.getElementById("listAnswer").innerHTML = '<li>'+ this.oQuiz.questions[this.page].correct_text + '</li>';
		document.getElementById("responseAnswer").innerHTML = this.responseAnswer;
		if (this.responseAnswer == 'Incorrecta'){document.getElementById("responseAnswer").style.color = 'red';}
		document.getElementById("nextBtnID").innerHTML = '<input type="button" onclick="quiz.siguiente();" value="Continuar" class="buttonRed"/>';
	}else{
	    this.siguiente();
	}
}

// Reccorro el array y busco el final para mostrar respuesta.
function _checkPosition(){

	var preguntasTotal = 0;
	var respuestasTotal = 0;

	preguntasTotal = this.oQuiz.questions.length;

	// Si en el array tengo menos preguntas que el total, modificar el total
	if (preguntasTotal != this.pageTotal)
	{
		this.pageTotal = preguntasTotal;
	}

	// Si termino el trivia
	if (this.pageTotal == this.page)
	{
		return false;
	}
	return true;
}


// Busco y devuelvo radio seleccionado, else false.
function _checkSelected()
{
	var selectBtn = "";
	var lenBtn = document.aspnetForm.pregunta.length;
	for (var i = 0; i <lenBtn; i++) {
		if (document.aspnetForm.pregunta[i].checked) {
			selectBtn = document.aspnetForm.pregunta[i].value;
		}
	}
	if (selectBtn == "") {
		alert("Seleccione una opcion");
		return false;
	}
	else {
		return selectBtn;
	}
}

// Limpia el radio seleccionado
function _clearRadio()
{
	var lenBtn = document.aspnetForm.pregunta.length
	for (var i = 0; i <lenBtn; i++) {
		document.aspnetForm.pregunta[i].checked = false;
	}
}

// Cargo 1 a variable contadora de tener respuesta correcta.
function _countAnwser()
{
	var totalAnswers = this.oQuiz.questions[this.page].answers.length - 1;
	for(var i = 0 ; i <= totalAnswers; i++)
	{
		if ((this.checkSelected() == this.oQuiz.questions[this.page].answers[i].id))
		{
		    this.responseAnswer = 'Correcta';

			this.correctCount += this.oQuiz.questions[this.page].answers[i].puntos;
			this.quizQuestionValueTotal += this.oQuiz.questions[this.page].answers[i].puntos;
		}
	}
}

// Hago redirect con los datos
function _endMessageShow(){
	//Muestro Cargando
	//alert("end message, total: " + this.quizQuestionValueTotal);
	var respuesta;
	var body;
	if(this.quizQuestionValueTotal<=9) {
		respuesta = "Tu huella ecol&oacute;gica es tan peque&ntilde;a como la de un sapo <br/>";
		respuesta = respuesta + "(ese que ten&eacute;s en el jard&iacute;n).<br/><br/>";
	    respuesta = respuesta + '<strong>Adem&aacute;s sos un chico divertido: </strong>buen&iacute;simo, pero no te olvides <br/>';
		respuesta = respuesta + 'que estos temas tambi&eacute;n tienen que ver con vos.';
	}
	if(this.quizQuestionValueTotal>=10 && this.quizQuestionValueTotal<=19) {
		respuesta = "Ten&eacute;s una conciencia desarrollada de tus actos y del impacto de ellos. Est&aacute;s al tanto de<br/>";
		respuesta = respuesta + "todos los gestos que pod&eacute;s poner en marcha para que tu huella ecol&oacute;gica sea moderada y que los<br/>";
	    respuesta = respuesta + 'dem&aacute;s tambi&eacute;n puedan disfrutar de un mundo lleno de vida. Justamente, compart&iacute; con los que te<br/>';
		respuesta = respuesta + 'rodean todas tus buenas pr&aacute;cticas.';
	}

	if(this.quizQuestionValueTotal>=20 && this.quizQuestionValueTotal<=29) {
		respuesta = '<span class="respuesta">Quiz&aacute;s tengas que empezar a hacer un esfuerzo:<br/><br/> est&aacute;s en un mundo limitado donde si todas las personas<br/> hicieran las cosas como vos, los recursos<br/> se terminar&iacute;an muy r&aacute;pido.<br/><br/> Pero no te preocupes, <br/>hay muchas cosas que pod&eacute;s hacer <br/>para mejorar tu huella ecol&oacute;gica. <br/><br/><strong>Tarea para el hogar:</strong> releer el cuaderno con mucho cuidado!</span>';
	}

	if(this.quizQuestionValueTotal>=30) {
		respuesta = "Tu huella ecol&oacute;gica es tan peque&ntilde;a como la de un sapo <br/>";
		respuesta = respuesta + 'Tu huella ecol&oacute;gica es gigantesca. Si te consegu&iacute;s otro planeta, avisanos.';
	}

    body =          '';
    body = body +   '<div id="fichas"><br/><br/><br/>';
    body = body + 	'	<div class="test">';
    body = body +       '<span class="pregunta" >Resultados</span><br/><br/><br/>';
    body = body +       '<div class="items">  <label/>';
    body = body +       '<span class="respuesta">';
    body = body +       respuesta;
    body = body +       '</span></div>';

	document.getElementById("quiz").innerHTML = body;

}



/*-------------------------*/


function User(oUser){

	var oUser;
	var userId;
	var userNick;
	var puntajeTrivia;
	var puntajeTotal;

	this.oUser = oUser;

	this.userId = this.oUser.id + "";
	this.userNick = this.oUser.nick;
	this.puntajeTrivia = this.oUser.puntajeTrivia;
	this.puntajeTotal = this.oUser.puntajeTotal;

	this.crear(this.userId, this.userNick, this.puntajeTrivia, this.puntajeTotal);
}

User.prototype.crear = _crearRespuesta;

// Crear respuestas

function _crearRespuesta(userId, userNick, puntajeTrivia, puntajeTotal) {
	if(userId != null && userNick != null && puntajeTrivia != null && puntajeTotal != null)
	{
	    var listAnswer;
	    var iLen = userId.length;
	    var userIdDir =  userId.substring(iLen, iLen - 1);
	    var errorImg = "this.src='images/avatar.gif'";
	    var rankingLink = "javascript:document.location.href='triviaRanking.aspx'";

	    listAnswer = '<li><img onerror="'+ errorImg +'" src="http://www.lanacion.com.ar/avatar/'+ userIdDir +'/'+ userId +'.jpg" alt="" style="margin-right: 10px; margin-top: 10px; margin-bottom: 20px;" /></li>';
	    listAnswer = listAnswer + '<li><strong>Usuario:</strong> '+ userNick +'</li>';
	    listAnswer = listAnswer + '<li><strong>Puntaje de trivia:</strong> '+ puntajeTrivia +'</li>';
	    listAnswer = listAnswer + '<li><strong>Puntaje de todas las trivias:</strong> '+ puntajeTotal +'</li>';
	    listAnswer = listAnswer + '<li><center><input type="button" onclick="'+rankingLink+';" value="Ver ranking" class="buttonRed"/></center></li>';
	    document.getElementById("listAnswer").innerHTML = listAnswer;
	}
}

/*-------------------------*/