function flush(s)     { document.write(s);}
function newline()    { return("\n"); }
function openQuote()  { return("\""); }
function closQuote()  { return("\""); }

function lineBreak() { return("<BR>"); }

function openTable() { return("<TABLE "); }
function closTable() { return("</TABLE>"); }

function openTableRow() { return("<TR>"); }
function closTableRow() { return("</TR>"); }

function openTableCel() { return("<TD>"); }
function closTableCel() { return("</TD>"); }

function openCenter() { return("<CENTER>"); }
function closCenter() { return("</CENTER>"); }

function openHeader(rank) { return( "<H" + rank +">"); }
function closHeader(rank) { return("</H" + rank +">"); }

function header(rank, headerString) { return(openHeader(rank) + headerString + closHeader(rank)); }
function headerBR(rank, headerString) { return(header(rank, headerString) + lineBreak()); }

function attrUValue(attr, value)
{
	return(attr + "=" + value + " "); 
}

function attrQValue(attr, value)
{
	return(attr + "=" + openQuote() + value + closQuote() + " "); 
}

function embedSound(soundFile, soundName, volume)
{
	return(
	"<EMBED " + 
	attrQValue("SRC", soundFile) +
	attrUValue("AUTOSTART","NO") +
	attrUValue("HIDDEN", "TRUE") +
	attrUValue("VOLUME", volume) +
	attrQValue("NAME", soundName) +
	"MASTERSOUND>");
}
	
function emptyTableRow()
{
	return( openTableRow() + openTableCel() + closTableCel() + closTableRow() );
}

function linkedImage(linkURL, imagName, border, height, width)
{
	return("<A " +
	attrQValue("HREF", linkURL)  +
	"><IMG " +
	attrQValue("SRC", imagName)  +
	attrQValue("BORDER", border) +
	attrQValue("HEIGHT", height) +
	attrQValue("WIDTH", width )  +
	">");
}

function openFont(fontSize)
{
	return("<FONT " + attrQValue("SIZE", fontSize) + ">");
}

function closFont()
{
	return("</FONT>");
}

function linkedText(fontSize, linkURL, text)
{
	return(openFont(fontSize) + "<A " + attrQValue("HREF", linkURL) + ">"  + text + "</A>" + closFont() );
}

function linkedTextBR(fontSize, linkURL, text)
{
	return(linkedText(fontSize, linkURL, text) + lineBreak());
}

function normalText(fontSize, text)
{
	return(openFont(fontSize) + text + closFont());
}

function normalTextBR(fontSize, text)
{
	return(normalText(fontSize, text) + lineBreak());
}

function buttonTableCel(linkURL, imagName, border, height, width)
{
	return(
		openTableRow() +
			openTableCel() +
				openCenter() +
					linkedImage(linkURL, imagName, border, height, width) +
				closCenter() +
			closTableCel() +
		closTableRow() 
	);
}

function buttonTableRow(linkURL, imagName, border, height, width)
{
	return(
		openTableRow() +
			buttonTableCel(linkURL, imagName, border, height, width) +
		closTableRow()
	);
}

function buttonTableRowDS(linkURL, imagName, border, height, width)
{
	return(
		buttonTableRow(linkURL, imagName, border, height, width) +
		emptyTableRow()
	); // Double Spaced
}
// end of dhtml.js source

// cookie code first
// Sets cookie values. Expiration date is optional
//
function setCookie(name, value, expire)
{
   document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}

function getCookie(Name)
{
	var search = Name + "="

	if (document.cookie.length > 0)	// if there are any cookies
	{
		offset = document.cookie.indexOf(search) 
		if (offset != -1) // if cookie exists 
		{
			 offset += search.length 
			 // set index of beginning of value
			 end = document.cookie.indexOf(";", offset) 
			 // set index of end of cookie value
			 if (end == -1) 
				end = document.cookie.length

			 return unescape(document.cookie.substring(offset, end))
		} 
	}
}

var cookieName = "UAMSPuzzleLevelC";

function setGameLevel(value)
{
	var today = new Date();
	var expires = new Date();
	expires.setTime(today.getTime() + 1000*60*60*24*365);
	setCookie(cookieName, value, expires);
}

function getGameLevel()
{
	level = getCookie(cookieName);
	if(level == null)
		tellDialog("Solve the puzzles, win a prize!");
	else
	{
		level++;
		tellDialog("You are at level " + level);
	}
}

// SoundLocation = "http://k14education.uams.edu/";

/*
 * The Puzzle is ShareWare
 *
 * Copyright (c) 1999 Warren Design Vision  All Rights Reserved.
 *
 * For licensing information contact:
 * L. Van Warren
 * Warren Design Vision (WDV)
 * http://www.wdv.com
 * lvwarren@wdv.com
 *
 */

var gameDirectory = "LargePuzzles/";


var gameFiles = new Array
		(
			"Venous",
			"Arterial",
			"Digestive",
			"Endocrine",
			"Lymphatic",
			"Musculatory",
			"Nervous",
			"Respiratory",
			"Sensory",
			"Skeletal",
			"Artificial"
		); 

var gamePtrn = new Array(gameFiles.length);

gamePtrn[0] =	new Array
		(
			 1,  2,  3,  4,
			 5,  6,  7,  8,
			 9, 10, 11, 12,
			13, 14,  0, 15
		);
gamePtrn[1] =	new Array
		(
			 0,  2,  3,  4,
			 1,  6,  7,  8,
			 5, 10, 11, 12,
			 9, 13, 14, 15
		);
gamePtrn[2] =	new Array
		(
			 2,  3,  4,  0,
			 1,  6,  7,  8,
			 5, 10, 11, 12,
			 9, 13, 14, 15
		);
gamePtrn[3] =	new Array
		(
			 1,  6,  2,  4,
			 0, 10,  3,  8,
			 5, 14,  7, 11,
			 9, 13, 15, 12
		);
gamePtrn[4] =	new Array
		(
			 0,  1,  2,  3,
			 5,  6,  7,  4,
			 9, 10, 11,  8,
			13, 14, 15, 12
		);
gamePtrn[5] =	new Array
		(
			 1,  2,  3,  4,
			 5,  0,  7,  8,
			10,  6, 11, 12,
			 9, 13, 14, 15
		);
gamePtrn[6] =	new Array
		(
			 5,  1,  2,  3,
			 9, 10,  6,  4,
			13,  0,  7,  8,
			14, 15, 11, 12
		);
gamePtrn[7] =	new Array
		(
			 5,  1,  2, 4,
			11,  3,  6, 7,
			10,  9, 15, 0,
			13, 14, 12, 8
		);
gamePtrn[8] =	new Array
		(
			 2,  6,  3,  4,
			 1,  7, 11, 10,
			 5,  9,  0,  8,
			13, 14, 15, 12
		);
gamePtrn[9] =	new Array
		(
			 5,  6,  7,  8,
			 1,  2,  3,  4,
			 9, 10, 11, 12,
			13, 14, 15,  0
		);
gamePtrn[10] =	new Array
		(
			 1,  2,  3,  4,
			 5,  6,  7,  8,
			 9, 10, 11, 12,
			13, 15, 14,  0
		);


var zeroRow=3;
var zeroCol=2;

// to setup a new puzzle,
// set the pattern to 1, 2, 3, 4 etc,
// then run the puzzle backwards.
// for(i = 1; i < 11; I++)
// { gamePtrn[i] = gamePtrn[0]; } // debugging

var gameGrid;
var gameSize= 4;
var image = new Array(16);
var gameLevel = 0;
var movesThisGame = 0;
var isDebugOn = false;

function valueAt(i, j) { return(i*gameSize + j); }

window.defaultStatus = "Loading Scripts ... please wait";

var isNS4Up, isIE4Up;

if (parseInt(navigator.appVersion.charAt(0)) >= 4)
{
  isNS4Up = (navigator.appName == "Netscape") ? true : false;

  isIE4Up = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
}

// if (isNS4Up) embedSound( SoundLocation + "applause.wav", "applause", "35%")

function movableImage(linkURL, imagFile, border, height, width, row, col)
{
	return(
	"<A " +
	attrQValue("HREF", linkURL) +
	attrQValue("onMouseOver", "javascript: changeNumbr(" + row + ", " + col + "); return true") +
	attrQValue(    "onClick", "javascript: changeImage(" + row + ", " + col + ")") +
	"><IMG " +
	attrQValue(   "SRC", imagFile) +
	attrQValue(  "NAME", "slot" + row + col) +
	attrUValue("BORDER",  0) +
	attrUValue("HEIGHT", 64) +
	attrUValue( "WIDTH", 64 ) +
	"></A>"
	);
}

function changeNumbr(i, j)
{
	if(isAdjacent(i, j))
		window.status= "maybe";
	else if( (i%2) == 0)
		window.status=  "not a good choice";
	else if( (j%2) == 0)
		window.status=  "try another tile";
	else
		window.status=  "nope";
}

function buildGameTable(level)
{
	var gameString;

	gameString = openCenter() +
	openTable() + attrQValue("BORDER WIDTH", "264") + ">" +
	openTableRow() +
	openTableCel();

	for(i = 0; i < gameSize; i++)
	{
		for(j = 0; j < gameSize; j++)
		{
			gameString += movableImage("#"+i+j, gameDirectory + gameFiles[level] + "/" + gameGrid[valueAt(i,j)] + ".gif", 0, 64, 64, i, j);
		}
		gameString += lineBreak();
	}

	gameString += closTableCel() +
	closTableRow() +
	closTable() +
	closCenter();

	flush(gameString);
	tellDebug(gameString);
}

function initGameGrid(folder, grid)
{
	// set up the blank tile!
	blankTile = new Image(64, 64);
	blankTile.src = gameDirectory + folder + "/" + "0b.gif";

	for(i = 0; i < gameSize*gameSize; i++)
	{
		image[i] = new Image(64, 64);
		image[i].src = gameDirectory + folder + "/" + i + ".gif";
	}

	gameGrid = grid;

	for(i = 0; i < gameSize; i++)
	{
		for(j = 0; j < gameSize; j++)
		{
			if(gameGrid[valueAt(i,j)] == 0)
			{
				zeroRow = i;
				zeroCol = j;
			}
		}
	}
}

function refreshGameGrid()
{
	for(i = 0; i < gameSize; i++)
	{
		for(j = 0; j < gameSize; j++)
		{
			tmp = gameGrid[valueAt(i,j)];
			setSlot(i, j, image[tmp].src);
		}
	}
}

function isSolutionCorrect()
{
	for(i = 0; i < gameSize; i++)
	{
		for(j = 0; j < gameSize; j++)
		{
			tile = i*gameSize + j + 1;
			if(tile == 16)
				tile = 0;
			if(gameGrid[valueAt(i,j)] != tile)
				return(false);
		}
	}
	return(true)
}

function setSlot(i, j, image)
{
	     if(i == 0)
	{
		     if( j == 0 ) document.slot00.src = image;
		else if( j == 1 ) document.slot01.src = image;
		else if( j == 2 ) document.slot02.src = image;
		else if( j == 3 ) document.slot03.src = image;
	}
	else if(i == 1)
	{
		     if( j == 0 ) document.slot10.src = image;
		else if( j == 1 ) document.slot11.src = image;

		else if( j == 2 ) document.slot12.src = image;
		else if( j == 3 ) document.slot13.src = image;
	}
	else if(i == 2)
	{
		     if( j == 0 ) document.slot20.src = image;
		else if( j == 1 ) document.slot21.src = image;
		else if( j == 2 ) document.slot22.src = image;
		else if( j == 3 ) document.slot23.src = image;
	}
	else if(i == 3)
	{
		     if( j == 0 ) document.slot30.src = image;
		else if( j == 1 ) document.slot31.src = image;
		else if( j == 2 ) document.slot32.src = image;
		else if( j == 3 ) document.slot33.src = image;
	}
}

function changeImage(currRow, currCol)
{

	if(gameGrid[valueAt(currRow,currCol)] == 0)
		alert("Click a tile BESIDE black tile!");

	if(isAdjacent(currRow, currCol))
	{
		tmp = gameGrid[valueAt(currRow,currCol)];
		gameGrid[valueAt(currRow,currCol)] = 0;
		gameGrid[valueAt(zeroRow,zeroCol)] = tmp;

		tmp2 = gameGrid[valueAt(zeroRow,zeroCol)];
		setSlot(zeroRow, zeroCol, image[tmp2].src);
		setSlot(currRow, currCol, image[ 0  ].src);

		zeroRow = currRow;
		zeroCol = currCol;

		if(isDebugOn)
			debugGameGrid();
	}

	movesThisGame++;

	if(isSolutionCorrect())
	{
		whichGame=gameLevel+1;
		tellDebug("whichGame: " + whichGame);
		tellDialog("You solved " + whichGame + " of " + gameFiles.length + ".  Loading, please wait!");
		setSlot(gameSize-1, gameSize-1, blankTile.src);


		if (isNS4Up)
		{
			applaud();
			setTimeout("setupNextGame()", 3000 ); // after 3 seconds
		}
		else
		{
		   setupNextGame();
		}

		setGameLevel(gameLevel+1); // sets cookie for game level
	}			
	else
	{
		feedDialog(movesThisGame);
	}

	if(isDebugOn)

		debugGameGrid();
}

function setupNextGame()
{
	movesThisGame=0;
	gameLevel = Math.min(gameFiles.length-1,gameLevel+1);
	initGameGrid(gameFiles[gameLevel], gamePtrn[gameLevel]);
	refreshGameGrid();
	if(gameLevel < gameFiles.length - 1)
		feedDialog(movesThisGame);
	else if(gameLevel == gameFiles.length - 1 )
		tellDialog("Email K14 for a prize!");
	else
		feedDialog("Solve for a clue to cancer...");
}

function applaud()
{
	// document.embeds[0].play(false);
}

function isAdjacent(a, b)
{
	return ( (Math.abs(a - zeroRow) + Math.abs(b - zeroCol)) == 1 );
}

function debugGameGrid()
{
	var reportString = "";
	for(i = 0; i < gameSize; i++)
	{
		reportString += "["
		for(j = 0; j < gameSize; j++)
		{
			if(j < gameSize-1)
				reportString += gameGrid[valueAt(i,j)] + ", ";
			else
				reportString += gameGrid[valueAt(i,j)] +   "";
		}
		reportString += "],\n"
	}

	tellDebug(reportString);

	tellDebug("zeroRow: " + zeroRow);
	tellDebug("zeroCol: " + zeroCol);
}

function showDialogForm()
{
	document.write("<CENTER><FORM name=\"dialogForm\">");
	document.write("<input type = \"text\" name=\"dialogText\" size=\"64\">");
	// document.write("<TEXTAREA name=\"dialogText\" rows=\"2\" cols=\"24\"></TEXTAREA>");
	document.write("</FORM></CENTER>");
}

function showDebugForm()
{
	document.write("<CENTER><FORM name=\"debugForm\">");
	document.write("<TEXTAREA name=\"debugTextArea\" rows=\"5\" WIDTH=200></TEXTAREA>");
	document.write("</FORM></CENTER>");
}

function feedDialog(moves)
{
	whichGame = gameLevel + 1;
	document.forms[0].elements[0].value = "Puzzle " + whichGame + ": " + gameFiles[gameLevel] + " System, Moves: " + moves;
}

function tellDialog(statement)
{
		document.forms[0].elements[0].value = statement;
}

function tellDebug(string)
{
	if(isDebugOn)
		document.forms[1].elements[0].value += string + "\n";
}

function runTheGame()
{
	if(isDebugOn)
		showDebugForm();

	window.defaultStatus = "Initializing Game Grid... please wait";

	if(getCookie(cookieName) == null)
		gameLevel = 0;
	else
		gameLevel = Math.min(gameFiles.length-1,getCookie(cookieName));

	initGameGrid(gameFiles[gameLevel], gamePtrn[gameLevel]);

	window.defaultStatus = "Building Game Table... please wait";

	buildGameTable(gameLevel);

	window.defaultStatus = "Building Game Table... please wait";

	window.defaultStatus = "Solve the Puzzle!";

	//showDialogForm();

	tellDebug("zeroRow: " + zeroRow);
	tellDebug("zeroCol: " + zeroCol);

	getGameLevel();
}


function upgradeBrowser()
{
	flush(
		openCenter() +
		normalTextBR("To run the puzzle and win fabulous prizes.") +
		linkedText(-1,"zHTM/openLetter.html", "You must first upgrade.") +
		closCenter()
	);
}

function middleSection()
{
	if (isNS4Up || isIE4Up)
	{
		runTheGame(); 
	}
	else 
	{
	   upgradeBrowser();
	}
}
