var currentQuestion = 1; // Global variable to hold current question
var totalQuestions = 6; // Global variable to hold maximum number of questions
var currentAnswer = false; // Global variable to hold state of whether the current answer has been chosen
var currentScore = 0; // Global variable to hold score

// Function to run on page load and DOM ready
Event.observe(window, 'load', function() {
	// Pre-load images
	MM_preloadImages(
		'../images/quiz/bg-results-panel.gif',
		'../images/quiz/points-1.gif',
		'../images/quiz/points-1-o.gif',
		'../images/quiz/points-2.gif',
		'../images/quiz/points-2-o.gif',
		'../images/quiz/points-3.gif',
		'../images/quiz/points-3-o.gif',
		'../images/quiz/bg-fact-1.gif',
		'../images/quiz/bg-fact-2.gif',
		'../images/quiz/bg-fact-3.gif',
		'../images/quiz/bg-fact-3.gif',
		'../images/quiz/bg-fact-5.gif',
		'../images/quiz/bg-fact-6.gif',
		'../images/quiz/hdr-como-respondiste.gif',
		'../images/quiz/hdr-y-luego-que.gif',
		'../images/quiz/hdr-not-a-sexpert-spanish.gif',
		'../images/quiz/hdr-sort-of-sexpert-spanish.gif',
		'../images/quiz/hdr-super-sexpert-spanish.gif'
	);
	
	// Set initial button event handlers when page is ready
	startButton = $('btnStartQuiz');
	startButton.onclick = function() {
		startQuiz(); return false;
	}
									   
	// Set initial values for current and max questsions
	oCurrentQuestion = $('currentQuestion');
	oCurrentQuestion.firstChild.nodeValue = currentQuestion;
	oTotalQuestions = $('totalQuestions');
	oTotalQuestions.firstChild.nodeValue = totalQuestions;
	
	// Build array of answer points
	question1 = Array();
	question1['AnswerA'] = 2;
	question1['AnswerB'] = 3;
	question1['AnswerC'] = 1;
	question1['AnswerD'] = 1;
	question2 = Array();
	question2['AnswerA'] = 1;
	question2['AnswerB'] = 2;
	question2['AnswerC'] = 1;
	question2['AnswerD'] = 3;
	question3 = Array();
	question3['AnswerA'] = 1;
	question3['AnswerB'] = 3;
	question3['AnswerC'] = 2;
	question3['AnswerD'] = 1;
	question4 = Array();
	question4['AnswerA'] = 3;
	question4['AnswerB'] = 2;
	question4['AnswerC'] = 1;
	question4['AnswerD'] = 2;
	question5 = Array();
	question5['AnswerA'] = 1;
	question5['AnswerB'] = 2;
	question5['AnswerC'] = 3;
	question5['AnswerD'] = 1;
	question6 = Array();
	question6['AnswerA'] = 3;
	question6['AnswerB'] = 1;
	question6['AnswerC'] = 1;
	question6['AnswerD'] = 2;
	
	questions = Array();
	questions['Question1'] = question1;
	questions['Question2'] = question2;
	questions['Question3'] = question3;
	questions['Question4'] = question4;
	questions['Question5'] = question5;
	questions['Question6'] = question6;
});



// This function switches the intro panel to the quiz panel
function startQuiz() {
	// Sets local object variables for each panel
	var oMain = $('quiz');
	var oPanelOff = $('quizIntroPanel');
	var oPanelOn = $('quizMainPanel');
	
	// Update the main panel to be the correct height for the quiz
	oMain.style.height = '590px';
	
	// Cross Fade the intro panel into the main quiz panel
	new Effect.Parallel(
		[
			Effect.Fade(oPanelOff, { sync: true }),
			Effect.Appear(oPanelOn, { sync: true })
		],
		{ duration: .5, afterFinish: function() { loadQuestion(currentQuestion); } }
	);
	

}

/* This function fades in the question and answers */
function loadQuestion(currentQuestion) {
	/* If this is not the first question, fade out the previous question first */
	if (currentQuestion != 1 ) {
		prevQuestion=(currentQuestion-1);
		oAnswerA = $('quizAnswer'+prevQuestion+'A');
		oAnswerB = $('quizAnswer'+prevQuestion+'B');
		oAnswerC = $('quizAnswer'+prevQuestion+'C');
		oAnswerD = $('quizAnswer'+prevQuestion+'D');
		oFact = $('fact'+prevQuestion);
		new Effect.Parallel(
			[
				Effect.Fade(oAnswerA, { sync: true }),
				Effect.Fade(oAnswerB, { sync: true }),
				Effect.Fade(oAnswerC, { sync: true }),
				Effect.Fade(oAnswerD, { sync: true }),
				Effect.Fade(oFact, { sync: true })
			],
			{ duration: .5 }
		);
		oCurrentQuestion = $('currentQuestion');
		oCurrentQuestion.firstChild.nodeValue = currentQuestion;
	}
	
	/* If we're done with the quiz, run the FinishQuiz function.  Otherwise fade in the next question and answers */
	if (currentQuestion > totalQuestions) {
		FinishQuiz();
	} else {
		oQuestionSetup = $('quizQuestionSetup'+currentQuestion);
		Effect.Appear(oQuestionSetup, { duration: .5, queue: { position: 'end', scope: 'question' } });
		
		oQuestion = $('quizQuestion'+currentQuestion);
		Effect.Appear(oQuestion, { duration: .5, queue: { position: 'end', scope: 'question' } });
		
		oAnswerA = $('quizAnswer'+currentQuestion+'A');
		Effect.Appear(oAnswerA, { duration: .25, queue: { position: 'end', scope: 'question' } });
		
		oAnswerB = $('quizAnswer'+currentQuestion+'B');
		Effect.Appear(oAnswerB, { duration: .25, queue: { position: 'end', scope: 'question' } });
		
		oAnswerC = $('quizAnswer'+currentQuestion+'C');
		Effect.Appear(oAnswerC, { duration: .25, queue: { position: 'end', scope: 'question' } });
		
		oAnswerD = $('quizAnswer'+currentQuestion+'D');
		Effect.Appear(oAnswerD, { duration: .25, queue: { position: 'end', scope: 'question' } });
		
		/* Reset the current answer state */
		currentAnswer = false;
	}
}

/* Rollover state for each answer */
function AnswerOver(answerDiv) {
	if (currentAnswer) return false; // Question has already been answered so do nothing
	oAnswer = $(answerDiv);
	oAnswer.style.cursor='pointer';
	oAnswer.style.fontWeight='bold';
	
	var aImages = oAnswer.getElementsByTagName('img');
	for (var i = 0; i < aImages.length; i++) {
		var src = aImages[i].getAttribute('src');
		var ftype = src.substring(src.lastIndexOf('.'), src.length);
		var hsrc = src.replace(ftype, '-o'+ftype);
		aImages[i].setAttribute('src', hsrc);
	}
}

/* Roll off state for each answer */
function AnswerOff(answerDiv) {
	if (currentAnswer) return false; // Question has already been answered so do nothing
	oAnswer = $(answerDiv);
	oAnswer.style.fontWeight='normal';
	var aImages = oAnswer.getElementsByTagName('img');
	for (var i = 0; i < aImages.length; i++) {
		var src = aImages[i].getAttribute('src');
		var ftype = src.substring(src.lastIndexOf('.'), src.length);
		var hsrc = src.replace('-o'+ftype, ftype);
		aImages[i].setAttribute('src', hsrc);
	}
}

function AnswerQuestion(answerDiv, question, answer) {
	if (currentAnswer) return false; // Question has already been answered so do nothing
	currentAnswer = true; // User answered the quesion so mark it as such.
	oAnswer = $(answerDiv);
	oAnswer.style.fontWeight='bold';
	
	/* Fade out the question setup text and slide the answers up */
	oSetup = $('quizQuestionSetup'+question);
	Effect.Fade(oSetup, { duration: .5, queue: { position: 'end', scope: 'question' } });
	oQuestion = $('quizQuestion'+question);
	Effect.Fade(oQuestion, { duration: .5, queue: { position: 'end', scope: 'question' } });
	
	oAnswerA = $('quizAnswer'+question+'A');
	new Effect.Move (oAnswerA, { duration: .2, x: 15, y: 70, mode: 'absolute', queue: { position: 'end', scope: 'question' } });
	
	oAnswerB = $('quizAnswer'+question+'B');
	new Effect.Move (oAnswerB, { duration: .2, x: 15, y: 130, mode: 'absolute', queue: { position: 'end', scope: 'question' } });
	
	oAnswerC = $('quizAnswer'+question+'C');
	new Effect.Move (oAnswerC, { duration: .2, x: 15, y: 190, mode: 'absolute', queue: { position: 'end', scope: 'question' } });
	
	oAnswerD = $('quizAnswer'+question+'D');
	new Effect.Move (oAnswerD, { duration: .2, x: 15, y: 250, mode: 'absolute', queue: { position: 'end', scope: 'question' } });
	
	/* Increment question counter, fade in fact */
	currentQuestion++;
	oFact = $('fact'+question);
	Effect.Appear(oFact, { duration: .75, queue: { position: 'end', scope: 'question' } });
	
	/* Change answer buttons to points indicators, highlighting the selected one */
	oImgA = $('quizAnswer'+question+'AButton');
	(answer=='A') ? oImgA.setAttribute('src', '../images/quiz/points-'+questions['Question'+question]['AnswerA']+'-o.gif') : oImgA.setAttribute('src', '../images/quiz/points-'+questions['Question'+question]['AnswerA']+'.gif');
	oImgB = $('quizAnswer'+question+'BButton');
	(answer=='B') ? oImgB.setAttribute('src', '../images/quiz/points-'+questions['Question'+question]['AnswerB']+'-o.gif') : oImgB.setAttribute('src', '../images/quiz/points-'+questions['Question'+question]['AnswerB']+'.gif');
	oImgC = $('quizAnswer'+question+'CButton');
	(answer=='C') ? oImgC.setAttribute('src', '../images/quiz/points-'+questions['Question'+question]['AnswerC']+'-o.gif') : oImgC.setAttribute('src', '../images/quiz/points-'+questions['Question'+question]['AnswerC']+'.gif');
	oImgD = $('quizAnswer'+question+'DButton');
	(answer=='D') ? oImgD.setAttribute('src', '../images/quiz/points-'+questions['Question'+question]['AnswerD']+'-o.gif') : oImgD.setAttribute('src', '../images/quiz/points-'+questions['Question'+question]['AnswerD']+'.gif');
	
	/* Update the score */
	currentScore += questions['Question'+question]['Answer'+answer];
	oScore = $('currentScore');
	oScore.firstChild.nodeValue = currentScore + ' pts';
	
}

/* This is the final function to calculate rank based on score and show the proper text */
function FinishQuiz() {
	oPromos = $('quizPromos');
	Effect.Fade(oPromos, { duration: .25});
	
	oRank = $('hdrResults');
	oRankDesc = $('txtResults');
	
	if (currentScore >= 15) {
		oRank.setAttribute('src', '../images/quiz/hdr-super-sexpert-spanish.gif');
		oRank.setAttribute('alt', 'Super Sexperto: 15 a 18 puntos');
		oRankDesc.firstChild.nodeValue = 'Tus amigos/as deberían hablar contigo antes de tomar decisiones sobre el sexo, porque eres una enciclopedia sobre el tema. Lo entiendes clarísimo: la única forma de prevenir 100% el embarazo es no tener relaciones sexuales, pero si las tienes sabes que tienes que cuidarte cada vez. Diles a tus amigos que tomen esta prueba  para ver si su puntaje es tan bueno como el tuyo.';
	} else if (currentScore >= 9) {
		oRank.setAttribute('src', '../images/quiz/hdr-sort-of-sexpert-spanish.gif');
		oRank.setAttribute('alt', 'Casi un sexperto: 14-9 puntos');
		oRankDesc.firstChild.nodeValue = 'La mayoría de las veces sabes cuál es la decisión correcta, pero no siempre cuando se trata del sexo. La abstinencia es la única manera para prevenir el embarazo o las ETS. Pero si tienes relaciones sexuales, debes cuidarte cada vez que lo hagas. Planéalo siempre. Haz que tus amigos tomen esta prueba y ver cuál es su puntaje.';
	} else {
		oRank.setAttribute('src', '../images/quiz/hdr-not-a-sexpert-spanish.gif');
		oRank.setAttribute('alt', '¿Sexperto? ¡Ni de broma!: 8-6 puntos  ');
		oRankDesc.firstChild.nodeValue = 'El sexo es un tema serio... ¿entonces por qué actúas como si fuera una decisión tan simple? Ojalá que esta prueba te haya mostrado que las relaciones sexuales pueden traer consecuencias serias. Aprende más en StayTeen.org, y luego vuelve a tomar la prueba. Tienes una segunda oportunidad... por ahora. Haz que tus amigos también tomen esta prueba y ver si les va mejor que a tí.';
	}
	
	oHeader = $('quizHeaderText');
	oHeader.style.display = 'none';
	oScore = $('quizHeaderScore');
	oScore.style.display = 'none';
	
	var txt1 = document.createTextNode('Puntuación total: ');
	var span1 = document.createElement('span');
		span1.setAttribute('class', 'currentScore');
	var txt2 = document.createTextNode(currentScore + ' pts');
		span1.appendChild(txt2);
	
	oFinalScore = $('quizHeaderScoreFinal');
	oFinalScore.appendChild(txt1);
	oFinalScore.appendChild(span1);
	oFinalScore.style.display = 'block';

	oResults = $('quizResultsPanel');
	Effect.Appear(oResults, { duration: .5 });
}