// ZEESLAG / BATTLEFIELD v0.2
// tested: IE7, FF2, NS8, Opera9
// rights: © Jerone Productions
// e-mail: jeronevw@hotmail.com

// TODO: 
//	- toetsenbord gebruiken
//	- nummers aan de zijkant
//	- boten als status
//	- teller (cliks/misses/hits/sinks)
//	- cheat funtie (toetsenbord)
//	- window.status
//	- NL & EN
//	- als je klaar bent, hover weghalen
//	- LinkAlert uitschakelen

// BUGS:
//	- tis nog mogelijk om ships te plaatsen terwijl spel is afgelopen.
//	- buttonShipType "vorige type" werkt nog niet van klein naar groot schip.

/**************************************************/
/* variabelen */
// Information used to draw the ships
// [jouwPlaatje,jouwPlaatje,...],[pcPlaatje,pcPlaatje,...]
var ship =  [[[1,5],[1,2,5],[1,2,3,5],[1,2,3,4,5]],[[6,10],[6,7,10],[6,7,8,10],[6,7,8,9,10]]];

// Information used to draw sunk ships
// [jouwPlaatje,jouwPlaatje,...],[pcPlaatje,pcPlaatje,...]
var dead = [[[201,203],[201,202,203],[201,202,202,203],[201,202,202,202,203]],[[204,206],[204,205,206],[204,205,205,206],[204,205,205,205,206]]];

// Information used to describe ships
// ["name",length,many]
var shiptypes = [["Mijnenveger",2,4],["Fregat",3,3],["Kruiser",4,2],["Slagschip",5,1]];

// grootte van het veld (in hokjes)
var gridx = 16, gridy = 16;

// begin plaatje bij muis
// ["image",width,height]
var trailimage = [["batt205.gif",16,16],["batt202.gif",16,16]];
// image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
// [x,y]
var offsetfrommouse = [1,-18];
//duration in seconds image should remain visible. 0 for always.
var displayduration = 0;

// the root for all images
var imageRoot = "images/"
// the root for all sounds
var soundRoot = "overige/"

var maxshiplength = shiptypes[3][1];
var player = [], computer = [], playersships = [], computersships = [];
var playerlives = 0, computerlives = 0, playflag=true, statusmsg="";
var playershiplives=[shiptypes.length], computershiplives=[shiptypes.length];

var editMode = false;
var editshiptype = 0;
var editshipno = 0;
var editshiporient = 0;
var editshipid = new Array();

/**************************************************/
/* functies */
// Function to preload all the images, to prevent delays during play
var preloaded = [];
function imagePreload(){
	var i,ids = [1,2,3,4,5,6,7,8,9,10,100,101,102,103,201,202,203,204,205,206];
	window.status = "Preloading images...please wait";
	for (i=0; i<ids.length; ++i){
		var img = new Image, name = imageRoot+"batt"+ids[i]+".gif";
		img.src = name;
		preloaded[i] = img;
	}
	window.status = "";
}

// Function to place the ships in the grid
function setupPlayer(ispc){
	var y,x;
	grid = [];
	for (y=0; y<gridy; ++y){
		grid[y] = [];
		for (x=0; x<gridx; ++x) grid[y][x] = [100,-1,0];
	}

	var shipno = 0;
	var s;
	for (s=shiptypes.length-1; s>=0; --s){
		var i;
		for (i=0; i<shiptypes[s][2]; ++i){
			var d = Math.floor(Math.random()*2);
			var len = shiptypes[s][1], lx=gridx, ly=gridy, dx=0, dy=0;
			if(d==0){
				lx = gridx-len;
				dx=1;
			}
			else {
				ly = gridy-len;
				dy=1;
			}
			var x,y,ok;
			do {
				y = Math.floor(Math.random()*ly);
				x = Math.floor(Math.random()*lx);
				var j,cx=x,cy=y;
				ok = true;
				for (j=0; j<len; ++j){
					if(grid[cy][cx][0] < 100){
						ok=false;
						break;
					}
					cx+=dx;
					cy+=dy;
				}
			} while(!ok);
			var j,cx=x,cy=y;
			for (j=0; j<len; ++j){
				grid[cy][cx][0] = ship[d][s][j];
				grid[cy][cx][1] = shipno;
				grid[cy][cx][2] = dead[d][s][j];
				cx+=dx;
				cy+=dy;
			}
			if(ispc){
				computersships[shipno] = [s,shiptypes[s][1]];
				computerlives++;
			}
			else {
				playersships[shipno] = [s,shiptypes[s][1]];
				playerlives++;
			}
			shipno++;
 		}
		if(ispc){ 
			computershiplives[s] = shiptypes[s][2]; 
		}
		else {
			playershiplives[s]   = shiptypes[s][2]; 
		}
	}
	return grid;
}

// Function to change an image shown on a grid
function setImage(y,x,id,ispc){
	if(ispc){
		computer[y][x][0] = id;
		document.images["pc"+y+"_"+x].src = imageRoot+"batt"+id+".gif";
	}
	else {
		player[y][x][0] = id;
		document.images["ply"+y+"_"+x].src = imageRoot+"batt"+id+".gif";
	}
}

// Handler for clicking on the grid
function gridClick(y,x){
	if(playflag && !editMode){
		disableEditMode();
		if(computer[y][x][0] < 100){
			shipHit(y,x,true);
			var shipno = computer[y][x][1];
			if(--computersships[shipno][1] == 0){
				sinkShip(computer,shipno,true);
				updateStatus(true);
				alertStatus("Computer "+shiptypes[computersships[shipno][0]][0]+" is gezonken!");
				if(--computerlives == 0){
					Gamescores.add(0);
					alertStatus("U heeft gewonnen! Klik op Start Opnieuw\n"+
					"om nogmaals te spelen.");
					playflag = false;
				}
			}
			if(playflag){
				computerMove();
			}
		}
		else if(computer[y][x][0] == 100){
			setImage(y,x,102,true);
			computerMove();
		}
	}
}

// Function to make the computers move. Note that the computer does not cheat, oh no!
function computerMove(){
	var x,y,pass;
	var sx,sy;
	var selected = false;
	/* Make two passes during 'shoot to kill' mode */
	for (pass=0;pass<2;++pass){
		for (y=0;y<gridy && !selected;++y){
			for (x=0;x<gridx && !selected;++x){ /* Explosion shown at this position */
				if(player[y][x][0]==103){
					sx=x; sy=y;
					var nup=(y>0 && player[y-1][x][0]<=100);
					var ndn=(y<gridy-1 && player[y+1][x][0]<=100);
					var nlt=(x>0 && player[y][x-1][0]<=100);
					var nrt=(x<gridx-1 && player[y][x+1][0]<=100);
					if(pass == 0){ /* On first pass look for two explosions in a row - next shot will be inline */
						var yup=(y>0 && player[y-1][x][0]==103);
						var ydn=(y<gridy-1 && player[y+1][x][0]==103);
						var ylt=(x>0 && player[y][x-1][0]==103);
						var yrt=(x<gridx-1 && player[y][x+1][0]==103);
						if(nlt && yrt){ sx = x-1; selected=true; }
						else if(nrt && ylt){ sx = x+1; selected=true; }
						else if(nup && ydn){ sy = y-1; selected=true; }
						else if(ndn && yup){ sy = y+1; selected=true; }
					}
					else { /* Second pass look for single explosion fire shots all around it */
						if(nlt){ sx=x-1; selected=true; }
						else if(nrt){ sx=x+1; selected=true; }
						else if(nup){ sy=y-1; selected=true; }
						else if(ndn){ sy=y+1; selected=true; }
					}
				}
			}
		}
	}
	if(!selected){	/* Nothing found in 'shoot to kill' mode, so we're just taking
						   potshots. Random shots are in a chequerboard pattern for 
						   maximum efficiency, and never twice in the same place */
		do{
			sy = Math.floor(Math.random() * gridy);
			sx = Math.floor(Math.random() * gridx/2)*2+sy%2;
		} while( player[sy][sx][0]>100 );
	}
	if(player[sy][sx][0] < 100){ /* Hit something */
		shipHit(sy,sx,false)
		var shipno = player[sy][sx][1];
		if(--playersships[shipno][1] == 0){
			sinkShip(player,shipno,false);
			updateStatus(false);
			alertStatus("Uw "+shiptypes[playersships[shipno][0]][0]+" is gezonken!");
			if(--playerlives == 0){
				knowYourEnemy();
				Gamescores.add(1);
				alertStatus("Computer wint! Klik op Start Opnieuw\n"+
				"om nogmaals te spelen.");
				playflag = false;
			}
		}
	}
	else { /* Missed */
		setImage(sy,sx,102,false);
	}
}

// als een schip is geraakt op een enkele plek
function shipHit(y, x, ispc){
	setImage(y,x,103,ispc);
	playSound(soundRoot+'Explosion-'+(ispc?'1':'2')+'.au');
}

// When whole ship is hit, show it using changed graphics
function sinkShip(grid,shipno,ispc){
	var y,x;
	for (y=0; y<gridx; ++y){
		for (x=0; x<gridx; ++x){
			if(grid[y][x][1] == shipno ){
				if(ispc){
					setImage(y,x,computer[y][x][2],true);
				}
				else {
					setImage(y,x,player[y][x][2],false);
				}
			}
		}
	}
	if(ispc){ 
		computershiplives[computersships[shipno][0]]--;
	}
	else { 
		playershiplives[playersships[shipno][0]]--;
	}
	playSound(soundRoot+'flush.au');
}

// Show location of all the computers ships - when player has lost
function knowYourEnemy(){
	var y,x;
	for (y=0;y<gridx;++y){
		for (x=0;x<gridx;++x){
			if(computer[y][x][0] == 103){
				setImage(y,x,computer[y][x][2],true);
			}
			else if(computer[y][x][0] < 100){
				setImage(y,x,computer[y][x][0],true);
			}
		}
	}
}

// Show how many ships computer has left
function updateStatus(ispc){
	var f=false,i,s = "Computer heeft ";
	for (i=0; i<computersships.length; ++i){
		if(computersships[i][1] > 0){
			if(f){
				s=s+", ";
			}
			else {
				f=true;
			}
			s = s + shiptypes[computersships[i][0]][0];
		}
	}
	if(!f){
		s = s + "niets meer, dankzij u!";
	}
	statusmsg = s;
	window.status = statusmsg;
	tmp = (ispc ? "Computer" : "Player")+"Ship";
	for (i = 0; i < ship.length; i++){
		for (j = 0; j < ship[1].length; j++){
			window.document.forms["statusForm"][tmp+j+(i==0?"live":"hit")].value = i*shiptypes[j][2] + (i==0?1:-1)*(ispc?computershiplives[j]:playershiplives[j]);
		}
	}
}

// update scrores en status
function updateScores(){
	updateStatus(false);
	updateStatus(true);
	Gamescores.show();
}

// draaid schip of wijzigd type (gebruikt bij scorebord)
function shipClick(s){
	if(editMode){
		if(editshiptype == s){
			buttonNextOrientation();
		}
		else {
			hidetrail();
			editshiptype = s;
			showtrail();
		}
	}
}

// ?
function getNewShipId(){
	return editshipid.pop();
}

// ?
function storeShipId(id){
	editshipid.push(id);
}


function onOffGrid(y, x, on){
	if(editMode){
		var shiplen = shiptypes[editshiptype][1];
		if(on){
			hidetrail();
			shipOffBoard = (editshiporient == 0? x : y) < shiplen-1;
			for (i = 0; i < shiplen; i++){
				xp = x-(1-editshiporient)*i;
				yp = y-(  editshiporient)*i;
				//A ship on the current position (y,x) or it does not fit on the board --> display as dead.
				if(shipOffBoard){
					s = dead[editshiporient][editshiptype][shiplen-1-i];
				}
				else if(player[yp][xp][0] < 100){
					s = dead[editshiporient][editshiptype][shiplen-1-i];
				}
				else {
					s = ship[editshiporient][editshiptype][shiplen-1-i];
				}
				if((xp >= 0) && (yp >= 0)){
					document.images["ply"+yp+"_"+xp].src = imageRoot+"batt"+s+".gif";
				}
			}
		}
		else {
			for (i = 0; i < shiplen; i++){
				xp = x-(1-editshiporient)*i;
				yp = y-(  editshiporient)*i;
				if((xp >= 0) && (yp >= 0)){
					document.images["ply"+yp+"_"+xp].src = imageRoot+"batt"+player[yp][xp][0]+".gif";
				}
			}
		}
	}
}

function eraseShip(shipno){
	var y,x;
	for (y=0; y<gridx; ++y){
		for (x=0; x<gridx; ++x){
			if( player[y][x][1] == shipno ){
				player[y][x] = [100,-1,0];
				document.images["ply"+y+"_"+x].src = imageRoot+"batt100.gif";
			}
		}
	}
	playershiplives[playersships[shipno][0]]--;
	playersships[shipno] = [];
}

function isFree(y,x,type){
	var shiplen = shiptypes[type][1];
	shipOffBoard = ((editshiporient == 0? x : y) < shiplen-1);
	if(shipOffBoard){
		return (false);
	}
	free = true;
	for (i = 0; i < shiplen; i++){
		xp = x-(1-editshiporient)*i;
		yp = y-(  editshiporient)*i;
		free = free && (player[yp][xp][0] == 100);
	}
	return (free);
}

function setupClick(y,x){
	if(editMode){
		if(isFree(y,x,editshiptype)){
			var shiplen = shiptypes[editshiptype][1];
			if(playershiplives[editshiptype] < shiptypes[editshiptype][2]){
				var shipid = getNewShipId();
				for (i = 0; i < shiplen; i++){
					xp = x-(1-editshiporient)*i;
					yp = y-(  editshiporient)*i;
					player[yp][xp][0] = ship[editshiporient][editshiptype][shiplen-1-i];
					player[yp][xp][1] = shipid;
					player[yp][xp][2] = dead[editshiporient][editshiptype][shiplen-1-i];
					document.images["ply"+yp+"_"+xp].src = imageRoot+"batt"+player[yp][xp][0]+".gif";
				}
				playersships[shipid] = [editshiptype,shiplen];
				playershiplives[editshiptype]++;
				editshipno++;
				updateStatus(false);
			}
			else {
				alertStatus('U mag niet meer dan '+shiptypes[editshiptype][2]+' '+shiptypes[editshiptype][0]+(shiptypes[editshiptype][2]==1?'':((editshiptype%2)==1 ? 'en':'s'))+' plaatsen.');
			}
		}
		else {
			var shiplen = shiptypes[editshiptype][1];
			shipOffBoard = ((editshiporient == 0? x : y) < shiplen-1);
			if(shipOffBoard){
				alertStatus('Schip past niet op het bord.');
			}
			else {
				if(confirm('Bezet! Hier ligt al een ander schip.\nKlik op OK om deze te verwijderen.')){
					//delete ships
					//where are ships colliding and of which type are they?
					for (i = 0; i < shiplen; i++){
						xp = x-(1-editshiporient)*i;
						yp = y-(  editshiporient)*i;
						if(player[yp][xp][0] != 100){
							//for each colliding ship: locate position, erase from board and return shipid to the list of free ship id's 
							shipid = player[yp][xp][1];
							eraseShip(shipid);
							storeShipId(shipid);
							updateStatus(false);
}	}	}	}	}	}	}

function playSound(sample){
	if(window.document.forms["gameControlsForm"].sound.checked){
		document.getElementById('noise').innerHTML='<embed src="../../artikels/art004/'+sample+'" hidden>';
	}
}

/**************************************************/
/* EDIT MODE */
// veranderd muziek plaatje
function setSoundImg(){
	if(window.document.forms["gameControlsForm"].sound.checked){
		document.getElementById('soundImg').src = 'sound.png'
	}
	else {
		document.getElementById('soundImg').src = 'sound_mute.png'
	}
}

// opend de editmode
function buttonEditMode(){
	if(editMode){
		if(boardIsValid()){
			editMode = false;
			hidetrail();
	//		window.document.forms["gameControlsForm"].EditMode.value = "Wijzig bord";
	//		window.document.forms["gameControlsForm"].EraseBoard.style.visibility = "hidden";
	//		window.document.forms["gameControlsForm"].NextShipType.style.visibility = "hidden";
	//		window.document.forms["gameControlsForm"].NextOrientation.style.visibility = "hidden";
			document.getElementById('editForm').style.visibility = "hidden";
			document.getElementById('EditModeA').innerText = "Einde wijzigingen";
			document.getElementById('EditModeImg').src = "cog_edit.png";
		}
		else {
			if(confirm('Ongeldige opstelling!\nKlik op OK om de computer een nieuwe opstelling te laten maken.')){
			// TODO: als ik 1 of meer schepen mis, geeft hij ook deze error.
				history.go(0);
			}
			else {
				alertStatus('Plaats de ontbrekende schepen op het bord.');
			}
		}
	}
	else {
		editMode = true;
		showtrail();
	//	window.document.forms["gameControlsForm"].EditMode.value = "Einde wijzigingen";
	//	window.document.forms["gameControlsForm"].EraseBoard.style.visibility = "visible";
	//	window.document.forms["gameControlsForm"].NextShipType.style.visibility = "visible";
	//	window.document.forms["gameControlsForm"].NextOrientation.style.visibility = "visible";
		document.getElementById('editForm').style.visibility = "visible";
		document.getElementById('EditModeA').innerText = "Einde wijzigingen";
		document.getElementById('EditModeImg').src = "cog_go.png";
		//The board is a contains a valid setup of ships. Therefore all ships are placed on the board. Hence, there are no unplaced ships.
		editshipid = new Array();
	}
}
function boardIsValid(){  // behoord bij buttonEditMode function
	var valid = true;
	for (i = 0; i < shiptypes.length; i++){
		valid = valid && (playershiplives[i] == shiptypes[i][2]);
	}
	return (valid);
}

// sluit de editmode
function disableEditMode(){
	window.document.forms["gameControlsForm"].EditMode.style.visibility = "hidden";
}

// verwijderd bord
function buttonEraseBoard(){
	for (y=0; y<gridy; ++y){
		for (x=0; x<gridx; ++x)	{
			player[y][x] = [100,-1,0];
			setImage(y,x,player[y][x][0],false);
		}
	}
	for (i = 0; i < shiptypes.length; i++){
		playershiplives[i] = 0;
	}
	playersships = [];
	id = 0;
	for (i = 0; i < shiptypes.length; i++){
		for (j = 0; j < shiptypes[i][2]; j++){
			storeShipId(id++);
		}
	}
	editshipno = 0;
	updateStatus(false);
}

// boot type wisselen
// "next" is volgende, "prev" is vorige.
function buttonShipType(direction){
	if(editMode){
		hidetrail();
		if(direction == "next"){
			console.log(editshiptype);
			editshiptype = (editshiptype+1)%ship[1].length;
			console.log(editshiptype);
			console.log(ship[1].length);
		}
		else if(direction == "prev"){
			console.log(editshiptype);
			editshiptype = ship[1].length%(editshiptype-1);
			console.log(editshiptype);
			console.log(ship[1].length);
//			console.log((editshiptype-1)%ship[1].length);
		}
		else {
			editshiptype = (editshiptype+1)%ship[1].length;
		}
		showtrail();
	}
}

// draaid boot
function buttonNextOrientation(){
	if(editMode){
		hidetrail();
		editshiporient = (editshiporient+1)%2;
		showtrail();
	}
}

/**************************************************/
/* MOUSE */
function gettrailobj(){
	if(document.getElementById){
		return document.getElementById("trailimageid"+editshiptype+'_'+editshiporient).style
	}
	else if(document.all){
		return document.all.trailimagid.style
	}
}

function hidetrail(){
	gettrailobj().visibility="hidden"
	document.onmousemove=""
}

function showtrail(){
	gettrailobj().visibility="visible"
	document.onmousemove=followmouse
}

function followmouse(e){
	if(editMode){
		var xcoord = offsetfrommouse[  editshiporient] - (1-editshiporient)*(16*ship[editshiporient][editshiptype].length+2);
		var ycoord = offsetfrommouse[1-editshiporient] - (  editshiporient)*(16*ship[editshiporient][editshiptype].length+2);
		if(typeof e != "undefined"){
			xcoord += e.pageX
			ycoord += e.pageY
		}
		else if(typeof window.event !="undefined"){
			xcoord += truebody().scrollLeft+event.clientX
			ycoord += truebody().scrollTop+event.clientY
		}
		var docwidth  = document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
		var docheight = document.all? Math.max(truebody().scrollHeight, truebody().clientHeight) : Math.max(document.body.offsetHeight, window.innerHeight)
		if(xcoord+trailimage[1]+3>docwidth || ycoord+trailimage[2]> docheight){
			gettrailobj().display="none"
		}
		else {
			gettrailobj().display=""
		}
		gettrailobj().left=xcoord+"px"
		gettrailobj().top=ycoord+"px"
	}
}

function truebody(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

if(displayduration>0){
	setTimeout("hidetrail()", displayduration*1000)
}

/**************************************************/
/* RENDER */
// Render de scorebord
ScoreTable = new function(){
	this.create = function(){
		colheight = maxshiplength;
		document.writeln('<form action="../../artikels/art004/zeeslag-spel.html" method="get" onsubmit="return false;">');
		document.writeln('<p align="center"><table border="0" cellpadding="0" cellspacing="0"><tr>');
		for (k = 0; k < 2; k++){
			for (j = 0; j < ship[1].length; j++){
				document.writeln('<td><div style="width:16px;height:80px;">');
				thisheight  = ship[1][j].length;
				thispadding = colheight-thisheight;
				for (i = 0; i < colheight; i++){
					document.write('<img src="../../artikels/art004/' + imageRoot + 'batt'+(i<thispadding?"100":eval((k==0?"ship":"dead")+"[1][j][i-thispadding]"))+'.gif" width="16px" height="16px" onclick=shipClick('+j+')>'); 
				}
				document.writeln('</div></td>');
			}
		}
		document.writeln('</tr>');
		for (i = 0; i < 2; i++){
			document.writeln('<tr>');
			for (j = 0; j < 2; j++){
				for (s = 0; s < ship[1].length; s++){
					document.write('<td><input type="text" name="'+(i==0?'Computer':'Player')+'Ship'+s+(j==0?'live':'hit')+'" value="0" size="1" readonly class="'+(j==0?'live':'hit')+'counter"></td>');
				}
			}
			document.writeln('<td align="left">'+(i==0?'computer':'Jij')+'</td>');
			document.writeln('</tr>');
		}
		document.writeln('</table><p></p></form>');
	}
}

// Renderd the grid
function renderGrid(ispc){
	var y,x;
	for (y=0; y<gridy; ++y){
		for (x=0; x<gridx; ++x){
			if(ispc){
				document.write ('<a href="javascript:gridClick('+y+','+x+');" class="grid"> <img name="pc'+y+'_'+x+'" src="../../artikels/art004/' + imageRoot + 'batt100.gif" width=16 height=16></a>');
			}
			else {
				document.write ('<a href="javascript:setupClick('+y+','+x+');" onmouseover=onOffGrid('+y+','+x+',1) onmouseout=onOffGrid('+y+','+x+',0) class="grid"> <img name="ply'+y+'_'+x+'" src="../../artikels/art004/' + imageRoot + 'batt'+player[y][x][0]+'.gif" width=16 height=16></a>');
			}
		}
		document.write('<br>');
	}
}

// Renderd verborgen plaatjes voor het handmatig plaatsen van de boten.
function renderImages(){
	if(document.getElementById || document.all){
		for (k = 0; k < 2; k++){
			for (j = 0; j < ship[k].length; j++){
				document.writeln('<div id="trailimageid'+j+'_'+k+'" style="position:absolute;'+(k==1?'width:1px;height:1px;':'')+'visibility:hidden">');
				//document.writeln('<div id="trailimageid'+j+'_'+k+'" style="'+(k==1?'width:1px;height:1px;':'')+'visibility:hidden">');
				for (i = 0; i < ship[k][j].length; i++){
					document.write('<img src="../../artikels/art004/' + imageRoot + 'batt'+ship[k][j][i]+'.gif" width="16px" height="16px">'); 
				}
				document.writeln('</div>');
			}
		}
	}
}

/**************************************************/
/* Cookie */
var expDate = new function(){
	this.init = function(){
		var  expYears = 5;
		this.expdate  = new Date();
		this.expdate.setTime(this.expdate.getTime() + (expYears*365*24*60*60*1000));
	}
	this.get = function(){
		return(this.expdate);
	}
}

function getCookieVal (offset){
	var endstr = document.cookie.indexOf (";", offset);
	if(endstr == -1){
		endstr = document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen){
		var j = i + alen;
		if(document.cookie.substring(i, j) == arg){
			return getCookieVal (j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0){
			break;
		}
	}
	return null;
}

function SetCookie (name, value){
	var argv = SetCookie.arguments;  
	var argc = SetCookie.arguments.length;  
	var expires = (argc > 2) ? argv[2] : null;  
	var path = (argc > 3) ? argv[3] : null;  
	var domain = (argc > 4) ? argv[4] : null;  
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape(value) +
 ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
 ((path == null) ? "" : ("; path=" + path)) +
 ((domain == null) ? "" : ("; domain=" + domain)) +
 ((secure == true) ? "; secure" : "");
}

function DeleteCookie (name){
	var exp = new Date();  
	exp.setTime (exp.getTime() - 1);  
	var cval = GetCookie (name);  
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

var Gamescores = new function()
{
	this.gamescore = new Array();
	this.init = function() 	{
		if(GetCookie('gamescore') == null){
			this.set();
			this.save();
		}
		else {
			this.get()
			//this.show();
		}
	}
	this.save = function(){
		var cookiestr = "";
		expDate.init();
		for(var i = 0; i < 2; i++) cookiestr += this.gamescore[i]+";";
		SetCookie('gamescore', cookiestr, expDate.get());
	}
	this.set = function(){
		for(var i = 0; i < 2; i++) this.gamescore[i] = 0;
	}
	this.get = function(){
		var cookiestr = GetCookie('gamescore');
		var n = 0;
		var m = cookiestr.indexOf(";", n);  
		var clen = cookiestr.length;
		var i = 0;
		while (n < clen){
			this.gamescore[i] = parseInt(cookiestr.substring(n, m));
			i++;
			if(i >= 2) break;
			n = m+1;
			m = cookiestr.indexOf(";", m+1);
			if(m == 0) break;
		}
	}
	this.add = function(ispc){
		if(ispc)	this.gamescore[1]++;
		else		this.gamescore[0]++;
		this.save();
		this.show();
	}
	this.show = function(){
		window.document.forms["scoreForm"].player.value = this.gamescore[0];
		window.document.forms["scoreForm"].computer.value = this.gamescore[1];
	}
}









/**************************************************/
/* Jerone */
// laat text zien in de statusbalk
function setStatus(){
	window.status = statusmsg;
}

// alert
// type 0 = mededeling, 1 = error
function alertStatus(msg){
	
//	if(type = 0)
	document.getElementById('alertStatus').innerHTML = msg;
}


