var UNGUESSED = 0;
var CORRECT = 1;
var INCORRECT = 2;

var done = false;

var selectedAnswer = -1;
var imagePreload;

var numRemaining;
var numIncorrect = 0;
var numCorrect = 0;

var timestaken = 0;
var sumofscores = 0;

var alphaAnswers;

function load()
{
	document.getElementById("btnGiveUp").disabled = false;
	setTimeout( load2, 500 );
}

function load2()	
{
	alphaAnswers = answers.slice();
	alphaAnswers.sort( answerByDisplay );
	initMapDiv();
	preloadImages();
	loadSelector();
	select(0);
	numRemaining = answers.length;
	displayRemaining();
	setTimeout( load3, 500 );
}

function load3()
{
	document.getElementById("maploading").style.display = "none";
	document.getElementById("quiz").style.display = "block";
	displayClock();
	setTimeout( decrementClock, 1000 );
}

function giveUp()
{
	finish();
}


function finish()
{
	deselect(selectedAnswer);
	document.getElementById("controls").style.display = "none";
	document.getElementById("btnGiveUp").disabled = true;
	done = true;
	getResults();
}

function getResults()
{
	var p = new Array();
	p.push( "?quiz=" + quizId );
	p.push( "&timeleft=" + seconds );
	for (var i=0; i<answers.length; i++)
	{
		var a = answers[i];
		if ( a.userGuess != null )
		{
			p.push("&a" + a.id + "=" + a.userGuess.id );
		}
	}

	var params = p.join('');

	var http = createRequestObject();
	http.open("get", "/quizzes/includes/set-map-results.php" + params, true);
	http.onreadystatechange = function()
	{
		if ( http.readyState == 4 )
			response = http.responseText;
		else
			return;

		var lines = response.split('\n');
		var mode = 0;

		for (var i=0; i<lines.length-1; i++)
		{
			if ( lines[i] == "TIMES TAKEN" )
			{
				mode = 1;
				continue;
			}
			if ( lines[i] == "SUM" )
			{
				mode = 2;
				continue;
			}
			if ( lines[i] == "MAP GUESSES" )
			{
				mode = 3;
				continue;
			}

			if ( mode == 1 )
			{
				timestaken = parseInt(lines[i]);
			}
			if ( mode == 2 )
			{
				sumofscores = parseInt(lines[i]);
			}
			if ( mode == 3 )
			{
				var tabs = lines[i].split('\t');

				var x = getAnswerWithId( parseInt( tabs[0] ) );
				var y = getAnswerWithId( parseInt( tabs[1] ) );
				var num = parseInt( tabs[2] );

				var z = new AnswerGuess(y,num);
				x.answerGuesses.push(z);
			}
		}		
		document.getElementById("postQuizA").innerHTML = "<div class=\"a\">You got <span class=\"x\">" + numCorrect + "/" + answers.length + "</span> correct</div><div class=\"b\">The average score is <span class=\"y\">" + Math.round(sumofscores/timestaken) + "</span>, but some people take it many times.</div>";
		document.getElementById("postQuiz").style.display = "block";
	}
	http.send(null);
}

function updateStatPanel()
{
	var div = document.getElementById("statPanel");
	div.style.display = "block";
	var a = answers[selectedAnswer];

	var html = new Array();
	
	var correct = true;
	if ( a.userGuess == null )
		correct = false;
	else if ( a.id != a.userGuess.id )
		correct = false;

	if  ( correct )
	{
		html.push("<div class=\"correct\">You guessed <span class=\"big\">" + a.display + "</span>.<br>Correct!</div>");
	}	
	else
	{
		html.push("<div class=\"incorrect\">The correct answer is <span class=\"big\">" + a.display + ".</span>");
		if ( a.userGuess == null )
			html.push("<p>You left this blank.");
		else
			html.push("<p>You guessed " + a.userGuess.display + ".");		
		html.push("</div>");
	}

	html.push("<div class=\"h\">Others Guessed:</div>");

	for (i=0; i<a.answerGuesses.length; i++)
	{
		var x = a.answerGuesses[i];
		var pct = Math.round( 100 * ( x.num / timestaken ) );
		var pxl = Math.round( 200 * ( x.num / timestaken ) );
		
		html.push("<div class=\"mbarh\">" + x.guess.display + " - " + pct + "%</div>");
		html.push("<div class=\"mbar\" style=\"width: " + pxl + "px;\"></div>");
	}

	div.innerHTML = html.join('');
}

function signAndShow()
{
	mlJoin(2);
	justShow();
}

function justShow()
{
	document.getElementById("postQuiz").style.display = "none";
	select(0);
}


function chooseAnswer()
{	
	var x = document.getElementById("selector");
	if ( x.selectedIndex < 0 )
	{
		alert("Please select an item name from the pull-down list");
		return;
	}

	var div = document.getElementById("answer_" + selectedAnswer );
	var buzz = document.getElementById("buzzer");
	var a = answers[ selectedAnswer ];
	a.userGuess = alphaAnswers[ x.value ];
	if ( a.id == a.userGuess.id )
	{
		a.status = CORRECT;
		numCorrect++;
		buzz.innerHTML = "Last: <span style=\"font-weight: bold; color: #009900; font-size: 18px;\">Correct!</span>";
	}
	else
	{
		a.status = INCORRECT;
		numIncorrect++;
		buzz.innerHTML = "Last: <span style=\"font-weight: bold; color: #990000; font-size: 18px;\">Incorrect.</span>";
	}

	numRemaining--;

	loadSelector();
	displayRemaining();

	if ( numRemaining == 0 )
		finish();
	else
		next();
}

function select(x)
{
	selectedAnswer = x;
	a = answers[selectedAnswer];
	div = document.getElementById("answer_" + selectedAnswer );
	div.innerHTML = "<img src=\"images/" + prefix + "/selected/" + a.code + ".png\">";
	div.style.zIndex = 3;
	if ( done )
	{
		updateStatPanel();
	}
}


function deselect(x)
{
	a = answers[x];
	div = document.getElementById("answer_" + x );
	if ( a.status == UNGUESSED )
		div.innerHTML = "";
	else if ( a.status == INCORRECT )
		div.innerHTML = "<img src=\"images/" + prefix + "/incorrect/" + a.code + ".png\">";
	else
		div.innerHTML = "<img src=\"images/" + prefix + "/correct/" + a.code + ".png\">";

	div.style.zIndex = 2;
}

function next()
{
	x = selectedAnswer + 1;
	while ( 1 == 1 )
	{
		if ( x == answers.length )
			x = 0;
		if ( x == selectedAnswer )
			break;
		a = answers[x];
		if ( a.status == UNGUESSED || done )
			break;
		x++;
	}
	deselect(selectedAnswer);
	select(x);
}

function prev()
{
	x = selectedAnswer - 1;
	while ( 1 == 1 )
	{
		if ( x < 0 )
			x = answers.length-1;
		if ( x == selectedAnswer )
			break;
		a = answers[x];
		if ( a.status == UNGUESSED || done )
			break;
		x--;
	}
	deselect(selectedAnswer);
	select(x);
}


function displayRemaining()
{
	var html = "<span class=\"bign\">" + numCorrect + "</span> correct, <span class=\"bign\">" + numRemaining + "</span> remaining.";
	document.getElementById("status").innerHTML = html;
}

function loadSelector()
{
	var sel = document.getElementById("selector");
	var length = 0;
	for (var i=0; i<alphaAnswers.length; i++)
	{
		var a = alphaAnswers[i];
		if ( a.status == UNGUESSED || a.status == INCORRECT )
			length++;
	}
	sel.options.length = length;
	length = 0;
	for (var i=0; i<alphaAnswers.length; i++)
	{
		var a = alphaAnswers[i];
		if ( a.status == UNGUESSED || a.status == INCORRECT )
			sel.options[length++] = new Option(a.display, i);
	}
}


function preloadImages()
{
	imagePreload = new Array();
	var x = new Array();
	for (var i=0; i<answers.length; i++)
	{
		var a = answers[i];
		x.push( "images/" + prefix + "/correct/" + a.code + ".png" );
		x.push( "images/" + prefix + "/incorrect/" + a.code + ".png" );
		x.push( "images/" + prefix + "/selected/" + a.code + ".png" );
	}

	for ( var i=0; i<x.length; i++ )
	{
		var y = new Image();
		y.src = x[i];
		imagePreload.push( y );
	}
}

function initMapDiv()
{
	var html = new Array();
	html.push("<img src=\"images/" + prefix + "/main.png\" style=\"position: absolute; left: 0px; top: 0px; z-index: 1;\">");

	for (var i=0; i<answers.length; i++)
	{
		var a = answers[i];
		html.push("<div id=\"answer_" + i + "\" style=\"position: absolute; left: " + a.x + "px; top: " + a.y + "px; z-index: 2;\"></div>");
	}
	document.getElementById("mapDiv").innerHTML = html.join('');
}



function decrementClock()
{
	if ( done ) 
		return;

	seconds--;

	displayClock();
	if ( seconds == 0 )
	{
		finish();
	}
	else	
		setTimeout( decrementClock, 1000 );
}


function displayClock()
{
	var s = seconds % 60;
	var m = ( seconds - s ) / 60;
	document.getElementById("clock").innerHTML = m + ":" + padZero(s);
}


function Answer(id, display, code, x, y, w, h)
{
	this.id = id;
	this.display = display;
	this.code = code;
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
	this.status = UNGUESSED;
	this.userGuess = null;
	this.answerGuesses = new Array();
}

function answerByDisplay(a,b)
{
	if ( a.display < b.display ) return -1;
	if ( a.display > b.display ) return 1;
	return 0;
}

function AnswerGuess(guess, num)
{
	this.guess = guess;
	this.num = num;
}

function getAnswerWithId(id)
{
	for (x=0; x<answers.length; x++)
	{
		if (answers[x].id == id)
			return answers[x];
	}
}

function padZero(num)
{
	if ( num == 0 )
		return "00";
	else if ( num < 10 )
		return "0" + num;
	else
		return "" + num;
}


