var GAMENAME = "BattleFleet";
var POSTSCRIPT = "iPhone";
var VERSION = "Beta.201";

var CREATOR = "Roger Kenny";
var LICENSE = "Licensed by Ripped Productions";
var COPYRIGHT = "Copyright &copy; 2007 Roger Kenny, Ripped Productions. All rights reserved";

var GAMETIP = "NEW FEATURE: Switch sides in the Options panel.";

var FOOTERINFO = "<p>Contact/Bugs/Ads: <a href='mailto:battlefleet@rogerkenny.com' style='color:#0088ff;' >battlefleet@rogerkenny.com</a></p>"+GAMENAME+" for "+POSTSCRIPT+" "+VERSION+" "+COPYRIGHT;
//Options
var autoshipplace = (readCookie("autoshipplace")!=null) ? ((readCookie("autoshipplace")=="false") ? false : true) : true;
var speed = (readCookie("gamespeed")!=null) ? parseInt(readCookie("gamespeed")) : 1 ;
var levelsetting = (readCookie("levelsetting")!=null) ? readCookie("levelsetting") : 2 ; //game difficulty 1 || 2 || 3
var playerteam = (readCookie("playerteam")!=null) ? readCookie("playerteam") : 2 ; //player team 1 = Red || 2 = Blue

//SecretOptions
var showenemyships = (readCookie("showenemyships")!=null) ? ((readCookie("showenemyships")=="false") ? false : true) : false;
var infiniteshot = (readCookie("infiniteshot")!=null) ? ((readCookie("infiniteshot")=="false") ? false : true) : false;

//Stats
var gamesplayed = (readCookie("gamesplayed")!=null) ? parseInt(readCookie("gamesplayed")) : 0 ;
var gameswon = (readCookie("gameswon")!=null) ? parseInt(readCookie("gameswon")) : 0 ;
var gameslost = (readCookie("gameslost")!=null) ? parseInt(readCookie("gameslost")) : 0 ;
var gamestied = (readCookie("gamestied")!=null) ? parseInt(readCookie("gamestied")) : 0 ;
var totalscore = (readCookie("totalscore")!=null) ? parseInt(readCookie("totalscore")) : 0 ;
var highscore = (readCookie("highscore")!=null) ? parseInt(readCookie("highscore")) : 0 ;


var playerscore = 0; //player score per game
var enemyscore = 0;//enemy score per game
var playershotsleft = (levelsetting>2) ? 22 : 44;
var enemyshotsleft = (levelsetting>2) ? 22 : 44;
var playershoticons = [];
var enemyshoticons = [];
var shipsinitialized = false; //switch on after first setup

var gamelevel = 1; //In multilevel play

function setAutoOption ( form ) {
	autoshipplace = form.autoshipplace.checked;
	createCookie("autoshipplace",autoshipplace,300);
}

function setGameSpeed ( form ) {
	for (var count=0; count<form.gamespeed.length; count++) {
		if (form.gamespeed[count].checked==true) {
			speed = parseInt(form.difficulty[count].value);
			createCookie("gamespeed", speed,300);
			slidesteps = 8/speed;
			boardslidespeed = 50/speed;
		} 
	}
}

function setGameLevel ( form ) {
	for (var count=0; count<form.difficulty.length; count++) {
		if (form.difficulty[count].checked==true) {
			levelsetting = form.difficulty[count].value;
			//updateLevelDisplay();
			createCookie("levelsetting",levelsetting,300);
			playershotsleft = (levelsetting>2) ? 22 : 44;
			enemyshotsleft = (levelsetting>2) ? 22 : 44;
			initializePlayerShotIcons();
			initializeEnemyShotIcons();
		} 
	}
}

function setGameTeam( form ) {
	for (var count=0; count<form.team.length; count++) {
		if (form.team[count].checked==true) {
			playerteam = parseInt(form.team[count].value);
			createCookie("playerteam", playerteam, 300);
			
			setTeam( playerteam );
		} 
	}
}

function setTeam( team ) {
	setBoardTeam( team );
	setDisplayTeam( team );
	
}

function setBoardTeam( team ) {
	var gameboard = document.getElementById('gameboard');
	if (team == 1) {
		gameboard.style.backgroundImage = 'url(images/seab.jpg)';
	} else {
		gameboard.style.backgroundImage = 'url(images/sea.jpg)';
	}
}

function setDisplayTeam( team ){
var playerpicprefix = (team == 1) ? "e" : "p";
var enemypicprefix = (team == 1) ? "p" : "e";

	document.getElementById("paicon").style.backgroundImage = 'url("images/letters/'+playerpicprefix+'a.gif")';
	document.getElementById("pbicon").style.backgroundImage = 'url("images/letters/'+playerpicprefix+'b.gif")';
	document.getElementById("pdicon").style.backgroundImage = 'url("images/letters/'+playerpicprefix+'d.gif")';
	document.getElementById("psicon").style.backgroundImage = 'url("images/letters/'+playerpicprefix+'s.gif")';
	document.getElementById("ppticon").style.backgroundImage = 'url("images/letters/'+playerpicprefix+'pt.gif")';

	document.getElementById("eaicon").style.backgroundImage = 'url("images/letters/'+enemypicprefix+'a.gif")';
	document.getElementById("ebicon").style.backgroundImage = 'url("images/letters/'+enemypicprefix+'b.gif")';
	document.getElementById("edicon").style.backgroundImage = 'url("images/letters/'+enemypicprefix+'d.gif")';
	document.getElementById("esicon").style.backgroundImage = 'url("images/letters/'+enemypicprefix+'s.gif")';
	document.getElementById("epticon").style.backgroundImage = 'url("images/letters/'+enemypicprefix+'pt.gif")';
}

function updateLevelDisplay() {
	var leveldisplay = document.getElementById("level");
	var whichlevel = (levelsetting == 1) ? "Easy" : (levelsetting == 2) ? "Normal" : "Hard";
	leveldisplay.innerHTML = ''+whichlevel;
}

var enemyboard = [];
var playerboard = [];
var whosturn = "player";
var gamestate = "none"; //start || placingships || autoplacingships || gameon || over
var ships = [];
var enemyships = [];
var shipbeingplaced = "none";
var autoplacedalready = false;

function imClicked () {
	var whogotclicked = this.getAttribute("id");
	switch (gamestate) {
		case "placingships":
			processPlaceShipClick(whogotclicked);
			break;
		case "gameon":
			processGameOnClick(whogotclicked);
			break;
		default:

	}

}


var waittoload;
var load_MSG = "Loading";
//Dialog Box Vars
var loadbox;
var startbox;
var optionsbox;
var doneplacingdialog;
var placingenemyshipsdialog;
var endscreen;

function Initialize() {
	//alert("gothere");
	setMessage("Loading...");
	fillFooterInfo();
	registerDialogs();
	showLoading();
	processExtras();
	loadGameInfoBar();
	drawBoard("shotboard");
	drawBoard("playerboard");
	preloadImages();
	setTeam( playerteam );
	
}

function fillFooterInfo() {
	var footerinfodiv = document.getElementById('footerinfo');
	footerinfodiv.innerHTML = FOOTERINFO;
}

function registerDialogs() {
	loadbox = document.getElementById("loadscreen");
	doneplacingdialog = document.getElementById("doneplacing");
	placingenemyshipsdialog = document.getElementById("placingenemyships");
	optionsbox = document.getElementById("optionspane");
	endscreen = document.getElementById("endscreen");
}

function gameLoaded () { 
	initializeShips();
	initializeEnemyShips();
	initializePlayerShotIcons();
	initializeEnemyShotIcons();
	updateScoreDisplay();
	//updateLevelDisplay();
	slideBoard( "title" );
	waitForSlide( startScreen );
}


function showLoading(){
	loadbox = document.getElementById("loadscreen");
	var loadindicator = document.getElementById("loadindicator");
	if (preloadFlag != true) {
		loadindicator.innerHTML += "."; 
		waittoload = setTimeout( showLoading, 250);
	} else {
		loadbox.setAttribute("class", "hidden");
		clearTimeout(waittoload);
		gameLoaded();
	}
}

var gameinfobar;
function loadGameInfoBar() {
	gameinfobar = document.getElementById('infoarea');
	gameinfobar.onclick = captureInfoClick;
	
}

var infoclicks = 0;
function captureInfoClick () {
	if (infoclicks < 4) {
		infoclicks++;
	} else {
		gameinfobar.onclick = displayInfoMenu;
		infoclicks = 0;
	}
}

function displayInfoMenu() {
	gameinfobar.onclick = captureInfoClick;
	var infomenu = document.createElement('div');
	infomenu.setAttribute('class', 'dialog');
	infomenu.setAttribute('id', 'infomenu');
	var headtext = document.createTextNode("Welcome to the Cheat Menu. Tap the infobar five times to get here again.");
	infomenu.appendChild(headtext);
	
	var showshipcheck = document.createElement('input');
	showshipcheck.setAttribute('type', 'checkbox');
	if (showenemyships == true) {
		showshipcheck.setAttribute('checked', true);
	}
	showshipcheck.setAttribute('id', 'showshipcheck');
	showshipcheck.setAttribute('name', 'showshipcheck');
	showshipcheck.onclick = setShowEnemyShips;
	var showshiplabel = document.createTextNode('Show Enemy Ships');
	var showshipdiv = document.createElement('div');
	showshipdiv.appendChild(showshiplabel);
	showshipdiv.appendChild(showshipcheck);
	infomenu.appendChild(showshipdiv);


	var closeinfobutton = document.createElement('div');
	closeinfobutton.setAttribute('class', 'dialogbutton');
	closeinfobutton.setAttribute('id', 'infomenuclose' );
	var closetext = document.createTextNode("Done");
	closeinfobutton.appendChild(closetext);
	closeinfobutton.onclick = hideInfoMenu;
	
	infomenu.appendChild(closeinfobutton);

	var gameextras = document.getElementById('infomholder');
	gameextras.appendChild(infomenu);
	
}

function setShowEnemyShips() {
	var showshipcheck = document.getElementById('showshipcheck');
	showenemyships = showshipcheck.checked;
	createCookie("showenemyships",showenemyships,3);
	processExtras();
}

function processExtras() {

	if (showenemyships==true) {
		showEShips();
	} else {
		hideEShips();
	}
}

function showEShips() {
	var enemyshiplayer = document.getElementById('enemyshiplayer');
		enemyshiplayer.style.display = "block";
}

function hideEShips() {
	var enemyshiplayer = document.getElementById('enemyshiplayer');
		enemyshiplayer.style.display = "none";

}

function hideInfoMenu() {
	var gameextras = document.getElementById('infomholder');
	gameextras.innerHTML = '';
}

function initializeShips() {
		ships[0] = new ship("Aircraft Carrier", "aircraft", 5, false, "paicon", "youradamage");
		ships[1] = new ship("Battleship", "battleship", 4, false, "pbicon", "yourbdamage");
		ships[2] = new ship("Destroyer", "destroyer", 3, false, "pdicon", "yourddamage");
		ships[3] = new ship("Submarine", "submarine", 3, false, "psicon", "yoursdamage");
		ships[4] = new ship("PT Boat", "ptboat", 2, false, "ppticon" , "yourpdamage");
	for (var s=0; s<ships.length; s++) {
		ships[s].initialize();
	}
}

function initializeEnemyShips() {
		enemyships[0] = new ship("Aircraft Carrier", "aircraft", 5, true, "eaicon", "theiradamage" );
		enemyships[1] = new ship("Battleship", "battleship", 4, true, "ebicon", "theirbdamage" );
		enemyships[2] = new ship("Destroyer", "destroyer", 3, true, "edicon", "theirddamage" );
		enemyships[3] = new ship("Submarine", "submarine", 3, true, "esicon", "theirsdamage" );
		enemyships[4] = new ship("PT Boat", "ptboat", 2, true, "epticon", "theirpdamage" );

	for (var s=0; s<enemyships.length; s++) {
		enemyships[s].initialize();
	}
	shipsinitialized = true;
}

function initializePlayerShotIcons() {
	var playershots = document.getElementById('playershots');
	var playershoticonholder = document.createElement('div');
	playershoticonholder.setAttribute("class", "playershotholder");
	var psi=0;
	if (playershoticons.length != 0) {
		for (var row=0; row < 4; row++) {
			for (var col=0; col < 11; col++) {
				var iconclass = (psi < playershotsleft) ? "shoticon" : "hidden";
				playershoticons[psi].setAttribute("class", iconclass );
				psi++;
			}
		}	
	} else {
		for (var row=0; row < 4; row++) {
			for (var col=0; col < 11; col++) {
				playershoticons[psi] = document.createElement('div');
				var iconclass = (psi < playershotsleft) ? "shoticon" : "hidden";
				playershoticons[psi].setAttribute("class", iconclass );
				playershoticons[psi].style.top = (row*8)+"px";
				playershoticons[psi].style.left = (col*5)+"px";
				
				playershoticonholder.appendChild(playershoticons[psi]);
				psi++;
			}
		}
		playershots.appendChild(playershoticonholder);
	}
}

function initializeEnemyShotIcons() {
	var enemyshots = document.getElementById('enemyshots');
	var enemyshoticonholder = document.createElement('div');
	enemyshoticonholder.setAttribute("class", "enemyshotholder");
	var esi=0;
	if (enemyshoticons.length > 0) {
		for (var row=0; row < 4; row++) {
			for (var col=0; col < 11; col++) {
				var iconclass = (esi < enemyshotsleft) ? "shoticon" : "hidden";
				enemyshoticons[esi].setAttribute("class", iconclass);
				esi++;
			}
		}
	} else {
		for (var row=0; row < 4; row++) {
			for (var col=0; col < 11; col++) {
				var iconclass = (esi < enemyshotsleft) ? "shoticon" : "hidden";
				enemyshoticons[esi] = document.createElement('div');
				enemyshoticons[esi].setAttribute("class", iconclass);
				enemyshoticons[esi].style.top = (row*8)+"px";
				enemyshoticons[esi].style.right = (col*5)+"px";
				enemyshoticonholder.appendChild(enemyshoticons[esi]);
				esi++;
			}
		}
		enemyshots.appendChild(enemyshoticonholder);
	}
}

function startScreen() {
//gotToast();
	setMessage("Press Start");
	loadbox.setAttribute("class", "hidden");
	gamestate = "start";
	setTimeout(function(){window.scrollTo(0, 1);}, 10);
	fadeDiv('startscreen', "in",  15);
	startbutton = document.getElementById('startbutton');
	startbutton.onclick = startNewGame;
	optionsbutton = document.getElementById('optionsbutton');
	optionsbutton.onclick = showOptionsPanel;
	instructionsbutton = document.getElementById('instructionsbutton');
	instructionsbutton.onclick = showInstructionsStart;
	//startbox.setAttribute("class", "dialog");
	
}

function setUpOptions () {
	var options = document.getElementById('optionspaneform');
	options.autoshipplace.checked = autoshipplace;
	options.gamespeed[speed-1].checked = true;
	options.difficulty[levelsetting-1].checked = true; 
	options.team[playerteam-1].checked = true; 
}

function showOptionsPanel () {
	setUpOptions();
	fadeDiv('startscreen', "out",  15, 0.95);
	waitForFade( function(){ fadeDiv('optionspane', 'in', 15, 0.95); } );
	var donebutton = document.getElementById('optionsdonebutton');
	donebutton.onclick = function() { fadeDiv('optionspane', 'out', 15); waitForFade( startScreen ); };
}

function showOptionsPanelEnd () {
	setUpOptions();
	fadeDiv('endscreen', "out",  15);
	waitForFade( function(){ fadeDiv('optionspane', 'in', 15, 0.95); } );
	var donebutton = document.getElementById('optionsdonebutton');
	donebutton.onclick = function() { fadeDiv('optionspane', 'out', 15); waitForFade( function() {fadeDiv('endscreen', 'in', 15, 1 ); } )};
}

function showInstructionsStart () {
	var donebutton = document.getElementById('instructionsdonebutton');
	donebutton.onclick = hideInstructionsStart;
	fadeDiv('startscreen', "out",  15, 0.95);
	waitForFade( function(){ fadeDiv('instructions', 'in', 15, 0.95); } );
} 

function hideInstructionsStart () {
	fadeDiv('instructions', 'out', 15); 
	waitForFade( startScreen );
}

function showInstructionsEnd () {
	var donebutton = document.getElementById('instructionsdonebutton');
	donebutton.onclick = hideInstructionsEnd;
	fadeDiv('endscreen', "out",  15 );
	waitForFade( function(){ fadeDiv('instructions', 'in', 15, 0.95); } );
}

function hideInstructionsEnd () {
	fadeDiv('instructions', 'out', 15); 
	waitForFade( function() {fadeDiv('endscreen', 'in', 15, 1 ); } )
}

function showAbout() {
	fadeDiv('endscreen', 'out', 15); 
	waitForFade( function() {fadeDiv('about', 'in', 15, 1 ); } )
}

function hideAbout() {
	fadeDiv('about', 'out', 15); 
	waitForFade( function() {fadeDiv('endscreen', 'in', 15, 1 ); } )
}

function startNewGame() {
//placeEnemyShips();
	fadeDiv('startscreen', "out", 5);

	//startbox.setAttribute("class", "hidden");
	slideBoard( "player" );
	waitForSlide( playerPlaceShips );
}

var slidechecktimeout;
var slideglobalcallback;

function waitForSlide( callFunction ) {
	slideglobalcallback = callFunction;
	waitForSlideWork();
}

function waitForSlideWork ( ) {
	if (issliding == false) {
		clearTimeout(slidechecktimeout);
		slideglobalcallback();
	} else {
		slidechecktimeout = setTimeout("waitForSlideWork()", 10);
	}
}

function playerPlaceShips() {
	setMessage("Place Your Ships");
	shiptoplace = "none";
	if (autoshipplace == true && autoplacedalready==false) { autoPlacePlayerShips(); }
	gamestate = "placingships";
	uncoverBoard();
	var count = 0;
	while (shiptoplace == "none") { //look for unplaced ships
		if (count<=ships.length-1) {
			shiptoplace = (ships[count].status == "placed") ? "none" : ships[count];
			count++;
		} else {
			shiptoplace = "done";
		}
	}
	if (shiptoplace == "done") {
		coverBoard();
		finishedPlacingPlayerShips();
	} else {
		placeShip(shiptoplace);
	}
}

function placeShip( shiptoplace ) {
	shipbeingplaced = shiptoplace;
	gameAlert("Please place your<br/>"+shiptoplace.name, false, 55);
}

function processPlaceShipClick( whogotclicked ){
	 if (shipbeingplaced!="none") {
	 //alert( whogotclicked+shipbeingplaced.name );

	 	shipbeingplaced.tryToPlaceShip( whogotclicked );
	 }
}


function finishedPlacingPlayerShips () {
	coverBoard();
	setTimeout( function(){ fadeDiv('doneplacing', "in"); }, 800/speed);
	//doneplacingdialog.setAttribute("class", "dialog");
}

function adjustMyShips() {
	gamestate = "placingships";
	uncoverBoard();
	fadeDiv('doneplacing', "out", 5);
	//doneplacingdialog.setAttribute("class", "hidden");
	setMessage("Select a ship to reposition it");
}

function placeEnemyShips () {
	fadeDiv('doneplacing', "out", 50);
	waitForFade( function () { fadeDiv('placingenemyships', "in", 4);
	slideBoard( "enemy" );
	waitForSlide( placeEnemyShipsWork ); }
	);
	setMessage("Placing Enemy Ships");

	
}

function placeEnemyShipsWork() {

	var testval = false;
	
	for (var count = 0; count<enemyships.length; count++) {

		do {	
			var edgeweighting = (Math.random()>0.25) ? true : false;
			var randrow = (edgeweighting == true) ? chooseRandomEdge() : chooseRandomCenter() ;
			var randcol = (edgeweighting == true) ? chooseRandomEdge() : chooseRandomCenter() ;
			var randloc = "e"+randrow;
			randloc += randcol;
			shipbeingplaced = enemyships[count];
			shipbeingplaced.orientation = (Math.random() > 0.5) ? "vertical" : "horizontal";
			shipbeingplaced.tryToPlaceShip(randloc);
		} while (enemyships[count].status !== "placed");
	}
	waitForFade( function () { fadeDiv('placingenemyships', "out", 4); });
	playGame();
}

function chooseRandomEdge() {
	var position = Math.floor(Math.random()*3);
	var location = (Math.random() > 0.5) ? 9-position : 0+position ;
	return location;
}

function chooseRandomCenter() {
	var location = Math.floor(Math.random()*4)+3;
	return location;
}

function autoPlacePlayerShips() {
	//alert("gothere");
	gamestate = "autoplacingships";
	var testval = false;
	for (var count = 0; count<ships.length; count++) {

		do {	

			var randrow = Math.floor(Math.random()*10);//alert("gothere");
			var randcol = Math.floor(Math.random()*10);
			var randloc = "p"+randrow;
			randloc += randcol;
			shipbeingplaced = ships[count];
			shipbeingplaced.orientation = (Math.random() > .5) ? "vertical" : "horizontal";
			shipbeingplaced.tryToPlaceShip(randloc);
		} while (ships[count].status !== "placed");
	}
		shiptoplace = "done";
		autoplacedalready = true;
}

/********** In Game Functions *************/
function playGame() {
	
	gamestate = "gameon";
	setTimeout(function () { gameAlert("Take your first shot."); uncoverBoard(); }, 1000/speed );
	setMessage("Click spot above to fire!");
}

function processGameOnClick( whogotclicked ) {
	//alert('damnit');
	if(whosturn=="player") {
		switch ( testLocation(whogotclicked) ) {
			case "ship":
				shootMissle( whogotclicked, 'hit', function() { playerHit( whogotclicked ); } );
			
			break;
			case "hit":
			
			break;
			case "miss":

			break;
			default:
				//alert('gothere');
				shootMissle( whogotclicked, 'miss', function() { playerMiss( whogotclicked ); } );		
		}
	}

}

var shipsinktoastcount = 0;

function playerHit( whogotclicked ) {
	setMessage("Good Shot!");
	document.getElementById( whogotclicked ).setAttribute("class", "hit");
	playerTookShot();
	var bonus = testHitShip( whogotclicked );
	playerscore += 100 + bonus;
	totalscore += 100 + bonus;
	updateScoreDisplay();
	isGameOver();
}

function playerMiss( whogotclicked ) {
	//gameAlert("MISS");
	coverBoard();
	setMessage("Too Bad");
	var missspot = document.getElementById( whogotclicked );
	missspot.setAttribute("class", "miss");
	//fadeDiv(missspot, "out", 3, 1, 0.1);
	playerTookShot();
	isGameOver();
	if (gamestate!="over") { 
		setTimeout(function (){ waitForFade( iMissed ); }, 350);
	}
}

function playerTookShot() {
	playershotsleft--;
	playershoticons[playershotsleft].setAttribute("class", "hidden");
}

function updateScoreDisplay() {
	var scoredisplay = document.getElementById('playerscore');
	scoredisplay.innerHTML='';
	scoredisplay.innerHTML= playerscore;

	highscore = (playerscore > highscore) ? playerscore : highscore;
	var hiscoredisplay = document.getElementById('hiscore');
	hiscoredisplay.innerHTML='';
	hiscoredisplay.innerHTML= highscore;
}

function iMissed() {
	shipsinktoastcount = 0;

	switch (whosturn) {
		case "player": //player missed
			if (enemyshotsleft > 0) {
				whosturn = "enemy";
				slideBoard( "player" );
				setMessage("Enemy's Turn");
				waitForSlide(takeComputerTurn);
			}
		break;
		case "enemy": //enemy missed
			if (playershotsleft > 0) {
				setMessage("Your Turn");
				uncoverBoard();
				playersTurn();
			}
		break;
		default:
	}
}

function playersTurn() { 
	whosturn = "player";
	slideBoard( "enemy" );
	waitForSlide (uncoverBoard);

}
var hitrecord = [];
//var shipssunk = [];
var possibleship = [];
var possibledirection = "all"; //direction of suspected ship
var lookdirection = "forwards";
var isunkaship = false;
var sunkcells;

function takeComputerTurn() {

	coverBoard();
	var location;
	
	if (isunkaship == true) {
		isunkaship = false;
		lookdirection = "forwards";
		removeSunkCellsFromHitList();
		emptyPossibleShip();
	}
	
	if (possibleship.length > 0 && levelsetting > 1) {
		location = goAfterSuspectedShip();
	} else if ((hitrecord.length > 0 && possibleship.length == 0) && ( levelsetting > 1 )) {
		location = goAfterHitShip();
	} else {
		location = pickRandomLocation(); //Only random at lowest difficulty
	}
	
	if (location == "lostship" || location == "sunkship" || location == false ) {// If I though I had a ship, but lost it.
		if (hitrecord.length > 0) { location = goAfterHitShip(); } else { location = pickRandomLocation(); }
	}
	
	//alert("location"+location);
	setTimeout( function () { processEnemyShot( location ); }, 300/speed ); //delay computer action 300ms
}

function goAfterSuspectedShip() {
	//alert('gothere');
	var trylocation;
	if (isunkaship == true) {
		lookdirection = "forwards";
		emptyPossibleShip();
		removeSunkCellsFromHitList();
		isunkaship = false;
		trylocation = "sunkship";
	} else if ((hitrecord[hitrecord.length-1]!=possibleship[possibleship.length-1])&&(lookdirection=="forwards")) {
		possibleship.push(hitrecord[hitrecord.length-1]);
		trylocation = testHitNeighbors( hitrecord[hitrecord.length-1], possibledirection );
	} else if ((hitrecord[hitrecord.length-1]==possibleship[possibleship.length-1])&&(lookdirection=="forwards")) {
		lookdirection = "reverse";
		trylocation = testHitNeighbors( possibleship[0], possibledirection );
	} else if ((hitrecord[hitrecord.length-1]!=possibleship[possibleship.length-1])&&(lookdirection=="reverse")) {
		possibleship.unshift(hitrecord[hitrecord.length-1]);
		trylocation = testHitNeighbors( hitrecord[hitrecord.length-1], possibledirection );
	} else if ((hitrecord[hitrecord.length-1]==possibleship[possibleship.length-1])&&(lookdirection=="reverse")) {
		lookdirection = "forwards";
		emptyPossibleShip();
		trylocation = "lostship";
		possibledirection = "";
	}
	
	if (trylocation == false && lookdirection == "forwards") {
		lookdirection = "reverse";
		trylocation = testHitNeighbors( possibleship[0], possibledirection );
	} else if (trylocation == false && lookdirection == "forwards") {
		lookdirection = "forwards";
		trylocation = "lostship" ;
		possibledirection = "";
	}
	
	return trylocation;
}

function emptyPossibleShip() {
 //alert("empty possible ship");
 while (possibleship.length > 0) {
 	var removed = possibleship.pop();
 }
// alert("empteed possible ship");

}

function removeSunkCellsFromHitList() {

	while (sunkcells.length > 0) {
		var acell = sunkcells.pop();
		var amatch = false;
		var count = 0;
		while (acell!=hitrecord[count]) {
			count++;
		}
		var removed = hitrecord.splice(count, 1);
		//alert("removed"+removed);
	}
	
}

function goAfterHitShip() {
	
	var trylocation = testHitNeighbors( hitrecord[hitrecord.length-1], "all" );
	
	var count = 0; //If last hit has no good neighbor locations, try previous hits
	while (count < hitrecord.length && trylocation == false) {
		trylocation = testHitNeighbors( hitrecord[count], "all" );
		count++;
	}
	
	if (trylocation == false) { //If no one has any good neighbor locations
		trylocation = pickRandomLocation();
	}
	
	return trylocation;
}

function testHitNeighbors( testmyneighbors, direction ) {
	var suggestedlocation;
	var direction = (direction==null) ? "all" : direction; //all || topbottom || leftright;
	
	var lasthit = testmyneighbors;
	var lasthitrow = extractCellRow(lasthit);
	var lasthitcol = extractCellCol(lasthit);
	var top = ((lasthitrow-1)>=0) ? 'p'+(lasthitrow-1)+lasthitcol : false ;
	var left = ((lasthitcol-1)>=0) ? 'p'+lasthitrow+(lasthitcol-1) : false ;
	var right = ((lasthitcol+1)<=9) ? 'p'+lasthitrow+(lasthitcol+1) : false ;
	var bottom = ((lasthitrow+1)<=9) ? 'p'+(lasthitrow+1)+lasthitcol : false ;
	
	var neighbors = [top, left, right, bottom];
	var neighborscore = [];
	
	//socore the neighbors
	for (var count=0; count < neighbors.length; count++) {
		neighborscore[count] = scoreNeighbor(neighbors[count]);
	}
	var top_bottompick = false;
	var left_rightpick = false;
	var top_bottomopposite = false;
	var left_rightopposite = false;
	
	//limit direction 
	//alert(neighborscore[0]);
	neighborscore[0] = (direction!="leftright") ? neighborscore[0] : 0 ;
	//alert(neighborscore[0]);
	neighborscore[1] = (direction!="topbottom") ? neighborscore[1] : 0 ;
	neighborscore[2] = (direction!="topbottom") ? neighborscore[2] : 0 ;
	neighborscore[3] = (direction!="leftright") ? neighborscore[3] : 0 ;
	
	var topscore = neighborscore[0];
	var leftscore = neighborscore[1];
	var rightscore = neighborscore[2];
	var bottomscore = neighborscore[3];
	
	//find the top bottom pick
	if ( neighborscore[0]==3 && neighborscore[3]==1 ) {
		top_bottompick = neighbors[0]; top_bottomopposite = neighbors[3];
	} else if (neighborscore[0]==1 && neighborscore[3]==3) {
		top_bottompick = neighbors[3]; top_bottomopposite = neighbors[0];
	} else if (neighborscore[0]==3 && neighborscore[3]==3) {
		var randpic = Math.random();
		top_bottompick = (randpic > 0.5) ? neighbors[0] : neighbors[3];
		top_bottomopposite = (randpic > 0.5) ? neighbors[3] : neighbors[0] ;
	} else if (neighborscore[0]==3 && neighborscore[3]<=2) {
		top_bottompick = neighbors[0]; top_bottomopposite = neighbors[3];
	} else if (neighborscore[0]<=2 && neighborscore[3]==3) {
		top_bottompick = neighbors[3]; top_bottomopposite = neighbors[0];
	} else if (neighborscore[0]<=2 && neighborscore[3]<=2) {
		top_bottompick = false; top_bottomopposite = false;
	}

	//find the left right pick
	if ( neighborscore[1]==3 && neighborscore[2]==1 ) {
		left_rightpick = neighbors[1]; left_rightopposite = neighbors[2]; 
	} else if (neighborscore[1]==1 && neighborscore[2]==3) {
		left_rightpick = neighbors[2]; left_rightopposite = neighbors[1];
	} else if (neighborscore[1]==3 && neighborscore[2]==3) {
		var randpick = Math.random();
		left_rightpick = (randpick>0.5) ? neighbors[1] : neighbors[2];
		left_rightopposite = (randpick>0.5) ? neighbors[2] : neighbors[1];
	} else if (neighborscore[1]==3 && neighborscore[2]<=2) {
		left_rightpick = neighbors[1]; left_rightopposite = neighbors[2];
	} else if (neighborscore[1]<=2 && neighborscore[2]==3) {
		left_rightpick = neighbors[2]; left_rightopposite = neighbors[1];
	} else if (neighborscore[1]<=2 && neighborscore[2]<=2) {
		left_rightpick = false; left_rightopposite = false;
	}

	var top_bottomscore = topscore + bottomscore; 
	var left_rightscore = leftscore + rightscore;

	//decide which pick to go with based on scores and infer about ship placement
	if (top_bottomscore == 4 && left_rightscore==4 ) {
		suggestedlocation = (Math.random()>0.5) ? left_rightpick : top_bottompick;
		//possibleship.push(lasthit, suggestedlocation);
	} else if (top_bottomscore == 4  && left_rightscore!=4 ) {
		suggestedlocation = top_bottompick; possibledirection = "topbottom";
		if (possibleship.length == 0) { possibleship.push(top_bottomopposite, lasthit); possibledirection = "topbottom"; }// Might be a ship
	} else if (top_bottomscore != 4  && left_rightscore == 4 ) {
		suggestedlocation = left_rightpick;  possibledirection = "leftright";
		if (possibleship.length == 0) { possibleship.push(left_rightopposite, lasthit); }//Might be a ship
	} else if ((top_bottomscore == 6 || left_rightscore == 6 )&&(top_bottomscore != 4 && left_rightscore!=4)) {
		suggestedlocation = (top_bottomscore == 6) ? top_bottompick : left_rightpick;
	} else if ((top_bottomscore == 3 || left_rightscore == 3 )&&(top_bottomscore != 4 && left_rightscore!=4)) {
		suggestedlocation = (left_rightscore == 3) ? left_rightpick : top_bottompick;
	} else if (top_bottomscore < 3  && left_rightscore < 3 ) {
		suggestedlocation = false;
	}
	return suggestedlocation;
}

function scoreNeighbor ( neighbor ) {
	var testResult;
	var score = 0;

	if (neighbor!==false) {
	testResult = testLocation( neighbor );
		switch (testResult) {
			case "miss":
				score = 0; //gives no benifit to across neighbor
			break;
			case "hit":
				score = 1;  //makes unkown across neigbor '4' and is what we're looking for
			break;
			default:
				score = 3; //unkown across neigbors are '6'
		}
	} else {
		score = 0;
	}
	return score;
}

function pickRandomLocation () {
	var randloc;
	var mytryresult;
	var count;
	var isthereroom = true;
	do {	
		count++;
		randloc = "p"+Math.floor(Math.random()*10);
		randloc += Math.floor(Math.random()*10); 
		mytryresult = testLocation(randloc);
		if (levelsetting > 1) {
			isthereroom = checkForRoom(randloc);
		}
	} while ((mytryresult=="hit") || (mytryresult=="miss") || (isthereroom == false));
	return randloc;
}

function checkForRoom( location ) {
	var count = 0;
	var endresult = false;
	while (count < ships.length) {
		if (ships[count].issunk != true) {
			var horzintalresult = ships[count].testHorizontalInGame( location );
			var verticalresult = ships[count].testVerticalInGame( location );
			if (horzintalresult==false && verticalresult==false) {
				endresult = endresult;
			} else {
				endresult = true;
			}
		}
		count++;
	}
	
	return endresult;
}

function processEnemyShot( location ) {
//alert(location);
	switch ( testLocation(location) ) {
		case "ship":
				shootMissle( location, 'hit', function() { enemyHit( location ); } );
		break;
		case "hit":
		
		break;
		case "miss":
			
		break;
		default:
				shootMissle( location, 'miss', function() { enemyMiss( location ); } );		
	}

}

function enemyHit( location ) {
	document.getElementById(location).setAttribute("class", "hit");
	enemyTookAShot();
	var bonus = testHitShip( location );
	enemyscore += 100 + bonus;
	hitrecord.push(location);
	isGameOver();
	if (gamestate!="over") {
		setTimeout(function (){ waitForFade( takeComputerTurn ); }, 2550/speed);
	}
}

function enemyMiss( location ) {
	//gameAlert("MISS");
	document.getElementById( location ).setAttribute("class", "miss");
	enemyTookAShot();
	isGameOver();
	if (gamestate!="over") { 
		setTimeout(function (){ waitForFade( iMissed ); }, 150);
	}
}

function enemyTookAShot() {
	enemyshotsleft--;
	enemyshoticons[enemyshotsleft].setAttribute("class", "hidden");
}

function testHitShip( whogotclicked ) {

	var testships = ( whosturn == "player") ? enemyships : ships;
	var count = 0;
	var bonus = 0;
	do { 
		if (testships[count].isItYou( whogotclicked ) === false) {
			count++;
		} else {
			testships[count].imHit();
			bonus = testships[count].bonus;
			count = testships.length;
		}
	} while (count < testships.length);
	return bonus;
}

function isGameOver() {
	if (allShipsSunk(ships)==true || allShipsSunk(enemyships)==true || playershotsleft<=0 || enemyshotsleft<=0) {
		gamestate = "over";
		setMessage("GAME OVER");
		displayEndScreen();
	}
}

function allShipsSunk ( shiplist ) {
	var howmanysunk = 0;
	for (var count = 0; count < shiplist.length; count++) {
		howmanysunk += (shiplist[count].issunk == true) ? 1 : 0;
	}
	var result = (howmanysunk == shiplist.length) ? true : false;
	//alert(result);
	return result;
}

function displayEndScreen() {
	var es = [];
	//setTimeout(function () { waitForFade(function () { endscreen.setAttribute('class', 'dialog'); tallyScores(); } ); }, 1000);
	switch (whosturn) {
		case "player": //enemy board is visible
			es[0] = setTimeout(function () { showEShips(); }, 100);
			es[1] = setTimeout(function () { endscreen.setAttribute('class', 'dialog'); tallyScores(); }, 2100);
		break;
		case "enemy": //player board is visible
			es[0] = setTimeout(function () { slideBoard('enemy'); }, 450 );
			es[1] = setTimeout(function () { showEShips(); }, 700);
			es[2] = setTimeout(function () { endscreen.setAttribute('class', 'dialog'); tallyScores(); }, 2400);
		break;
		default:
			es[0] = setTimeout(function () { slideBoard('enemy'); }, 50 );
			es[1] = setTimeout(function () { showEShips(); }, 500);
			es[2] = setTimeout(function () { endscreen.setAttribute('class', 'dialog'); tallyScores(); }, 2400);
	}
	
}

var scorecount;
var showpercent = 0;

function tallyScores() {
	var outcome = (playerscore > enemyscore) ? "winner" : (playerscore == enemyscore) ? "draw" : "loser" ;
	var outcomediv = document.getElementById("outcome");
	gamesplayed++;
	
	var outcomemessage;
	switch ( outcome ) {
		case "winner":
			outcomediv.innerHTML = "You Win!";
			gameswon++;
			
			break;
		case "loser":
			outcomediv.innerHTML = "You Lose!";
			gameslost++;
		break;
		case "draw":
			outcomediv.innerHTML = "Tie!";
			gamestied++;
		break;
		default:

	}
	updateStats();
	
	showpercent = 0;
	countUpEnd();
	
	
	//document.getElementById("rematchbutton").setAttribute("onclick", "rematch();");
 }

function countUpEnd () {
	showpercent += 20;
	if (showpercent <= 100) {
		var ypoints = document.getElementById("yourpoints");
		var tpoints = document.getElementById("theirpoints");
		ypoints.innerHTML = ''+(playerscore*(showpercent/100));
		tpoints.innerHTML = ''+(enemyscore*(showpercent/100));
		for(var count=0; count<ships.length; count++) {
			ships[count].showDamage(showpercent); 
			enemyships[count].showDamage(showpercent);
		}
		scorecount = setTimeout (countUpEnd, 50/speed);
	} else {
		clearTimeout(scorecount);
		
	}

}

function updateStats () {
	var expires = 1024;
	createCookie("gamesplayed",gamesplayed,expires);
	createCookie("gameswon",gameswon,expires);
	createCookie("gameslost",gameslost,expires);
	createCookie("gamestied",gamestied,expires);
	createCookie("totalscore",totalscore,expires);
	createCookie("highscore",highscore,expires);
	
	document.getElementById("gamesplayed").innerHTML = gamesplayed;
	document.getElementById("gameswon").innerHTML = gameswon;
	document.getElementById("gameslost").innerHTML = gameslost;
	document.getElementById("gamestied").innerHTML = gamestied;
	document.getElementById("totalscore").innerHTML = totalscore;

}

function rematch () {
	hideEShips();
	endscreen.setAttribute('class', 'hidden'); 
	resetGame();
	slideBoard('player');
	waitForSlide( playerPlaceShips );
}

function resetGame () {
	setMessage("Resetting...");
	gamestate = "start";
	whosturn = "player";
	shipbeingplaced = "none";
	resetComputerEnemy();
	
	//Put Ships back to 'virgin' state
	//initializeShips();alert('gothere');
	//initializeEnemyShips(); 
	autoplacedalready=false;
	//Clear last games score
	playerscore = 0;
	enemyscore = 0;
	
	//Clear the gameboard
	clearBoard(); 
	
	//reset shot count
	playershotsleft = (levelsetting>2) ? 22 : 44;
	enemyshotsleft = (levelsetting>2) ? 22 : 44;
	
	clearShips();
	initializePlayerShotIcons();
	initializeEnemyShotIcons();
	updateScoreDisplay();
	
}

function clearShips(){
for (var s=0; s<ships.length; s++) {
	ships[s].reset();
	enemyships[s].reset();
}
/*
	var shiplayer = document.getElementById("shiplayer");
	var eshiplayer = document.getElementById("enemyshiplayer");
	shiplayer.innerHTML = '';
	eshiplayer.innerHTML = '';
*/
}

function clearBoard() {
	for (var b = 0; b < 2; b++) {
		for (var row=0; row < 10; row++) {
			for (var col=0; col < 10; col++) {
				var id = (b==0) ? 'p' : 'e';
				id += row;
				id += col;
				var cell = document.getElementById(id);
				cell.setAttribute('class', 'blank');
			}
		}
	}
}

function resetComputerEnemy () {
	var removed 
	while (hitrecord.length > 0) {
		removed = hitrecord.pop(); 
	}
		while (possibleship.length > 0) {
		removed = possibleship.pop(); 
	}
}

/********** Dialog and Fade Options **********/

var fadertimer;
var atimer="stopped";
//var fadespeed = (speed==2) ? 5 : 1;
var btimer;

function setMessage (message) {
	var marea = document.getElementById("messagearea");
	marea.innerHTML = "";
	marea.innerHTML = message;
}

function gameAlert (message, coverboard, milliseconds, maxopacity) {
	var gamealert = document.getElementById("gamealert");
	if (coverboard === true) { coverBoard(); }
	gamealert.innerHTML = '';
	gamealert.innerHTML = message;
	//atimer = -10;
	fadeDiv( "gamealert", "inout", milliseconds, maxopacity );
	if (coverboard === true) { waitForFade( uncoverBoard ); }
}

function fadeDiv( whatdiv, direction, milliseconds, maxopacity, minopacity ) { 
	var divtofade = document.getElementById( whatdiv );
	var direction = (direction == null) ? "inout" : direction;
	var milliseconds = (milliseconds == null) ? 80 : milliseconds;
	var maxopacity = (maxopacity == null) ? 0.8 : maxopacity;
	var minopacity = (minopacity == null) ? -1 : minopacity;
	if (atimer==="stopped") { 
		switch (direction) {
			case "in":
				atimer = -10;
				btimer = 0;
				divtofade.setAttribute('class', 'dialog');				
			break;
			case "out":
				atimer = 0;
				btimer = 10;
			break;
			case "inout":
				divtofade.setAttribute('class', 'dialog');				
				atimer = -10;
				btimer = 10;
			break;
			default:
		}
	} 
	var speedadjusted = (speed==2) ? 1.5 : 1;
	var nexto = fadeAnimCurve( atimer );
	if (atimer < btimer && nexto > minopacity) {
		atimer += speed;
		divtofade.style.opacity = (nexto >= maxopacity) ? maxopacity : nexto;
		fadertimer = setTimeout(function () { fadeDiv(whatdiv, direction, milliseconds, maxopacity); }, Math.floor(milliseconds/speedadjusted));
	} else {
		clearTimeout(fadertimer);
		if ((direction=="out" || direction=="inout")&&(minopacity === -1)) {
			divtofade.setAttribute('class', 'hidden');
		}
		atimer = "stopped";
	}

}

function fadeAnimCurve( x ) {
	var y = (-0.013 *(x*x))+1.314; //animation curve function
	return y;
}

var waitfade;

function waitForFade (callback) {
	if (atimer!="stopped") {
		waitfade = setTimeout(function () { waitForFade( callback );}, 80 ); 
		
	} else {
		clearTimeout(waitfade);
		callback(); 
	}
}

/********* Cookie Functions ********************/

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else {var expires = "";}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


/********** Ship Object Declairations ************/
function resetShip() {
	this.damage = 0;
	this.issunk = false;
	this.status = "none"; //string with the state of the ship
	while (this.cells.length>0) {
		var removed = this.cells.pop();
	}
	this.sunkindicator.innerHTML = '';
	this.damageindicator.innerHTML = '';
	this.shiplayer.removeChild(this.shipdiv);
	this.initialize();

}

function initializeShip () {	
	var whichboard = (this.isenemy == true) ? "enemyshiplayer" : "shiplayer";
	this.shiplayer = document.getElementById(whichboard);


	this.bonus = this.gridsize * 100 * levelsetting;
			//alert(this.shipdiv);	
 
		this.shipdiv = document.createElement('div');
			this.shipdiv.style.position = "absolute";
			this.shipdiv.style.width = (this.gridsize * 32) + "px";
			this.shipdiv.style.height = (this.gridsize * 32) + "px";
	
		this.verticalshipdiv = document.createElement('div');
			this.shipdiv.appendChild(this.verticalshipdiv);
			this.verticalshipdiv.style.position = "absolute";
			this.verticalshipdiv.style.width = "32px";
			this.verticalshipdiv.style.height = (this.gridsize * 32) + "px";
			this.verticalshipdiv.style.backgroundImage = "url(ships/"+this.imagename+"v.gif)";			
			this.verticalshipdiv.style.top = "0px";
			this.verticalshipdiv.style.left = "0px";
			this.verticalshipdiv.setAttribute("class", "hidden");
	
		this.horizontalshipdiv = document.createElement('div');
			this.shipdiv.appendChild(this.horizontalshipdiv);
			this.horizontalshipdiv.style.position = "absolute";
			this.horizontalshipdiv.style.width = (this.gridsize * 32) + "px";
			this.horizontalshipdiv.style.height = "32px";
			this.horizontalshipdiv.style.backgroundImage = "url(ships/"+this.imagename+"h.gif)";
			this.horizontalshipdiv.style.top = "0px";
			this.horizontalshipdiv.style.left = "0px";
			this.horizontalshipdiv.setAttribute("class", "hidden");
	
		this.shiplayer.appendChild(this.shipdiv);

}

function tryToPlaceShip ( locationid ) {
	if (this.testLocation(locationid)!="ship") {
		var horizontalresult = this.testHorizontal( locationid );
		var verticalresult = this.testVertical( locationid );
		if (horizontalresult===false && verticalresult===false){
				if (!this.isenemy && gamestate!="autoplacingships")	{alert("Can't place Ship in that location");}
				 return false;
		} else {
			if (horizontalresult!=false && this.orientation==="horizontal"){ this.placeHorizontal(horizontalresult); }
			else if (verticalresult!==false && this.orientation==="vertical"){ this.placeVertical(verticalresult); }
			else if (verticalresult!==false && horizontalresult===false){ this.placeVertical(verticalresult); }
			else if (horizontalresult!==false){ this.placeHorizontal(horizontalresult); }
			return true;
		}
	} else {
		if (!this.isenemy && gamestate!="autoplacingships")	{switchShipsToPlace( locationid );} //Grab a different ship
		return false;
	}
}


function switchShipsToPlace ( locationid ) { //Grab a different ship

	var count=0;
	do {
		if (ships[count].isItYou(locationid)===false) {
			count++;
		} else {
		
			shipbeingplaced.hideControls();
			ships[count].showControls( ships[count].cells );
			placeShip( ships[count] );
			count = ships.length;
		}
	} while (count<ships.length);
}

function isItYou ( location ) { //takes one location and sees if it matches ships cell list
	var cellcheck = 0;
	var found = false;
	do {	
		found = (this.cells[cellcheck]==location) ? true : false;
		cellcheck ++;
	} while (cellcheck<this.cells.length && found==false);
	//alert( location+found + this.name +this.cells );
	return found;
}

function  imHit () {
	this.damage++;
	if (this.damage == this.gridsize) { 
		this.imSunk(); 
	} else {
		//gameAlert("HIT!");
	}

}

function imSunk () {
	this.issunk = true;
	shipsinktoastcount++; // if three ships sink without a miss, toastie
	if (shipsinktoastcount >= 3) { gotToast(); }
	if (this.isenemy != true) { isunkaship = true; sunkcells = this.cells.slice(); }
	var sunkmessage = (this.isenemy) ? "You sunk my<br/>"+this.name : "I sunk your<br/>"+this.name ;
	waitForFade(function () { gameAlert(sunkmessage, true, 90); } );
	var xedout = document.createElement('img');
	xedout.setAttribute("src", "images/letters/x.png");
	
	this.sunkindicator.appendChild(xedout);
}

function placeVertical ( locations ) {
	this.orientation = "vertical";
	if(gamestate=="placingships") { this.showControls( locations ); }
	this.horizontalshipdiv.setAttribute("class", "hidden");// turn off horizontal ship
	var topleftcellid = locations[0];
	var toppos = extractCellRow(topleftcellid) * 32;
	var leftpos = extractCellCol(topleftcellid) * 32;
	this.shipdiv.style.top = toppos+"px";
	this.shipdiv.style.left = leftpos+"px";
	this.verticalshipdiv.setAttribute("class", "placed");
	this.setShipLocation( locations );
}

function placeHorizontal ( locations ) {
	this.orientation = "horizontal";
	if(gamestate=="placingships") { this.showControls( locations ); }
	this.verticalshipdiv.setAttribute("class", "hidden");//turn off vertical ship
	var topleftcellid = locations[0];
	var toppos = extractCellRow(topleftcellid) * 32;
	var leftpos = extractCellCol(topleftcellid) * 32;
	this.shipdiv.style.top = toppos+"px";
	this.shipdiv.style.left = leftpos+"px";
	this.horizontalshipdiv.setAttribute("class", "placed");
	this.setShipLocation( locations );
}

function showControls ( locations ) {
//alert("gotherexx"+this.cells);
	if (this.isenemy==false) {
		this.controllayer = document.getElementById("control");
	
		this.hideControls();
		
		this.rotatediv = document.createElement('div');
		this.controllayer.appendChild(this.rotatediv);
			this.rotatediv.setAttribute("style", "position:absolute; width:32px; height:32px; background-image: url(images/rotateicon.png);");
			this.rotatediv.setAttribute("class", "hidden");
			this.rotatediv.onclick = rotateShip; 
		this.setdiv = document.createElement('div');
		this.controllayer.appendChild(this.setdiv);
			this.setdiv.setAttribute("style", "position:absolute; width:32px; height:32px; background-image: url(images/checkicon.png);");
			this.setdiv.setAttribute("class", "hidden");
			this.setdiv.onclick = setShip;
			
		switch (this.orientation) {
			case "horizontal":
				this.showHorizontalControls( locations );
			break;
			case "vertical":
				this.showVerticalControls( locations );
			break;
			default:
			
		}
	}
			
}

function showHorizontalControls( locations ) {
	var myrow = extractCellRow(locations[0])+1;
	myrow = (myrow>9) ? 8 : myrow;
	//alert(myrow);
	var mycol = extractCellCol(locations[0]);
	this.rotatediv.style.top = (myrow * 32)+"px";
	this.rotatediv.style.left = (mycol * 32) + "px";
	this.rotatediv.setAttribute("class", "shown");
	this.setdiv.style.top = (myrow * 32)+"px";
	this.setdiv.style.left = ((mycol+1) * 32) + "px";
	this.setdiv.setAttribute("class", "shown");
}

function showVerticalControls( locations ) {
	var myrow = extractCellRow(locations[0]);
	var mycol = extractCellCol(locations[0])+1;
	mycol = (mycol>8) ? 7 : mycol;
	this.rotatediv.style.top = (myrow * 32)+"px";
	this.rotatediv.style.left = (mycol * 32) + "px";
	this.rotatediv.setAttribute("class", "shown");
	this.setdiv.style.top = (myrow * 32)+"px";
	this.setdiv.style.left = ((mycol+1) * 32) + "px";
	this.setdiv.setAttribute("class", "shown");
}

function rotateShip() {
	if (gamestate == "placingships") {
		shipbeingplaced.rotateShip();
	}
}

function rotateThisShip() {
	switch (this.orientation) {
		case "horizontal":
			var canirotate = this.testVertical(this.cells[0]);//Math.ceil(this.cells.length/2)
			if (canirotate!=false) {
				this.placeVertical(canirotate);
			} else { alert("Can't rotate ship"); }
		break;
		case "vertical":
			var canirotate = this.testHorizontal(this.cells[0]);
			if (canirotate!=false) {
				this.placeHorizontal(canirotate);
			} else { alert("Can't rotate ship"); }
		break;
		default:
		
	}
}

function setShip() {
	if (gamestate == "placingships") {
		shipbeingplaced.hideControls();
		shipbeingplaced.status = "placed";
		playerPlaceShips();
	}
}

function hideControls() {
	this.controllayer = document.getElementById("control");
	//this.setdiv.setAttribute("class", "hidden");
	//this.rotatediv.setAttribute("class", "hidden");
			this.controllayer.innerHTML = '';
}

function testLocation ( locationid ) { //returns class of specified playerboard div
	return document.getElementById(locationid).getAttribute("class");
}

function testHorizontal ( locationid ) {
	var right = 0; //how many free spaces to the right
	var left = 0; //how many free spaces to the left
	var count = 0;
	var currentspotcontains = "";
	var prefix = extractCellBoard( locationid );
	var row = extractCellRow( locationid );
	var firstcol = extractCellCol( locationid );
	var currentcol = firstcol;	
	var freespots = [ locationid ];
	
	//check free space to the right
	while ( (count<this.gridsize-1) && (currentspotcontains!="ship") && (currentcol<9) ){
		count++;
		currentcol++;
		testid = prefix+row+currentcol;
		currentspotcontains = this.testLocation( testid );
		if (currentspotcontains=="ship" && this.isItYou( testid )) { currentspotcontains = ""; }
		if ((currentspotcontains!="ship") && (currentcol<=9)) { freespots.push(testid); right++; }
	} 
	if (right >= this.gridsize-1) { //if there's enough room to the right
		return freespots;
	} else { //check free space to the left
		count = 0;
		currentcol = firstcol;
		currentspotcontains = "";
		while ( (count<this.gridsize-1) && (currentspotcontains!="ship") && (currentcol>1) ){
			count++;
			currentcol--;
			testid = prefix+row+currentcol;
			currentspotcontains = this.testLocation( testid );
			if (currentspotcontains=="ship" && this.isItYou( testid )) { currentspotcontains = ""; }
			if ((currentspotcontains!="ship") && (currentcol>=1)) { freespots.unshift(testid); left++; }
		} 
		if (left >= this.gridsize-1) { //if there's enough room to the left
			freespots.splice(this.gridsize, 10);
			return freespots;
		} else {
			if (freespots.length >= this.gridsize) { //if there's enough room overall
				freespots.splice(this.gridsize, 10);
				return freespots;
			} else { //there's no room
				return false;
			}
		}
	}
}

function testVertical ( locationid ) {
	var top = 0; //how many free spaces to the top
	var bottom = 0; //how many free spaces to the bottom
	var count = 0;
	var currentspotcontains = "";
	var prefix = extractCellBoard( locationid );
	var firstrow = extractCellRow( locationid );
	var col = extractCellCol( locationid );
	var currentrow = firstrow;	
	var freespots = [ locationid ];
	
	//check free space to the top
	while ( (count<this.gridsize-1) && (currentspotcontains!="ship") && (currentrow<9) ){
		count++;
		currentrow++;
		testid = prefix+currentrow+col;
		currentspotcontains = this.testLocation( testid );
		if (currentspotcontains=="ship" && this.isItYou( testid )) { currentspotcontains = ""; }
		if ((currentspotcontains!="ship") && (currentrow<=9)) { freespots.push(testid); bottom++; }
	} 
	if (bottom >= this.gridsize-1) { //if there's enough room to the bottom
		return freespots;
	} else { //check free space to the top
		count = 0;
		currentrow = firstrow;
		currentspotcontains = "";
		while ( (count<this.gridsize-1) && (currentspotcontains!="ship") && (currentrow>1) ){
			count++;
			currentrow--;
			testid = prefix+currentrow+col;
			currentspotcontains = this.testLocation( testid );
			if (currentspotcontains=="ship" && this.isItYou( testid )) { currentspotcontains = ""; }
			if ((currentspotcontains!="ship") && (currentrow>=1)) { freespots.unshift(testid); top++; }
		} 
		if (top >= this.gridsize-1) { //if there's enough room to the top
			freespots.splice(this.gridsize, 10);
			return freespots;
		} else {
			if (freespots.length >= this.gridsize) { //if there's enough room overall
				freespots.splice(this.gridsize, 10);
				return freespots;
			} else { //there's no room
				return false;
			}
		}
	}
}



function setShipLocation ( locations ){
	var classcheck = 'Removed:';

	//Remove ship from previous location
	while (this.cells.length>0) {
		var oldspot = this.cells.shift();
		var olddiv = document.getElementById(oldspot);
		olddiv.setAttribute("class", "blank");
		classcheck += oldspot + olddiv.getAttribute("class");

	} 
	var i = 0;
	classcheck += 'Added:';
	while (this.cells.length<locations.length) {
		this.cells[i] = locations[i];
		var onecell = document.getElementById(locations[i]);
		onecell.setAttribute("class", "ship");
		classcheck += this.cells[i] + onecell.getAttribute("class");

		i++
	}
		//alert(this.name+"setShipLocationcells="+this.cells);

	if (this.isenemy || gamestate=="autoplacingships" ) { this.status = "placed"; }
}

function showDamage( percent ) {
	var showpercent = (percent == null) ? 100 : percent;
	var showpercent = showpercent / 100;
	this.damageindicator.innerHTML = '';
	if (this.damage!=0) {
		var damagegraph = document.createElement('div');
		var playerprefix = (playerteam == 1) ? 'e' : 'p';
		var enemyprefix = (playerteam == 1) ? 'p' : 'e';
		var damclass = (this.isenemy==false) ? playerprefix + 'damage' : enemyprefix + 'damage';
		damagegraph.setAttribute('class', damclass);
		damagegraph.style.width = (Math.floor((this.damage*140)/(this.gridsize)))*showpercent + 'px';
		this.damageindicator.appendChild( damagegraph );
		if (this.issunk == true && showpercent == 1) {
			damagegraph.innerHTML = "DESTROYED";
		}
	}
}

/***************** Versions for use by enemy during gameplay *****************/
function testHorizontalInGame ( locationid ) {
	var right = 0; //how many free spaces to the right
	var left = 0; //how many free spaces to the left
	var count = 0;
	var currentspotcontains = "";
	var prefix = extractCellBoard( locationid );
	var row = extractCellRow( locationid );
	var firstcol = extractCellCol( locationid );
	var currentcol = firstcol;	
	var freespots = [ locationid ];
	
	//check free space to the right
	while ( (count<this.gridsize-1) && (currentspotcontains!="miss") && (currentspotcontains!="hit") && (currentcol<9) ){
		count++;
		currentcol++;
		var testid = prefix+row+currentcol;
		currentspotcontains = this.testLocation( testid );
		if ((currentspotcontains!="miss") && (currentspotcontains!="hit") && (currentcol<=9)) { 
			freespots.push(testid); right++; 
		}
	} 
	if (right >= this.gridsize-1) { //if there's enough room to the right
		return freespots;
	} else { //check free space to the left
		count = 0;
		currentcol = firstcol;
		currentspotcontains = "";
		while ( (count<this.gridsize-1) && (currentspotcontains!="miss") && (currentspotcontains!="hit") && (currentcol>1) ){
			count++;
			currentcol--;
			var testid = prefix+row+currentcol;
			currentspotcontains = this.testLocation( testid );
			if ((currentspotcontains!="miss") && (currentspotcontains!="hit") && (currentcol>=1)) { 
				freespots.unshift(testid); left++; 
			}
		} 
		if (left >= this.gridsize-1) { //if there's enough room to the left
			freespots.splice(this.gridsize, 10);
			return freespots;
		} else {
			if (freespots.length >= this.gridsize) { //if there's enough room overall
				freespots.splice(this.gridsize, 10);
				return freespots;
			} else { //there's no room
				return false;
			}
		}
	}
}

function testVerticalInGame ( locationid ) {
	var top = 0; //how many free spaces to the top
	var bottom = 0; //how many free spaces to the bottom
	var count = 0;
	var currentspotcontains = "";
	var prefix = extractCellBoard( locationid );
	var firstrow = extractCellRow( locationid );
	var col = extractCellCol( locationid );
	var currentrow = firstrow;	
	var freespots = [ locationid ];
	
	//check free space to the top
	while ( (count<this.gridsize-1) && (currentspotcontains!="miss") && (currentspotcontains!="hit") && (currentrow<9) ){
		count++;
		currentrow++;
		var testid = prefix+currentrow+col;
		currentspotcontains = this.testLocation( testid );
		if ((currentspotcontains!="miss") && (currentspotcontains!="hit") && (currentrow<=9)) { 
			freespots.push(testid); bottom++; 
		}
	} 
	if (bottom >= this.gridsize-1) { //if there's enough room to the bottom
		return freespots;
	} else { //check free space to the top
		count = 0;
		currentrow = firstrow;
		currentspotcontains = "";
		while ( (count<this.gridsize-1) && (currentspotcontains!="miss") && (currentspotcontains!="hit") && (currentrow>1) ){
			count++;
			currentrow--;
			var testid = prefix+currentrow+col;
			currentspotcontains = this.testLocation( testid );
			if ((currentspotcontains!="miss") && (currentspotcontains!="hit") && (currentrow>=1)) { 
				freespots.unshift(testid); top++; 
			}
		} 
		if (top >= this.gridsize-1) { //if there's enough room to the top
			freespots.splice(this.gridsize, 10);
			return freespots;
		} else {
			if (freespots.length >= this.gridsize) { //if there's enough room overall
				freespots.splice(this.gridsize, 10);
				return freespots;
			} else { //there's no room
				return false;
			}
		}
	}
}

/********************* End Enemy Gameplay Functions ********************/

function ship(displayname, imagename, gridsize, isenemy, sunkindicatordiv, damageindicator ) {
	//properties
	this.name = displayname;
	this.imagename = imagename;
	this.isenemy = isenemy;
	this.gridsize = gridsize;
	this.sunkindicator = sunkindicatordiv;
	this.damageindicator = damageindicator;
	this.shiplayer;
	this.shipdiv; //main positioning element
	this.verticalshipdiv; //vertical ship image
	this.horizontalshipdiv; //horizontal ship image
	this.cells = []; //holds the grid locations of the ship
	this.status = "none"; //string with the state of the ship
	this.issunk = false;
	this.orientation; //horizontal or vertical
	this.controllayer;
	this.rotatediv;
	this.setdiv;
	this.damage = 0;
	this.bonus;
	this.sunkindicator = document.getElementById(this.sunkindicator);
	this.damageindicator = document.getElementById(this.damageindicator);
	
	
	//methods
	this.initialize = initializeShip;
	this.setShipLocation = setShipLocation;
	this.testHorizontal = testHorizontal;
	this.testVertical = testVertical;
	this.testLocation = testLocation;
	this.tryToPlaceShip = tryToPlaceShip;
	this.placeVertical = placeVertical;
	this.placeHorizontal = placeHorizontal;
	this.isItYou = isItYou;
	this.showHorizontalControls = showHorizontalControls;
	this.showVerticalControls = showVerticalControls;
	this.showControls = showControls;
	this.hideControls = hideControls;
	this.setShip = setShip;
	this.rotateShip = rotateThisShip;
	this.imHit = imHit;
	this.imSunk = imSunk;
	this.showDamage = showDamage;
	this.reset = resetShip;
	this.testHorizontalInGame = testHorizontalInGame;
	this.testVerticalInGame = testVerticalInGame;
}



/*********** End Ship **********/
/************ HAppyTimeFunExtraS! ******************/
var toasttimer = 'stopped';
var banditoextra;
var bandwindow;
var toastiediv;
var toastspeed = 100; //mills
var toastpercent = 0;
var bytoastpercent = 20;
var bstarth = 0;
var bendh = 64;
var alreadytoasted = false;

function gotToast() {
//alert('gothere');
	banditoextra = document.getElementById('bandito');
	banditoextra.onclick = toastHit;
	bandwindow = document.createElement('div');
	bandwindow.setAttribute('id', 'banditowindow');
	bandwindow.style.height = bstarth+'px';
	banditoextra.appendChild(bandwindow);
	toastiediv = document.createElement('div');
	toastiediv.setAttribute('id', 'toastie');
	toastiediv.setAttribute('class', 'hidden');
	var toasttext = document.createTextNode('Toastie.');
	toastiediv.appendChild(toasttext);
	banditoextra.appendChild(toastiediv);
	alreadytoasted = false;
	toastpercent = 0;
	banditoextra.setAttribute('class', 'shown');
	animateToast();
	
}

function toastHit() {
	if (gamestate=='gameon') {
		playerscore += 1000;
		updateScoreDisplay();
	}
}

function animateToast() {
	
	if (toastpercent <= 100) {
		var nextbh = Math.floor((bendh*toastpercent)/100);//(((bstarty-bendy)*toastpercent)/100)-bendy;
		bandwindow.style.height = nextbh+'px';
		toastpercent += bytoastpercent;
		if (toastpercent >= 60 && alreadytoasted!=true ) { sayToast();  alreadytoasted=true; }
		toasttimer = setTimeout( animateToast, toastspeed );
	} else {
		clearTimeout( toasttimer );
		toasttimer = 'stopped';
		setTimeout(function() { removeToast(); }, 100);
	}
}

function sayToast () {
		toastiediv.setAttribute('class', 'dialog');
}

var toastremovecounter = 0;
var toastremoveinterval = 1;
var toastremovetimer = 'stopped';

function removeToast() {
	if (toastremovecounter <= 10) {
		var nextopacity = fadeAnimCurve( toastremovecounter );
		toastiediv.style.opacity = nextopacity;
		bandwindow.style.opacity = nextopacity;
		toastremovecounter += toastremoveinterval;
		toastremovetimer = setTimeout(removeToast, toastspeed);
	} else {
		clearTimeout( toastremovetimer );
		banditoextra.setAttribute('class', 'hidden');
		banditoextra.innerHTML = '';
		toastremovecounter = 0;
		toastremovetimer = 'stopped';
	}
}


/************** END HAPPY *************************/
function coverBoard() {
	document.getElementById("boardcover").style.display = "block";
}

function uncoverBoard() {
	document.getElementById("boardcover").style.display = "none";
}

/************ Draw Board ******************/
function drawBoard (whichboard) {
	var boarddiv = document.getElementById(whichboard);

	for (var r = 0; r<=9; r++) {
					//alert(r);
		var newrow = document.createElement("div");
		newrow.setAttribute("id", "row"+r);
		for (var c = 0; c<=9; c++) {
			var id = (whichboard=="shotboard") ? "e" : "p";
			id += r;
			id += c;
			
			var newcol = document.createElement("div");
			newcol.setAttribute("id", id);
			//newcol.style.border = "1px solid black";
			newcol.style.position = "absolute";
			newcol.style.height = "32px";
			newcol.style.width = "32px";
			newcol.style.left = (c*32) + "px";
			newcol.setAttribute("class", "blank"); 
			newcol.onclick = imClicked;
			newrow.appendChild(newcol);
			
			
		}
		boarddiv.appendChild(newrow);
	}
	
}

function extractCellCol (id) {
	return parseInt(id.charAt(2));
}

function extractCellRow (id) {
	return parseInt(id.charAt(1));
}

function extractCellBoard (id) {
	return id.charAt(0);
}


/*************** Animate Board Slide ***********/
var gameboard;
var currenttoppos = 0;
var slideboardtimer;
var boardslidespeed = 50/speed;
var playertoppos = -404;
var enemytoppos = 0;
var titletoppos = -310;
var slidedistance = 10;
var issliding = false;
var slidesteps = 8/speed;
	
function slideBoard( towhere ) {
	switch ( towhere ) {
		case "player":
			slidedistance = Math.floor(Math.abs((currenttoppos-playertoppos)/slidesteps));
		break;
		case "enemy":
			slidedistance = Math.floor(Math.abs((currenttoppos-enemytoppos)/slidesteps));

		break;
		case "title":
			slidedistance = Math.floor(Math.abs((currenttoppos-titletoppos)/slidesteps));
		
		break;
		default:
		
	}
	coverBoard();
	slideBoardWork( towhere );
}

function slideBoardWork( towhere ) { 
	gameboard = document.getElementById("gameboard");
	switch (towhere) {
		case "player":
				currenttoppos -= slidedistance;
				if (currenttoppos >= playertoppos) {
					gameboard.style.top = currenttoppos + "px";
						slideboardtimer = setTimeout("slideBoardWork( 'player' )", boardslidespeed);
						issliding = true;

				} else {
					gameboard.style.top = playertoppos + "px";
					clearTimeout(slideboardtimer);
					issliding = false;
					//whosturn = "enemy";
					uncoverBoard();
				}
		break;
		case "enemy":
				currenttoppos += slidedistance;
				if (currenttoppos <= enemytoppos) {
					gameboard.style.top = currenttoppos + "px";
						slideboardtimer = setTimeout("slideBoardWork( 'enemy' )", boardslidespeed);
						issliding = true;

				} else {
					gameboard.style.top = enemytoppos + "px";
					clearTimeout(slideboardtimer);
					issliding = false;
					//whosturn = "player";
					uncoverBoard();
				}
		
		break;
		case "title":
			currenttoppos += (currenttoppos>titletoppos) ? -slidedistance : slidedistance;
				var checkdiff = Math.abs(currenttoppos-titletoppos);
				if (checkdiff > slidedistance+1) {
					gameboard.style.top = currenttoppos + "px";
		//alert ("gothere"+gameboard.style.top);
						slideboardtimer = setTimeout("slideBoardWork( 'title' )", boardslidespeed);
						issliding = true;

				} else {
					gameboard.style.top = titletoppos + "px";
					clearTimeout(slideboardtimer);
					issliding = false;
					//whosturn = "enemy";
					uncoverBoard();
				}
		break;
		default:
		
	}
}





/***********Preload Images***************/
function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

/*function changeImages() {
	if (document.images && (preloadFlag == true)) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}*/

var preloadFlag = false;
function preloadImages() {
	if (document.images) {
		img_bpin = newImage("images/bluepinstripe.jpg");
		img_hitimg = newImage("images/hit.png");
		img_missimg = newImage("images/miss.png");
		img_sea = newImage("images/sea.jpg");
		img_bflogo = newImage("images/battlefleetlogo.gif");
		img_rotateiconimg = newImage("images/rotateicon.png");
		img_checkiconimg = newImage("images/checkicon.png");
		//Ships Images
		img_ach = newImage("ships/aircrafth.gif");
		img_acv = newImage("ships/aircraftv.gif");
		img_bsh = newImage("ships/battleshiph.gif");
		img_bsv = newImage("ships/battleshipv.gif");
		img_dh = newImage("ships/destroyerh.gif");
		img_dv = newImage("ships/destroyerv.gif");
		img_sh = newImage("ships/submarineh.gif");
		img_sv = newImage("ships/submarinev.gif");
		img_ph = newImage("ships/ptboath.gif");
		img_pv = newImage("ships/ptboatv.gif");
		img_pla = newImage("images/letters/pa.gif");
		img_plb = newImage("images/letters/pb.gif");
		img_pld = newImage("images/letters/pd.gif");
		img_pls = newImage("images/letters/ps.gif");
		img_plp = newImage("images/letters/ppt.gif");
		img_ela = newImage("images/letters/ea.gif");
		img_elb = newImage("images/letters/eb.gif");
		img_eld = newImage("images/letters/ed.gif");
		img_els = newImage("images/letters/es.gif");
		img_elp = newImage("images/letters/ept.gif");
		img_x = newImage("images/letters/x.png");
		img_lya = newImage("images/labels/yourammo.gif");
		img_lys = newImage("images/labels/yourships.gif");
		img_lta = newImage("images/labels/theirammo.gif");
		img_lts = newImage("images/labels/theirships.gif");
		img_shot = newImage("images/shoticon.gif");
		img_missle = newImage("animation/missle.png");
		img_exp0 = newImage("animation/explosion0.png");
		img_exp1 = newImage("animation/explosion1.png");
		img_exp2 = newImage("animation/explosion2.png");
		img_rocketjet = newImage("animation/rocketjet.png");
		img_spl0 = newImage("animation/splash0.png");
		img_spl1 = newImage("animation/splash1.png");
		setTimeout ( function() { preloadFlag = true; }, 2500);
	}
}

/********************** Missle Animation Code ************************/
var missletimer = "stopped";
var currenty = 0;
var misslepercent = 0;
var bypercent = 10;
var missleframerate = 60/speed; //milliseconds
var missleanimationdiv;
var callbackfunction;


function shootMissle ( gridlocation, ending, callback ) {
//alert('gothere');
	coverBoard();
	callbackfunction = callback;
	var targetx = (extractCellCol( gridlocation )*32)+16;
	var targety = (extractCellRow( gridlocation )*32)+16;
	missleanimationdiv = document.getElementById('missleanimation');
	missleanimationdiv.style.display = 'block';
	animateMissle (targetx, targety, ending);

}

function animateMissle (targetx, targety, ending) {
	var misslediv = document.getElementById('missle');
	var rocketjet = document.getElementById('rocketjet');
	if (misslepercent <= 100) {
		misslediv.style.display = 'block';
		rocketjet.style.display = 'block';
		rocketjet.style.opacity = (Math.random()*.95)+0.5;
 		var nexty = Math.floor(320*(misslepercent/100))-(320-targety);
		missleanimationdiv.style.top = nexty+'px';
		missleanimationdiv.style.left = targetx+'px';
		misslepercent += bypercent;
		missletimer = setTimeout(function () { animateMissle(targetx, targety, ending); }, missleframerate);
	} else {
		misslepercent = 0;
		clearTimeout( missletimer );
		misslediv.style.display = 'none';
		rocketjet.style.display = 'none';
		switch (ending) {
			case 'hit':
				animateExplosion(); 
			break;
			case 'miss':
				animateSplash(); 
			break;
			default:
				animateSplash(); 
		}
	}
}

var explosioncount = 0;
var explosionframes = ['explosion0', 'explosion1', 'explosion2' ];
var explosionmills = [50, 200, 150]; //milliseconds per frame

var nextframe;
var previousframe;

function animateExplosion() {
	if (explosioncount < explosionframes.length) {
		if (previousframe!=null) { previousframe.style.display = 'none'; }
		nextframe = document.getElementById(explosionframes[explosioncount]);
		nextframe.style.display = 'block';
		missletimer = setTimeout ( animateExplosion, explosionmills[explosioncount] );
		previousframe = nextframe;
		explosioncount++;
	} else {
		previousframe.style.display = 'none'; 
		clearTimeout(missletimer);
		explosioncount = 0;
		missletimer = "stopped";
		uncoverBoard();
		callbackfunction();
	}
	
}

var splashcount = 0;
var splashframes = ['splash0', 'splash1'];
var splashmills = [150, 100];

function animateSplash() {
	if (splashcount < splashframes.length) {
		if (previousframe!=null) { previousframe.style.display = 'none'; }
		nextframe = document.getElementById(splashframes[splashcount]);
		nextframe.style.display = 'block';
		missletimer = setTimeout ( animateSplash, splashmills[splashcount] );
		previousframe = nextframe;
		splashcount++;
	} else {
		previousframe.style.display = 'none'; 
		clearTimeout(missletimer);
		splashcount = 0;
		missletimer = "stopped";
		uncoverBoard();
		callbackfunction();
	}
	
}

/********************* End Missle Code ******************************/

window.onload = function() {

var loadboxinfo = document.getElementById("loadinfo");
loadboxinfo.innerHTML = "<p>"+GAMETIP+"</p><p>"+GAMENAME+" for "+POSTSCRIPT+"<br/>Version: "+VERSION+"</p><p>Created By "+CREATOR+"<br/>"+LICENSE+"</p><p>"+COPYRIGHT+"</p>";
document.getElementById("startversion").innerHTML = VERSION;
showLoading();

Initialize();

};
