
// Utitlity functions

function get_random()
{
    var ranNum= Math.floor(Math.random()*1000000000)+1;
    return ranNum;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function getQueryVariable(variable)
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++)
	{
		var pair = vars[i].split("=");
		if (pair[0] == variable)
		{
			return pair[1];
		}
	} 
	return "";
}

function createXHR() 
{
	var request = false;
	try
	{
		request = new ActiveXObject('Msxml2.XMLHTTP');
	}
	catch (err2)
	{
		try
		{
			request = new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch (err3)
		{
			try
			{
				request = new XMLHttpRequest();
			}
			catch (err1) 
			{
				request = false;
			}
		}
	}
	return request;
}


function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}


function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}





// Class definitions

//Class which stores state of a single box.
function BoxData()
{
	this.opened = false;
	this.value = -1; // -1 means a random value must be assigned.
	this.openOrder = 0; // 0 means not opened.
}

//Class to store all the data for a single game
function GameData()
{
	this.skew = gameSkewFactor;
	this.numBoxes = gameNumBoxes;
	this.openBoxes = 0;
	this.boxes = Array();

	//The id of the box which has the highest value so far.
	this.maxBoxId = -1;



	//Function to assign random values to all boxes.
	//Boxes which already have assigned values will not be changed.
	this.assignAllValues = function()
	{
		for(var i=0; i<this.boxes.length; i++)
		{
			this.assignBoxValue(i);
		}
	}


	//Function to assign random values to all boxes.
	//Boxes which already have assigned values will not be changed.
	this.reset = function()
	{
		this.skew= gameSkewFactor;
		this.numBoxes = gameNumBoxes;
		this.boxes = Array();
		this.lastBoxID = -1;
		this.maxBoxID = -1;
		this.prevMaxBoxID = -1;
		this.openBoxes = 0;

 		for(var i = 0; i < this.numBoxes; i++)
		{
			this.boxes[i] = new BoxData(); 
 		}

	}

	//Opens a box and assigns it a value.
	this.openBox = function(id)
	{
		var boxValue;
	
		if (this.boxes[id].opened == true)
		{
			return false;
		}
		//open the box
		this.boxes[id].opened = true;
		this.boxes[id].openOrder = this.openBoxes + 1;
		this.assignBoxValue(id);
		boxValue = this.getBoxValue(id);
		//Check if it is max box and update lastBoxID and maxBoxID
		this.lastBoxID = id;

		return true;

	}

	//Returns the monetry value of the given box.
	this.getBoxValue = function(id)
	{
		return this.boxes[id].value;
	}


	//Assigns a random monetry value to the given box.
	//The value depends on the skew of the game.
	this.assignBoxValue = function(id)
	{
		if (this.boxes[id].value != -1)
		{
			return false;
		}

		do
		{
			boxVals = generateBoxVals(this.skew, 1);
		} while (this.boxHasValue(boxVals[0]) == true)
		this.boxes[id].value = boxVals[0];

		if ((this.maxBoxID == -1) || (this.boxes[id].value >= this.boxes[this.maxBoxID].value))
		{
			this.prevMaxBoxID = this.maxBoxID;
			this.maxBoxID = id;
		}

		return this.boxes[id].value;
	}

	this.boxHasValue = function(val)
	{
		for (var i=0; i < this.boxes.length; i++)
		{
			if (this.boxes[i].value == val)
			{
				return true;
			}
		}
		return false;
	}

	//Returns the rank of the box the user selected..
	this.getStopRank = function()
	{
		var rank = 1;
		for (var i=0; i < this.boxes.length; i++)
		{
			if (i != this.lastBoxID)
			{
				if (this.boxes[i].value > this.boxes[this.lastBoxID].value)
				{
					rank++;
				}
			}
		}
		return rank;
	}


	//Returns a string suitable for use with the AJAX POST call. 
	this.getPostVars = function()
	{
		var postString;

		postString = "numboxes=" + this.numBoxes + "&skewfactor=" + this.skew + "&stoprank=" + this.getStopRank();
		for (var i=0; i < this.boxes.length; i++)
		{
			postString += "&box" + i + "=";
			if (this.boxes[i].opened)
			{
				postString += this.boxes[i].value;
			}
			else
			{
				postString += 0;
			}

			postString += "&bo" + i + "=";
			postString += this.boxes[i].openOrder;
		}
		return postString;
	}

}


//Used in descriptions of boxes.
var boxDescr = Array();
boxDescr[0] = "";
boxDescr[1] = "first";
boxDescr[2] = "second";
boxDescr[3] = "third";
boxDescr[4] = "fourth";
boxDescr[5] = "fifth";
boxDescr[6] = "sixth";
boxDescr[7] = "seventh";
boxDescr[8] = "eighth";
boxDescr[9] = "ninth";
boxDescr[10] = "tenth";
boxDescr[11] = "eleventh";
boxDescr[12] = "twelfth";
boxDescr[13] = "thirteenth";
boxDescr[14] = "foureenth";
boxDescr[15] = "fifteenth";
boxDescr[16] = "sixteenth";
boxDescr[17] = "seventeenth";
boxDescr[18] = "eighteenth";
boxDescr[19] = "nineteenth";
boxDescr[20] = "twentieth";
boxDescr[21] = "twenty-first";
boxDescr[22] = "twenty-second";
boxDescr[23] = "twenty-third";
boxDescr[24] = "twenty-fourth";
boxDescr[25] = "twenty-fifth";
boxDescr[26] = "twenty-sixth";
boxDescr[27] = "twenty-seventh";
boxDescr[28] = "twenty-eighth";
boxDescr[29] = "twenty-ninth";
boxDescr[30] = "thirtieth";
boxDescr[31] = "thirty-first";
boxDescr[32] = "thirty-second";
boxDescr[33] = "thirty-third";
boxDescr[34] = "thirty-fourth";
boxDescr[35] = "thirty-fifth";
boxDescr[36] = "thirty-sixth";
boxDescr[37] = "thirty-seventh";
boxDescr[38] = "thirty-eighth";
boxDescr[39] = "thirty-ninth";
boxDescr[40] = "fourtieth";
boxDescr[41] = "forty-first";
boxDescr[42] = "forty-second";
boxDescr[43] = "forty-third";
boxDescr[44] = "forty-fourth";
boxDescr[45] = "forty-fifth";
boxDescr[46] = "forty-sixth";
boxDescr[47] = "forty-seventh";
boxDescr[48] = "forty-eighth";
boxDescr[49] = "forty-ninth";
boxDescr[50] = "fiftieth";

var gameData = new GameData();
var highestText = document.createElement("p");
highestText.setAttribute("id", "highestText");
highestText.innerHTML = "<- Most money so far";

var gameEnded = false;


//Update the display of a single box.
function openBox(id)
{
	//Read data from that box.
	if (!gameData.openBox(id))
	{
		return;
	}
	//Update the div containing that box view.
	var boxDiv = document.getElementById("boxDiv" + id);
	var resultText = boxDiv.childNodes[0];	
	resultText.innerHTML = " &nbsp; " + addCommas(gameData.getBoxValue(id)) + " dollars";
	//Update the max amount identifier.
	if (id == gameData.maxBoxID)
	{
		boxDiv.appendChild(highestText);
	}
	gameData.openBoxes = gameData.openBoxes + 1;
	if (gameData.openBoxes == gameData.numBoxes)
	{
		stopGame();
	}
}

//Handles the AJAX call.
function writeGameData(url, content)	// url is the script and data is a string of parameters
{ 

	var xhr = createXHR();
	xhr.onreadystatechange=function()
	{ 
		if(xhr.readyState == 4)
		{
			// nothing for now
			//alert(xhr.responseText);
		}
	}; 
	xhr.open("POST", url, false);		
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
	//content = "user=4&word=5";
	
	xhr.send(content); 
	//xhr.send(null); 
} 


//Handles the AJAX call.
function generateBoxVals(skew, numBoxes)	// url is the script and data is a string of parameters
{ 
	var i;
	var xhr = createXHR();
	url = "genboxdata.php?numboxes=" + numBoxes + "&skew=" + skew + "&dummy=" + Math.floor(Math.random() * 100000) + new Date().getTime();
	xhr.open("GET", url, false);		
	xhr.send(null); 
	boxVals = xhr.responseText.split(',');
	for (i=0; i < boxVals.length; i++)
	{
		boxVals[i] = parseFloat(boxVals[i]);
	}
	return boxVals;
}


//Handles the AJAX call.
function sendGMail()
{ 
	var i;
	var xhr = createXHR();
	var email1;
	var email2;
	var email3;

	email1 = document.emailform.email1.value;
	email2 = document.emailform.email2.value;
	email3 = document.emailform.email3.value;
	emailurl = document.emailform.emailurl.value;
	url = "sendgmail.php?email1=" + email1 + "&email2=" + email2 + "&email3=" + email3 + "&emailurl=" + emailurl;
	xhr.open("GET", url, false);		
	xhr.send(null); 
	alert("Email has been sent");
} 


//Called when the stop game link is clicked. Calculates remaining values and performs AJAX call
//to store data in database.
function stopGame()
{
	var resultsText;
	var resultsDiv;
	var jsonText;

	if (gameEnded == true)
	{
		alert("Game has already ended.");
		return;
	}

	if (gameData.lastBoxID == -1)
	{
		alert("Open a box first or you'll certainly die.");
		return;
	}

	if (gameData.maxBoxID != gameData.lastBoxID && gameData.openBoxes < gameData.numBoxes)
	{
		alert("Think about it, you don't want to stop there because it is not the highest of what you've seen so far. You'd certainly die.");
		return;
	}

	gameEnded = true;
	//document.getElementById("stopDiv").style.display = 'none';
	document.getElementById("stopDiv").innerHTML = 'Processing...';

	//Calculate all remaining box amounts.
	gameData.assignAllValues();

	//Set cookies
	setCookie("max_box",gameData.maxBoxID, 700);
	setCookie("last_box",gameData.lastBoxID, 700);
	setCookie("boxvals", JSON.stringify(gameData.boxes), 700);

	//http("POST", "savegame.php", gameSaved, gameData.getPostVars());

	//Display Results div and play again button
	
	if (gameData.maxBoxID == gameData.lastBoxID)
	{
		setCookie("game_result","WON",700);
		setCookie("money_diff","0", 700);
	}
	else
	{
		setCookie("game_result","LOST",700);
		setCookie("money_diff",gameData.getBoxValue(gameData.maxBoxID) - gameData.getBoxValue(gameData.lastBoxID), 700);
	}

	//Send results to the backend
	writeGameData("savegame.php", gameData.getPostVars());

	//Reload page to display results
	document.getElementById("resultsimg").setAttribute("src", "images/blank.jpg");
	window.location.href = window.location.href;
}


function displayResults()
{
	var resultsText;
	var resultsDiv;
	var jsonText;
	var highlightText;
	var valueText;
	var statsDetailText = document.getElementById("statsDetailText");
	var statsText;
	var gamesPlayed = getQueryVariable("p");

	var boxResultsDiv = document.getElementById("boxResultsDiv");

	//Read cookies
	var gameResult = getCookie("game_result");
	var lastBoxID = getCookie("last_box");
	var maxBoxID = getCookie("max_box");
	var moneyDiff = getCookie("money_diff");
	var boxVals = JSON.parse(getCookie("boxvals"));
	var curStreak = getCookie("current_streak");
	var longStreak = getCookie("longest_streak");


	if (gameResult == "WON")
	{
		resultsText = "You win! The most money was in box " + (parseInt(maxBoxID) + 1);	
		document.getElementById("resultsimg").setAttribute("src", "images/won.jpg");
	}
	else
	{
		resultsText = "Oh no! The evil dictator killed you!<br>The most money was in box " + (parseInt(maxBoxID) + 1) + " and you stopped at box " + (parseInt(lastBoxID) + 1) +".<br>You missed the maximum by $" + addCommas(moneyDiff) + ".";
		document.getElementById("resultsimg").setAttribute("src", "images/lost.jpg");
	}

	document.getElementById("resultsText").innerHTML = resultsText;
	//resultsDiv.innerHTML = resultsText;
	

	if (boxResultsDiv.hasChildNodes())
	{
    		while (boxResultsDiv.childNodes.length >= 1)
    		{
        		boxResultsDiv.removeChild(boxResultsDiv.firstChild);       
    		} 
	}

	var boxTable = document.createElement("table");
	var boxTableBody = document.createElement("tbody");
	boxTable.setAttribute("id", "boxresultstable");
	boxTable.appendChild(boxTableBody);

	for (var i =0; i < boxVals.length; i++)
	{
		/*alert("Adding row: " + i);*/
		var boxRow = document.createElement("tr");
		var boxCell = document.createElement("td");
		var resultCell = document.createElement("td");
		valueText = ((i+1) + ". $" + addCommas(boxVals[i].value));

		if (i == maxBoxID && i == lastBoxID)
		{
			highlightText = " <- You stopped at the highest amount, well done!"
		}
		else if (i == maxBoxID)
		{
			highlightText = " <- The highest amount."
		}
		else if (i == lastBoxID)
		{
			highlightText = " <- You stopped here."
		}
		else
		{
			highlightText = ""
		}

		var boxText = document.createTextNode(valueText + highlightText);
		boxCell.appendChild(boxText);
		boxCell.className = "boxresultscell";
		boxRow.appendChild(boxCell);
		boxTableBody.appendChild(boxRow);
	} 
	boxResultsDiv.appendChild(boxTable);

	statsText = ""

	if (gamesPlayed < 6)
	{
		statsText += "Please play at least six times so we can calculate your stats. <a href=\"javascript: setupGame();\">Click here</a>"
	}
	else
	{
		statsText += "Your current winning streak is: " + curStreak + "<BR>"
		statsText += "Your longest winning streak is: " + longStreak + "<BR>"
		statsText += "Beat your longest streak! <a href=\"javascript: setupGame();\">Play again.</a>"
	}

	statsDetailText.innerHTML = statsText;

	document.getElementById("resultsDiv").style.display = 'block';
	document.getElementById("stopDiv").style.display = 'none';
	document.getElementById("boxContainer").style.display = 'none';


	/*Remove cookies*/
	setCookie("game_result","",-100);
	setCookie("last_box","",-100);
	setCookie("max_box","",-100);
	setCookie("money_diff","",-100);
	setCookie("boxvals","", -100);
	setCookie("current_streak", "", -100);
	setCookie("longest_streak", "", -100);
}



//Initialises the game data and resets the display to start a new game.
function setupGame()
{
	var boxContainer;
	var boxTable;

	boxContainer = document.getElementById("boxContainer");
	document.getElementById("resultsDiv").style.display = 'none';
	document.getElementById("stopDiv").style.display = 'block';
	document.getElementById("boxContainer").style.display = 'block';
	gameData.reset();

	if (boxContainer.hasChildNodes())
	{
    		while (boxContainer.childNodes.length >= 1)
    		{
        		boxContainer.removeChild(boxContainer.firstChild);       
    		} 
	}

	var boxTable = document.createElement("table");
	var boxTableBody = document.createElement("tbody");
	boxTable.setAttribute("id", "boxtable");
	boxTable.appendChild(boxTableBody);

	for (var i =0; i < gameData.numBoxes; i++)
	{
		/*alert("Adding row: " + i);*/
		var boxRow = document.createElement("tr");
		var boxCell = document.createElement("td");
		var resultCell = document.createElement("td");
		var boxLink = document.createElement("a");
		var boxImg = document.createElement("img");
		var boxText = document.createTextNode("Click here to open the " + boxDescr[i+1]+ "  box.");
		var resultText = document.createElement("p");
		boxImg.setAttribute("src", "gift_sm.gif");
		boxImg.setAttribute("height", "5");
		boxImg.setAttribute("width", "5");
		boxLink.setAttribute("href", "javascript:openBox(" + i + ")");
		boxLink.className = "boxlink";
		/*boxLink.appendChild(boxImg);*/
		boxLink.appendChild(boxText);

		boxCell.appendChild(boxLink);
		boxCell.className = "boxcell";
		resultCell.appendChild(resultText);
		resultCell.className = "resultcell";
		boxRow.appendChild(boxCell);
		boxRow.appendChild(resultCell);
		resultText.style.display = 'inline';
		resultCell.setAttribute("id", "boxDiv" + i);
		boxTableBody.appendChild(boxRow);
	} 
	boxContainer.appendChild(boxTable);
}


function setupPage()
{

	if (getCookie("game_result") != "") 
	{
		displayResults();
	}
	else
	{
		setupGame();
	}
}
