﻿// 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
	
    if((readCookie("cookieLogin")!=null) && (readCookie("cookieLogin")!=''))
    {
        this.crear();
    }else{
        this.login();
    }	
}

Quiz.prototype.crear = _crearRespuestas;
Quiz.prototype.login = _login;
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 + '<li>';
			listAnswers = listAnswers + '<input type="radio" value="'+this.oQuiz.questions[this.page].answers[i].id+'" name="pregunta" id="respuesta_'+this.oQuiz.questions[this.page].answers[i].id+'"/>';
			listAnswers = listAnswers +	'<label 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+'</label>';
			listAnswers = listAnswers + '</li>';	

		}
		// 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 =          '<img width="310" height="300" id="imgAnswer" src="'+quizImg+'" />';
    body = body +   '<div class="content">';
    body = body +       '<h2>'+quizTiulo+'</h2>';
    body = body +       '<h4>'+quizSubTiulo+'</h4>';
    body = body +       '<p><strong>'+titleAnswer+'</strong></p>';
    body = body +       '<span id="responseAnswer"></span>';    
    body = body +       '<ul class="gray" id="listAnswer">'+listAnswers;
    body = body +       '</ul>';
	body = body +   '<center><span id="nextBtnID"><input type="button" onclick="quiz.siguienteMsg();" value="Ok" class="buttonRed"/></span></center>';
    body = body +   '</div>';
    body = body +   '<div class="footer">';
    body = body +       '<p><strong>Incorrectas:</strong> '+ this.incorrectCount +'</p>';
    body = body +       '<p><strong>Correctas:</strong> '+ this.correctCount +'</p>';
    body = body +       '<p><strong>Puntaje:</strong></p>';
    body = body +   '</div>';
    body = body +   '<div class="puntajeCnt">'+ this.quizQuestionValueTotal +'</div>';    
    //body = body +   '<br clear="all"/>';


	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
	}
}

// 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.oQuiz.questions[this.page].answers[i].correct == "1"))
		{
		    this.responseAnswer = 'Correcta';
			this.correctCount++;
			this.quizQuestionValueTotal = this.quizQuestionValue * this.correctCount;
		}else{
			if (this.checkSelected() == this.oQuiz.questions[this.page].answers[i].id)
			{
			    this.responseAnswer = 'Incorrecta';
				this.incorrectCount++;
			}
		}
	}
}

// Hago redirect con los datos
function _endMessageShow(){
	
	//Muestro Cargando
	
	this.html(this.quizTitulo, 'Procesando los datos.', this.oQuiz.questions[this.page-1].image_file, '', '', '');	
	document.getElementById("nextBtnID").innerHTML = '<img style="float:none;" src="images/icons/ajax-loader.gif" alt="" />';	
	
    var quizId = this.oQuiz.id;
    var userId = readCookie("usuario_id");
    var userNick = readCookie("usuario_usuario");
    var userScore = this.quizQuestionValueTotal;
	
    document.getElementById('ctl00_ContentPlaceHolder1_quizId').value = quizId;
    document.getElementById('ctl00_ContentPlaceHolder1_userId').value = userId;
    document.getElementById('ctl00_ContentPlaceHolder1_userNick').value = userNick;
    document.getElementById('ctl00_ContentPlaceHolder1_userScore').value = userScore;   	
	
	document.aspnetForm.submit();
}

function _login() {

		var listAnswers;
		listAnswers = '<li><p>Para participar de la Trivia tenes que ser usuario de ZonaCinemania.</p>';
		listAnswers = listAnswers + '<p><a href="https://registracion.lanacion.com.ar/ingresar?sitioId=15&tipoParticipacion=2&pagina=http://www.zonacinemania.com/trivia.aspx?quiz='+this.oQuiz.id+'">Ingresá</a> o <a href="https://registracion.lanacion.com.ar/registracion?tipoParticipacion=2&sitioId=15">Registrate</a></p></li>';
		
		// exec html print total
		this.html(this.quizTitulo, this.quizSubTitulo, this.oQuiz.questions[this.page].image_file, '', listAnswers, '');
		document.getElementById("listAnswer").className = '';
		document.getElementById("nextBtnID").innerHTML = '';
}


/*-------------------------*/


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;
	}		
}

/*-------------------------*/