function getHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
			} catch (E) {
				xmlhttp = false;
			}
		}
	@else
		xmlhttp = false;
	@end @*/

	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}

	return xmlhttp;
}

function ajaxReceive()
{
	if(http.readyState == 4)
	{
		if(http.status == 200)
			return http.responseText;
		else
			showStatus("There was a server error initiating the script. Please try again later.");
	}

	return false;
}

function ajaxSend(url, f)
{
    try
    {
     	http.open("GET", url, true);
        http.onreadystatechange = f;
        http.send(null);
    }
    catch(e)
    {

    }
}

var http = getHTTPObject();
var brands;
var pointer = 0;
var score = 0;
var gameover = false;

function showBrand(brand)
{
	document.getElementById("brand").childNodes[0].nodeValue = brand;
}

function showNextBrand()
{
	if(pointer < brands.length)
	{
		showBrand(brands[pointer]);
		pointer++;
	}
}

function showStatus(msg)
{
	document.getElementById("status").firstChild.nodeValue = msg;
}

function updateScore()
{
	document.getElementById("score").firstChild.nodeValue = score;
}

function receiveBrands()
{
	txt = ajaxReceive();
	if(txt == false) return;

	showStatus(" ");

	brands = txt.split(":");
	pointer = 0;
	showNextBrand();
}

function loadBrands()
{
	showStatus("Loading ...");
    ajaxSend("cars.php", receiveBrands);
}

function receiveResults()
{
	txt = ajaxReceive();
	if(txt == false) return;

	showStatus(" ");

	if(txt == "y")
	{
		score++;
    	updateScore();
    }

	if(pointer == brands.length)
	{
		alert("Game over. You got " + score + " brands right, out of 10 possible.");
		gameover = true;
	}
	else
		showNextBrand();
}

function checkBrand(corp)
{
	if(gameover)
	{
		if(confirm("You need to restart the game first. Should I do that for you?"))
			begin();
	}
	else
	{
		if(typeof brands == "undefined")
            alert("The game couldn't initialize. Please try reloading this page later.");
		else
		{
    		showStatus("Checking ...");
            ajaxSend("cars.php?b=" + brands[pointer - 1] + "&c=" + corp, receiveResults);
        }
	}
}

function begin()
{
	gameover = false;
	loadBrands();
	score = 0;
	updateScore();
}

function showAnswers()
{
	document.getElementById("answers").style.display = "block";
}

begin();
