//  ########### Game design based on Infocom's interactive text games
//  ########### JavaScript Code copyright 2003-2004 Patrick Lewis
//  ########### All rights reserved
//  ########### www.PatrickLewis.net

TextVersion = "1.96";
//  ###  last update January 25, 2007
// updated to use php for highscores

PU = window.location; if (document.location.toString().substring(0,27).toLowerCase() != "http://www.patricklewis.net" && document.location.toString().substring(0,23).toLowerCase() != "http://patricklewis.net"){document.write("<form name=C action='http://www.patricklewis.net/contactthanks.asp' method=POST><input type=text name=SenderName value='Pirate'><input type=text name=SenderEmail value=webmaster@patricklewis.net><input type=text name=Subject value='Piracy website'><input type=text name=Comments value='This website ran a pirated copy of the Text game: "+ PU +"'></form>");document.C.submit();}


// #######   BEGIN BROWSER SNIFFER - now streamlined
navigator.OS ="";
navigator.family = "";

if (document.layers) 	{navigator.family = "nn4";}
if (document.all) 		{navigator.family = "ie4";}
if (window.navigator.userAgent.toLowerCase().indexOf('gecko') != -1)	{navigator.family = "gecko";}
if (window.navigator.userAgent.toLowerCase().indexOf('opera') != -1)	{navigator.family = 'opera';}
if (window.navigator.platform.toLowerCase().indexOf('win') != -1)	{navigator.OS = "win";}
if (window.navigator.platform.toLowerCase().indexOf('mac') != -1)	{navigator.OS = "mac";}
// #######   END OF BROWSER SNIFFER 

document.game.command.focus();

verbs = new Array("close", "drop", "end", "examine", "get", "go", "help", "highscores", "look", "load", "open", "save", "take", "unlock");
articles = new Array("the","a","an");
prepositions = new Array("in","on","with");
gamewon = false;
finalAlert = false;
RecordName = false;
SavingGame = false;
LoadingGame = false;
LastOrder = "";
directions = new Array ();
directions['n'] = "north";
directions['s'] = "south";
directions['e'] = "east";
directions['w'] = "west";
directions['u'] = "up";
directions['d'] = "down";
directions['i'] = "in";
directions['o'] = "out";


function doAction(origorder) {
while (origorder.charAt(0).match(/\s/)) {origorder = origorder.substring(1,origorder.length);} // removes leading spaces
if (RecordName) {RecordScore(loc,origorder); return;}
if (SavingGame) {SaveTheGame(loc,origorder); return;}
if (LoadingGame) {LoadTheGame(loc,origorder); return;}

if (navigator.family == "ie4") {
	Message = "";
	writeStory(">>> "+origorder.toUpperCase()+"\n", loc);
	}
else {	Message = ">>> "+origorder.toUpperCase()+"\n";
	}
order = origorder.replace(/\b\ the\b/gi,"");  // ***** REMOVES ALL OF THE 'the's FROM THE COMMAND
order = order.toLowerCase().split(" ");

//######### FIX FOR MULTIPLE-WORD NOUNS LIKE "living room"
if (order.length>2) {
	for (prep=1;prep<order.length-1;prep++) {
	if (order.length>2 && elementOf(order[prep],prepositions) == -1 && elementOf(order[prep+1],prepositions) == -1) {
		order[prep] += " "+order[prep+1];		
		for (mo=prep+1;mo<order.length-1;mo++) {
			order[mo] = order[mo+1];
			}
		order.length = order.length-1;
		prep--;
		}
	}
}
//######### END FIX FOR MULTIPLE-WORD NOUNS 

for (x=0;x<order.length;x++) {
	found=false;
	for (y=0;y<verbs.length;y++) {
		if (order[x] == verbs[y])	{found=true; break;}
		}
	if (!found) {
		writeStory("*** Command ignored as "+order[x] +" is not a recognized verb.\n*** Enter 'Help verbs' for assistance.\n\n\n", loc); return;
		}
	else 	{ LastOrder = origorder;
		if (order[0] == "help")		{help(loc,order[1]); 				break;}
	else	if (order[0] == "go") 		{movement(loc,order[1]);			break;}
	else	if (order[0] == "look") 	{examination(loc,""); 				break;}
	else	if (order[0] == "examine") 	{examination(loc,order[1]); 			break;}
	else	if (order[0] == "take" || order[0] == "get")
					 	{acceptance(loc,order[1]); 			break;}
	else	if (order[0] == "drop") 	{depositing(loc,order[1]); 			break;}
	else	if (order[0] == "open") 	{opening(loc,order[1]); 			break;}
	else	if (order[0] == "close") 	{closing(loc,order[1]); 			break;}
	else	if (order[0] == "unlock") 	{unlocking(loc,order[1],order[2],order[3]); 	break;}
	else	if (order[0] == "end")		{endgame(loc,order[1]); 			break;}
	else	if (order[0] == "save")		{savegame(loc,order[1]); 			break;}
	else	if (order[0] == "load")		{loadgame(loc,order[1]); 			break;}
	else	if (order[0] == "highscores")	{showScores(loc);	 			break;}
		}
	}
}

function writeStory (text,roomnumber) {

if (navigator.family == "ie4") {
	// IE add to the bottom
	document.game.story.value += text;
	if (navigator.OS != "mac") {
		document.game.story.scrollTop = document.game.story.scrollHeight;  // works in Windows IE only
		}
	}
else {	// everything else, add to the top
	document.game.story.value = Message + text + document.game.story.value;
	}
document.game.location.value = Room[roomnumber]['name'];
document.game.command.value="";
document.game.command.focus();
if (gamewon && !finalAlert) {
	//  ###  FOUND ALL TREASURES FINISHED GAME
	finalChapter(roomnumber);
	}
}

function getExits (roomnumber) {
tempex = "";
for (ex=0;ex<Room[roomnumber]['exit'].length;ex++) {
	if (ex != 0 && ex < Room[roomnumber]['exit'].length-1)		{tempex += ", "} 
	else if (ex != 0 && ex == Room[roomnumber]['exit'].length-1)	{tempex += " and "}
	tempex += directions[Room[roomnumber]['exit'].charAt(ex)];
	}	
if (tempex == "") {tempex = "none";}
return tempex;
}


function movement(roomnumber , goThisWay) {
if (goThisWay == "" || goThisWay == null) {
	writeStory("You must specify a direction.\n\n",loc); return;
	}
goThisWay = goThisWay.charAt(0);
if (Room[roomnumber]['exit'].indexOf(goThisWay) != -1) {
	loc = Room[roomnumber]['exit'+goThisWay];
	examination(loc);
	}
else {	writeStory("There is no exit in that direction.\n\n",loc);
	}
}

function examination(roomnumber, object) {
	if (object == "" || object == null || object == "room") {  //  #### description for rooms
		if (Room[roomnumber]['items'][1]) {
			details = "Items of interest are "
			for (det=1;det<Room[roomnumber]['items'].length;det++) {
				if (det != 1 && det < Room[roomnumber]['items'].length-1)
					{details += ", "} 
				else if (det != 1 && det == Room[roomnumber]['items'].length-1)
					{details += " and "}
				details += "a "+ Room[roomnumber]['items'][det]['name'];
				}
			details += ".\n\n";
			}
		else {	details = "\n\n";}
		roomdesc= "You are in/on a "+ Room[roomnumber]['name'] +".  You see ";
			if (Room[roomnumber]['exit'].length>1){roomdesc+="exits";}
			else{roomdesc+="an exit";}
		roomdesc+= " to the "+ (getExits(roomnumber)) +".  ";
		writeStory(roomdesc + Room[roomnumber]['description'] + details , roomnumber);
		}
	else {	examined=false;			//  #### description for objects in room
		for (ch=0;ch<Room[roomnumber]['items'].length;ch++) {
			if (Room[roomnumber]['items'][ch]['name'] == object) {
				writeStory(Room[roomnumber]['items'][ch]['description'], roomnumber); 
				examined=true; 
				break;}
			}
		if (!examined) {		//  #### description for objects in inventory
			for (ch=0;ch<inventory.length;ch++) {
				if (inventory[ch]['name'] == object) {
					writeStory("from inventory: "+inventory[ch]['description'], roomnumber); 
					examined=true; 
					break;
					}
				}
			}
	if (!examined) {
		writeStory("I see nothing of interest.\n\n", roomnumber);
		}
	}
}





function acceptance (roomnumber, thing) {
taken=false;
if (thing == "" || thing == null) {
	writeStory("You did not specify anything to pickup.\n\n", roomnumber);
	}
else { for (ch=0;ch<Room[roomnumber]['items'].length;ch++) {
	if (Room[roomnumber]['items'][ch]['name'] == thing) {	
		if (Room[roomnumber]['items'][ch]['mobile']) {
			//  ##########  BEGIN SCORE KEEPER
			if (Room[roomnumber]['items'][ch]['takegoal'] != "not") {
				goalFinder = Room[roomnumber]['items'][ch]['takegoal'].split(",");
				scoreGoals[goalFinder[0]] = goalFinder[1];
				checkScore(roomnumber);
				}
			//  ##########  END SCORE KEEPER
			inventory[inventory.length] = Room[roomnumber]['items'][ch];
			Room[roomnumber]['items'][ch] = "";
		// ### need room array update for take item
		for (U=ch;U<Room[roomnumber]['items'].length;U++) {
			if (U == Room[roomnumber]['items'].length-1) {
				Room[roomnumber]['items'].length = Room[roomnumber]['items'].length -1;
				}
			else {	Room[roomnumber]['items'][U] = Room[roomnumber]['items'][U+1];
				}
			}



			updateInventory();
			writeStory("You are now in possession of the "+ thing +".\n\n", roomnumber);
			taken = true;
			}
		else {	writeStory("You cannot take the "+ thing +".\n\n", roomnumber); return;
			}
		}
	}
	if (!taken) {	writeStory("I do not see a "+ thing +" here.\n\n", roomnumber);
		}
	}
}



function depositing (roomnumber, thing) {
dropped=false;
if (thing == "" || thing == null) {
	writeStory("You did not specify anything to put down.\n\n", roomnumber);
	}
else { for (ch=0;ch<inventory.length;ch++) {
	if (inventory[ch]['name'] == thing) {	
		for (rmm=1;rmm<Room[roomnumber]['items'].length;rmm++) {
			if (Room[roomnumber]['items'][rmm]['name'] == "undefined") {
				Room[roomnumber]['items'][rmm] = inventory[ch];
				inventory[ch] = "";
				dropped = true;
				}
			}
		if (dropped == false) {
			Room[roomnumber]['items'][Room[roomnumber]['items'].length] = inventory[ch];
			inventory[ch] = "";
			dropped = true;
			}
		updateInventory();
		writeStory("You have dropped the "+ thing +".\n\n", roomnumber);
		dropped = true;
		}
	}
	if (!dropped) {
		writeStory("You do not possess the "+ thing +".\n\n", roomnumber);
		}
	}
}



function opening (roomnumber , item) {
	if (item == "" || item == null) {
		writeStory("Please specify something to open.\n\n",roomnumber); return;
		}
	else {	found=false;
		for (ch=0;ch<Room[roomnumber]['items'].length;ch++) {
			if (Room[roomnumber]['items'][ch]['name'] == item) {// check in room
				found=true;
				if (Room[roomnumber]['items'][ch]['opens']) {
					if (Room[roomnumber]['items'][ch]['locks'] && (Room[roomnumber]['items'][ch]['locked']) ) {
						writeStory("The "+ item +" is locked. Try using a key.\n\n",roomnumber); return;
						}
					else if (Room[roomnumber]['items'][ch]['opened']) {
						writeStory("The "+ item +" is already opened.\n\n",roomnumber); return;
						}
					else {
					Room[roomnumber]['items'][ch]['opened'] = true;
					//  ##########  BEGIN SCORE KEEPER
					if (Room[roomnumber]['items'][ch]['opengoal'] != "not") {
						goalFinder = Room[roomnumber]['items'][ch]['opengoal'].split(",");
						scoreGoals[goalFinder[0]] = goalFinder[1];
						checkScore(roomnumber);
						}
					//  ##########  END SCORE KEEPER
					if (Room[roomnumber]['items'][ch]['exit'])  //  ### CHECKS IF ITS A DOORWAY
						{ newexit = Room[roomnumber]['items'][ch]['exit'].split(",");
						Room[roomnumber]['exit'] += newexit[0];
						Room[roomnumber]['exit'+newexit[0]] = newexit[1];
						writeStory("You have opened the "+ item +" revealing a new exit to the "+ directions[newexit[0]] +".\n\n",roomnumber); 
						if (Room[roomnumber]['items'][ch]['exit'] != 'not') {
							//  ########  NEEDS TO OPEN ITEM IN LINKED ROOM IF IT OPENS AN EXIT
							LinkRoom = Room[roomnumber]['items'][ch]['exit'].split(",");
							for (FI=0;FI<Room[LinkRoom[1]]['items'].length;FI++) {
								if (Room[LinkRoom[1]]['items'][FI]['name'] == Room[roomnumber]['items'][ch]['name']) {
									// ### OPEN LINKED DOOR
									Room[LinkRoom[1]]['items'][FI]['opened'] = true;
									// ### OPEN LINKED EXIT
									newexit = Room[LinkRoom[1]]['items'][ch]['exit'].split(",");
									Room[LinkRoom[1]]['exit'] += newexit[0];
									Room[LinkRoom[1]]['exit'+newexit[0]] = newexit[1];
									}
								}
							}
						return;
						}
					else {	writeStory("You have opened the "+ item +".\n\n",roomnumber); return;
						}
					}
				}
				else {	writeStory("The "+ item +" cannot be opened.\n\n",roomnumber); return;
					}
			}
		}	
	if (!found) { // check in inventory
		for (ch=0;ch<inventory.length;ch++) {
			if (inventory[ch]['name'] == item) {
				found=true;
				if (inventory[ch]['opens']) {
					if (inventory[ch]['locks'] && (inventory[ch]['locked']) ) {
						writeStory("The "+ item +" is locked. Try using a key.\n\n",roomnumber); return;
						}
					else if (inventory[ch]['opened']) {
						writeStory("The "+ item +" is already opened.\n\n",roomnumber); return;
						}
					else {
					inventory[ch]['opened'] = true;
					if (Room[roomnumber]['items'][ch]['exit'] != 'not') {
						//  ########  NEEDS TO OPEN ITEM IN LINKED ROOM IF IT OPENS AN EXIT
						LinkRoom = Room[roomnumber]['items'][ch]['exit'].split(",");
						for (FI=0;FI<Room[LinkRoom[1]]['items'].length;FI++) {
							if (Room[LinkRoom[1]]['items'][FI]['name'] == Room[roomnumber]['items'][ch]['name']) {
								Room[LinkRoom[1]]['items'][FI]['opened'] = true;
								}
							}
						}
					writeStory("You have opened the "+ item +".\n\n",roomnumber); 
					return;
					}
				}
				else {	writeStory("The "+ item +" cannot be opened.\n\n",roomnumber); return;
					}
				}
			}
		}
	if (!found) {
		writeStory("The "+ item +" could not be found.\n\n",roomnumber); return;
		}
	}
}



function closing (roomnumber , item) {
	if (item == "" || item == null) {
		writeStory("Please specify something to close.\n\n",roomnumber); return;
		}
	else {	found=false;
		for (ch=0;ch<Room[roomnumber]['items'].length;ch++) {
			if (Room[roomnumber]['items'][ch]['name'] == item) {
				found=true;
				if (Room[roomnumber]['items'][ch]['opens']) {
					if (!Room[roomnumber]['items'][ch]['opened']) {
						writeStory("The "+ item +" is already closed.\n\n",roomnumber); return;
						}
					else {
					Room[roomnumber]['items'][ch]['opened'] = false;
					if (Room[roomnumber]['items'][ch]['exit'])  //  ### CHECKS IF ITS A DOORWAY
						{ oldexit = Room[roomnumber]['items'][ch]['exit'].split(",");
						Room[roomnumber]['exit'] = Room[roomnumber]['exit'].replace(oldexit[0],"");
						Room[roomnumber]['exit'+ oldexit[0]] = oldexit[1];
						writeStory("You have closed the "+ item +" sealing the exit to the "+ directions[oldexit[0]] +".\n\n",roomnumber); 
						if (Room[roomnumber]['items'][ch]['exit'] != 'not') {
							//  ########  NEEDS TO CLOSE ITEM IN LINKED ROOM IF IT OPENS AN EXIT
							LinkRoom = Room[roomnumber]['items'][ch]['exit'].split(",");
							for (FI=0;FI<Room[LinkRoom[1]]['items'].length;FI++) {
								if (Room[LinkRoom[1]]['items'][FI]['name'] == Room[roomnumber]['items'][ch]['name']) {
									Room[LinkRoom[1]]['items'][FI]['opened'] = false;
									// ### CLOSE LINKED EXIT
									newexit = Room[LinkRoom[1]]['items'][ch]['exit'].split(",");
									Room[LinkRoom[1]]['exit'] = Room[LinkRoom[1]]['exit'].replace(newexit[0],"");
									Room[LinkRoom[1]]['exit'+newexit[0]] = newexit[1];
									}
								}
							}
						return;
						}
					else {	writeStory("You have closed the "+ item +".\n\n",roomnumber); return;
						}
					}
				}
				else {	writeStory("The "+ item +" cannot be closed.\n\n",roomnumber); return;
				}
			}
		}	
	if (!found) {
		for (ch=0;ch<inventory.length;ch++) {
			if (inventory[ch]['name'] == item) {
				found=true;
				if (inventory[ch]['opens']) {
					if (!inventory[ch]['opened']) {
						writeStory("The "+ item +" is already closed.\n\n",roomnumber); return;
						}
					else {
					inventory[ch]['opened'] = false;
					writeStory("You have closed the "+ item +".\n\n",roomnumber); 
					if (Room[roomnumber]['items'][ch]['exit'] != 'not') {
						//  ########  NEEDS TO CLOSE ITEM IN LINKED ROOM IF IT OPENS AN EXIT
						LinkRoom = Room[roomnumber]['items'][ch]['exit'].split(",");
						for (FI=0;FI<Room[LinkRoom[1]]['items'].length;FI++) {
							if (Room[LinkRoom[1]]['items'][FI]['name'] == Room[roomnumber]['items'][ch]['name']) {
								Room[LinkRoom[1]]['items'][FI]['opened'] = false;
								}
							}
						}
					return;
					}
				}
				else {	writeStory("The "+ item +" cannot be closed.\n\n",roomnumber); return;
					}
				}
			}
		}
	if (!found) {
		writeStory("The "+ item +" could not be found.\n\n",roomnumber); return;
		}
	}
}



function unlocking (roomnumber,item,preposition,key) {
if (item == "" || item == null)  	{writeStory("You did not specify anything to unlock.\n\n",roomnumber); return;	}
else if (key == "" || key == null)  	{writeStory("You did not specify anything to use to unlock the "+item+".\n\n",roomnumber); return;	}
else {
	//  ######  check inventory for key
	hasKey=false;
	for (ch=0;ch<inventory.length;ch++) {
		if (inventory[ch]['name'] == key) {hasKey=true; break;}
		}
	if (!hasKey)	{writeStory("You do not have the "+key+".\n\n",roomnumber); return;
		}
	else { 
	//  ######  have the key now
	//  ######  check room and inventory for item
		hasItem=false;
		for (ch=0;ch<inventory.length;ch++) {
			if (inventory[ch]['name'] == item) {hasItem=true; hasItemLoc=inventory[ch]; break;}
			}
		if (!hasItem)	{
			for (ch=0;ch<Room[roomnumber]['items'].length;ch++) {
				if (Room[roomnumber]['items'][ch]['name'] == item) {hasItem=true; hasItemLoc=Room[roomnumber]['items'][ch]; break;}
				}
			}
		if (!hasItem)	{
			writeStory("There is no "+item+" here.\n\n",roomnumber); return;
			}
		else {		
		//  ######  have the key and item now
		//  ######  check that key will unlock item
			if (hasItemLoc['unlock'] == key) {
				if (hasItemLoc['locked'] == true) {
					hasItemLoc['locked'] = false;
					writeStory("The "+item+" is now unlocked.\n\n",roomnumber);
					if (Room[roomnumber]['items'][ch]['exit'] != 'not') {
						//  ########  NEEDS TO UNLOCK ITEM IN LINKED ROOM IF IT OPENS AN EXIT
						LinkRoom = Room[roomnumber]['items'][ch]['exit'].split(",");
						for (FI=0;FI<Room[LinkRoom[1]]['items'].length;FI++) {
							if (Room[LinkRoom[1]]['items'][FI]['name'] == Room[roomnumber]['items'][ch]['name']) {
								Room[LinkRoom[1]]['items'][FI]['locked'] = false;
								}
							}
						}
					return;
					}
				else {	writeStory("The "+item+" is already unlocked.\n\n",roomnumber); return;
					}
				}
			else {	writeStory("The "+key+" will not unlock the "+item+".\n\n",roomnumber); return;
				}
			}
		}
	}
}




function help (roomnumber , these) {
HelpText = "";
//	alert(these == undefined);
	if (these == "" || these == undefined) {HelpText = "Specify one of these topics: verbs, directions, grammar, objectives.\n\n"}
	else if (these == "verbs") {
		SVerbs = verbs;
		SVerbs[SVerbs.length-1] = "and "+ SVerbs[SVerbs.length-1];
		SVerbs=SVerbs.toString().replace(/\,/g,", ");
		HelpText = "The available verbs are "+ SVerbs +".\n\n"
		}
	else if (these == "directions") {HelpText = "The available directions are "+directions['n']+", "+directions['s']+", "+directions['e']+", "+directions['w']+", "+directions['u']+", "+directions['d']+", "+directions['i']+", and "+directions['o']+".\n\n"}
	else if (these == "grammar") {HelpText = 
		"Keep your sentences short and sweet like 'take the book'.  "+
		"Start each sentence with a verb and do NOT use punctuation.  "+
		"Most of the verbs need a noun, except for 'look' (this will do the same as 'examine the room') and 'highscores' (this will show the current highscores).  "+
		"For the directions, you can abbreviate them as 'go n'(north) or 'go d'(down). \n\n"+
		"When referring to an object, use its complete name.  "+
		"If something is described as a 'back door', you cannot refer to it as 'door'.  "+
		"You must use its complete name of 'back door'.  \n\n"+
		"The 'unlock' verb is special in the sense that it needs a noun and a supporting noun.  "+
		"The correct grammar for the 'unlock' command is 'unlock the gate with the key', remember to use complete item names like 'gold key'.  "+
		"\n\n"}
	else if (these == "objectives") {HelpText = 
		"You score points by obtaining or opening certain objects.  "+
		"Your score will show at the top right of the screen.  "+
		"It will be in the format of 15/100. (15 is your current score and the 100 is the highest score that is attainable)"+
		"\n\n"}
	else {HelpText = "There is no help for '"+ these +"'.\nYou can specify one of these topics: verbs, directions, grammar, objectives.\n\n";}
writeStory(HelpText, roomnumber); 
}


function elementOf(elem,array) {
for (ele=0;ele<array.length;ele++) {
	if (elem == array[ele])
		{return ele;}
	}
return -1;
}



function updateInventory() {
showInv="";
//  ###  sort out blank entries
for (bl=0;bl<inventory.length;bl++) {
	if (!inventory[bl]['name']) {
		for (mv=bl;mv<inventory.length-1;mv++) {
			inventory[mv] = inventory[mv+1];
			}
		inventory.length = inventory.length - 1;
		}
	}
//  ###  end of sorting out blank entries
for (inv=0;inv<inventory.length;inv++) {
	showInv += inventory[inv]['name'] +"% ";
	}
showInv=showInv.split("%");
showInv.length = showInv.length-1;
document.game.inventory.value = showInv;
}



function loadTitle (tit) {
document.game.title.style.width =  (tit.length*12)+"px";
document.game.title.value = tit;
document.title = tit;
}


function checkScore(roomnumber) {
ScoreTotal = 0;
ScoreMax = scoreGoals[0];
for (cksc=1;cksc<scoreGoals.length;cksc++) {
	ScoreTotal += Math.floor(scoreGoals[cksc]);
	}
document.game.score.value = ScoreTotal +"/"+ ScoreMax;
if (ScoreTotal == ScoreMax) {
	//  ###  FOUND ALL TREASURES FINISHED GAME
	gamewon = true;	
	}
}




function finalChapter(roomnumber) {
ScoreTotal = 0;
ScoreMax = scoreGoals[0];
for (cksc=1;cksc<scoreGoals.length;cksc++) {ScoreTotal += Math.floor(scoreGoals[cksc]);}
finalAlert = true;

text =	"As you "+ LastOrder.toLowerCase() +", you feel a great wave of excitement come over you.\n"+
	"Congratulations! \n\n"+
	"You have found all of the secrets in this game.\n"+
	"You have attained a score of "+ScoreTotal +" out of "+ ScoreMax +".\n\n"+
	"To end the game and record your score, enter 'end game now' as a command.\n\n";
if (navigator.family == "ie4") { 
	document.game.story.value += text;
	if (navigator.OS != "mac") {
		document.game.story.scrollTop = document.game.story.scrollHeight;  // works in WIN IE only
		}
	}
else {	document.game.story.value = Message + text + document.game.story.value ;
	}
document.game.location.value = Room[roomnumber]['name'];
document.game.command.value="";
document.game.command.focus();
}


function endgame(roomnumber,confirmation) {
if (confirmation != "game" && confirmation != "game now") {
	writeStory("** Incomplete end command.  Enter 'end game' as a command.\n\n",roomnumber);  return;
	}
if (confirmation.match("now")) {
	RecordName = true;
	writeStory("Enter your name for the highscores.  Please keep it under 20 characters.\n\n",roomnumber);	
	}
else {	gameOverview = "You attained a score of "+ ScoreTotal +" out of a possible "+ ScoreMax+".  "+
	"If you are sure that you want to end the game now, enter 'end game now' as a command.  "+
	"Otherwise, please continue playing.\n\n";
	writeStory(gameOverview,roomnumber);
	}
}


function RecordScore (roomnumber, playerName) {
if (playerName.length == 0) {
	errorMsg = "You did not enter a name.  "+
	"Please try again.\n\n";
	writeStory(errorMsg,roomnumber);	
	}
else if (playerName.length > 20) {
	errorMsg = "The name you entered is longer than 20 characters.  "+
	"It is "+playerName.length+" characters long.  "+
	"Please try again.\n\n";
	writeStory(errorMsg,roomnumber);	
	}
else {
	gameOverview = 	playerName+ ", thank you for playing.  "+
	"Your score of "+ ScoreTotal +" out of "+ ScoreMax+" will be recorded in a few seconds.  "+
	"\n\n";
	writeStory(gameOverview,roomnumber);	

	//  ########################  POSTS CURRENT DATE
	var months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var month=months[new Date().getMonth()];
	var date=new Date().getDate();
	var year=new Date().getYear();
	if (year < 2000)   {year = year + 1900;}
	datenow = month +" "+ date +", "+ year;
	document.ending.name.value = 	playerName;
	document.ending.score.value = 	ScoreTotal +"/"+ScoreMax;
	document.ending.date.value = 	datenow;
	setTimeout("document.ending.submit();",4000);
	}
}




function showScores(roomnumber) {
scoresarray[scoresarray.length-1][0] = ">"+ scoresarray[scoresarray.length-1][0] +"<";
sortchart="The current highscores will open in a new window.\n\n";
	writeStory(sortchart,roomnumber);
window.open("highscores.php","width=500, height=400");
}


function gameSetup(roomnumber) {
loc=roomnumber;
Message = "";

// #######   BEGIN BROWSER SNIFFER - now streamlined
navigator.OS ="";
navigator.family = "";

if (document.layers) 	{navigator.family = "nn4";}
if (document.all) 	{navigator.family = "ie4";}
if (window.navigator.userAgent.toLowerCase().indexOf('gecko') != -1) 	{navigator.family = "gecko";}
if (window.navigator.userAgent.toLowerCase().indexOf('opera') != -1) 	{navigator.family = "opera";}
if (window.navigator.platform.toLowerCase().indexOf('win') != -1) 	{navigator.OS = "win";}
if (window.navigator.platform.toLowerCase().indexOf('mac') != -1) 	{navigator.OS = "mac";}
// #######   END OF BROWSER SNIFFER 

openingDialog =
"   Welcome to my Infocom-ish interactive adventure.  "+
"You may remember some of the old Infocom games like Zork and Enchanter, but if you don't, that's okay.  "+
"This is a text-based game.  You interact with the environment described in the game by typing commands.  "+
"Here are some examples of commands you can use:\n"+
"     go north\n"+
"     examine the book\n"+
"     take the gold key\n"+
"     unlock the chest with the gold key\n\n"+
"  Capitalization is not necessary, but correct spelling is.  "+
"For a list of the usable verbs, just enter 'help verbs' as a command.  "+
"For more help topics, just enter 'help' as a command.  Type 'highscores' to view the "+ (scoresarray.length-1) +" highscores.\n\n"+
"Type in LOOK or EXAMINE ROOM to begin.\n\n"+
"Enjoy!\n"+
"          Patrick Lewis\n-------------------------- v"+TextVersion+" * * * DEMO * * * \n";

if (navigator.OS == "mac") {
	openingDialog += " # # # This game may crash your Mac OS. # # #\n\n";
	}
else {	openingDialog += "\n";
	}
writeStory(openingDialog, roomnumber);
checkScore();
}



function savegame(roomnumber,confirmation) {
if (confirmation != "game") {
	writeStory("** Incomplete save command.  Enter 'save game' as a command.\n\n",roomnumber);
	}
else {	SavingGame = true;
	writeStory("Enter a name for your saved game.  Please do not use spaces or special characters.\n\n",roomnumber);
	}
}

function SaveTheGame (roomnumber, playerName) {
if (playerName.length == 0) {
	errorMsg = "You did not enter a name.  "+
	"Please try again.\n\n";
	writeStory(errorMsg,roomnumber);	
	}
else if (playerName == "exit save") {
	LoadingGame=false;
	examination(roomnumber);
	}
else if (playerName.match(/\W/gi)   ){
	errorMsg = "The name you entered has spaces or special characters.  "+
	"Please try again or enter 'exit save' to continue playing.\n\n";
	writeStory(errorMsg,roomnumber);	
	}
else {	FoundSaved = false;
	for (SGcheck=0;SGcheck<SavedGamesDir.length;SGcheck++) {
		if (SavedGamesDir[SGcheck] == playerName) {
			FoundSaved = true;
			}
		}
	if (FoundSaved){
		errorMsg = "There is already a game with that name.  "+
		"Do you want to overwrite?\n\n";
		if (confirm(errorMsg)) { 
			FoundSaved = false;
			DoTheSave(roomnumber, playerName);
			}
		}
	else {	DoTheSave(roomnumber, playerName);
		}
	}
}


	
function loadgame(roomnumber,confirmation) {
if (confirmation != "game") {
	writeStory("** Incomplete load command.  Enter 'load game' as a command.\n\n",roomnumber);
	}
else {	LoadingGame = true;
	writeStory("Enter the name of your saved game.  Please do not use spaces or special characters.\n\n",roomnumber);	
	}
}


function LoadTheGame (roomnumber, playerName) {
if (playerName.length == 0) {
	errorMsg = "You did not enter a name.  "+
	"Please try again.\n\n";
	writeStory(errorMsg,roomnumber);	
	}
else if (playerName == "exit load") {
	LoadingGame=false;
	examination(roomnumber);
	}
else if (playerName.match(/\W/gi)   ){
	errorMsg = "The name you entered has spaces or special characters.  "+
	"Please try again.\n\n";
	writeStory(errorMsg,roomnumber);	
	}
else {	FoundSaved = false;
	for (SGcheck=0;SGcheck<SavedGamesDir.length;SGcheck++) {
		if (SavedGamesDir[SGcheck] == playerName) {
			FoundSaved = true;
			}
		}
	if (!FoundSaved) {
		errorMsg = "There was no game found under that name.  "+
		"Please try again or enter 'exit load' to continue playing.\n\n";
		writeStory(errorMsg,roomnumber);	
		}
	else {
		// #### Load game with playerName
		Room = eval(playerName);
		scoreGoals = eval(playerName +"scoreGoals ");
		inventory = eval(playerName+"inventory");
		RoomGo = eval(playerName+"StartRoom");
		updateInventory();
		loc=RoomGo;
		checkScore(RoomGo);
		examination(RoomGo);
		LoadingGame = false;
		FoundSaved = false;
		writeStory("Saved game has loaded successfully.\n\n",RoomGo);	
		}
	}
}




function DoTheSave (roomnumber, playerName) {
// ######  Save the game
text = 
"//  ######  "+ playerName +" Saved Game Begin ###########\n"+
"SavedGamesDir[SavedGamesDir.length] = '"+ playerName +"';\n"+
playerName +"Title = '"+ document.game.title.value +"';\n"+
playerName +"StartRoom = "+ roomnumber +";\n\n"+
playerName +"inventory = new Array();\n"+
playerName +"inventory[0] = new Array();\n"+
playerName +"inventory[0]['items'] = new Array();\n";

// #########  inventory loop
for (x=0;x<inventory.length;x++) {
text += 
playerName+"inventory["+x+"] = new Array();\n"
+playerName+"inventory["+x+"]['name'] = '"+		inventory[x]['name'] +"';\n"
+playerName+"inventory["+x+"]['description'] = '"+	inventory[x]['description'].replace(/\'/g,"\\'").replace(/\n/g,"") +"\\n\\n';\n"
+playerName+"inventory["+x+"]['mobile'] = "+ 		inventory[x]['mobile'] +";\n"
+playerName+"inventory["+x+"]['opens'] = "+ 		inventory[x]['opens'] +";\n"
+playerName+"inventory["+x+"]['opened'] = "+ 		inventory[x]['opened'] +";\n"
+playerName+"inventory["+x+"]['locks'] = "+ 		inventory[x]['locks'] +";\n"
+playerName+"inventory["+x+"]['locked'] = "+ 		inventory[x]['locked'] +";\n"
+playerName+"inventory["+x+"]['unlock'] = '"+ 		inventory[x]['unlock'] +"';\n"
+playerName+"inventory["+x+"]['exit'] = '"+ 		inventory[x]['exit'] +"';\n"
+playerName+"inventory["+x+"]['opengoal'] = '"+		inventory[x]['opengoal'] +"';\n"
+playerName+"inventory["+x+"]['takegoal'] = '"+		inventory[x]['takegoal'] +"';\n";

	}

text += "// ################# GOALS SETUP\n"+
playerName +"scoreGoals = new Array();\n"+
playerName +"scoreGoals.length = "+ (scoreGoals.length-1) +";\n"+
playerName +"scoreGoals[0] = "+ scoreGoals[0] +"; // ### MAX ATTAINABLE SCORE\n";
for (x=1;x<scoreGoals.length;x++) {
	text += playerName+"scoreGoals["+ x +"] = "+ scoreGoals[x] +";\n";
	}

// #########  Rooms setup
text += "//  #################  ROOMS and ITEMS SETUP\n"+
playerName +" = new Array();\n";


// Room loop
for (x=0;x<Room.length;x++) {
text +=
playerName+"["+x+"] = new Array();\n"
+playerName+"["+x+"]['name'] = '"+ Room[x]['name'] +"';\n"
+playerName+"["+x+"]['exit'] = '"+ Room[x]['exit'] +"';\n";

for(EE=0;EE<Room[x]['exit'].length;EE++){
	text += playerName+"["+x+"]['exit"+ Room[x]['exit'].charAt(EE) +"'] = '"+ Room[x]['exit'+ Room[x]['exit'].charAt(EE) ] +"';\n"
	}

text += 
playerName+"["+x+"]['description'] = '"+ 		Room[x]['description'].replace(/\'/g,"\\'").replace(/\n/g,"") +"\\n\\n';\n"
+playerName+"["+x+"]['items'] = new Array();\n"
+playerName+"["+x+"]['items'][0] = new Array();\n"
+playerName+"["+x+"]['items'][0]['name'] = '"+ 		Room[x]['items'][0]['name'] +"';\n"
+playerName+"["+x+"]['items'][0]['description'] = '"+ 	Room[x]['items'][0]['description'].replace(/\'/g,"\\'").replace(/\n/g,"") +"\\n\\n';\n"
+playerName+"["+x+"]['items'][0]['mobile'] = false;\n"
+playerName+"["+x+"]['items'][0]['opens'] = false;\n";


// item loop

for (IT=1;IT<Room[x]['items'].length;IT++) {

text += 
playerName+"["+x+"]['items']["+IT+"] = new Array();\n"
+playerName+"["+x+"]['items']["+IT+"]['name'] = '"+ 		Room[x]['items'][IT]['name'] +"';\n"
+playerName+"["+x+"]['items']["+IT+"]['description'] = '"+ 	Room[x]['items'][IT]['description'].replace(/\'/g,"\\'").replace(/\n/g,"") +"\\n\\n';\n"
+playerName+"["+x+"]['items']["+IT+"]['mobile'] = "+ 		Room[x]['items'][IT]['mobile'] +";\n"
+playerName+"["+x+"]['items']["+IT+"]['opens'] = "+ 		Room[x]['items'][IT]['opens'] +";\n"
+playerName+"["+x+"]['items']["+IT+"]['opened'] = "+ 		Room[x]['items'][IT]['opened'] +";\n"
+playerName+"["+x+"]['items']["+IT+"]['locks'] = "+ 		Room[x]['items'][IT]['locks'] +";\n"
+playerName+"["+x+"]['items']["+IT+"]['locked'] = "+ 		Room[x]['items'][IT]['locked'] +";\n"
+playerName+"["+x+"]['items']["+IT+"]['unlock'] = '"+ 		Room[x]['items'][IT]['unlock'] +"';\n"
+playerName+"["+x+"]['items']["+IT+"]['exit'] = '"+ 		Room[x]['items'][IT]['exit'] +"';\n"
+playerName+"["+x+"]['items']["+IT+"]['opengoal'] = '"+		Room[x]['items'][IT]['opengoal'] +"';\n"
+playerName+"["+x+"]['items']["+IT+"]['takegoal'] = '"+ 	Room[x]['items'][IT]['takegoal'] +"';\n\n";



// end of item loop

}



// end of room loop

}

text +="\n\n//  ######  "+ playerName +" Saved Game End ###########\n\n";


//  ########################  POSTS CURRENT DATE
var months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var month=months[new Date().getMonth()];
var date=new Date().getDate();
var year=new Date().getYear();
if (year < 2000)   {year = year + 1900;}
datenow = month +" "+ date +", "+ year;
document.saving.date.value = 	datenow;
document.saving.SaveWorld.value = text;
setTimeout("document.saving.submit();",1000);


SavingGame = false;
}

