//------------------------------------------------------------------------------
// Battleship.js
//------------------------------------------------------------------------------
// BATTLESHIP by Mark Carson
// Copyright 2003-2004 Mark L. Carson, All rights reserved.
// Version 1.0  10-JAN-2004
//------------------------------------------------------------------------------
//  Usage: Intended for draggable images.
//
//  Supported Browsers:
//    MSIE   5/6 : Drag and Drop
//    Netscape 6 : Drag and Drop
//    Netscape 4 : No drag and drop
//    Mozilla 5  : Drag and Drop
//    Opera 6    : No drag and drop
//    Opera 7    : Drag and Drop
//------------------------------------------------------------------------------

  var mode = "setup";  // "setup", "ready" , "play", "done"
  var redSetup = false;

  var blueShipsOnBoard = 0; 
  var blueShots = 5;

  var redShipsOnBoard = 0; 
  var redShots = 5;

  var currentShots = new Array(5);

  var helpCounter = 0;

//------------------------------------------------------------------------------

  var minMove = 1  // minimum nudge value
  var el = null

  var boardCellsX      = 15;
  var boardCellsY      = 10;  
  var boardCellWidth   = 30;
  var boardCellHeight  = 30;
  var boardWidth       = (boardCellsX * boardCellWidth) + 1;
  var boardHeight      = (boardCellsY * boardCellHeight) + 1;
  var boardLeft        = 130;
  var boardTop         = 20;
  var boardTitleHeight = 15;
  var boardRight       = boardLeft + boardWidth;
  var boardBottom      = boardTop + boardHeight;
  var boardSpacing     = 20;
  
  //Private Attributes and Methods
  var oldLeft
  var oldTop
  var newLeft;
  var newTop;
  var engageLeft
  var engageTop
  var linkHref
  var linkElement
  var validMove = false

  var blueShipGrid = new Array(boardCellsX * boardCellsY);
  wipeGrid(blueShipGrid);

  var redShipGrid  = new Array(boardCellsX * boardCellsY);
  wipeGrid(redShipGrid);

  var blueShotGrid = new Array(boardCellsX * boardCellsY);
  wipeGrid(blueShotGrid);

  var redShotGrid  = new Array(boardCellsX * boardCellsY);
  wipeGrid(redShotGrid);

  var bluePrevShotGrid = new Array(boardCellsX * boardCellsY);
  wipeGrid(bluePrevShotGrid);
  
//------------------------------------------------------------------------------

  function validShot(board, cell) {
    var targetGrid;
    if (board == "red") 
	  targetGrid = redShotGrid;
	else
	  targetGrid = blueShotGrid;  
    if (!targetGrid[cell] || targetGrid[cell] == 0) {
	  targetGrid[cell] = 1;
      var row = Math.floor(cell / boardCellsX);
	  var col = cell % boardCellsX;
      var id = board + "-r_" + row + "-c_" + col;
      //alert("validShot()\nboard=" + board + "\ncell=" + cell + "\nid=" + id);
      var obj = document.getElementById(id);
      if (obj) {
        if (board == "blue") {
          //alert("blueShipGrid[" + cell + "]=" + blueShipGrid[cell]);
          if (blueShipGrid[cell] && blueShipGrid[cell] != 0) {
            //--- Hit in Blue territory ---
	        obj.bgColor = "#ff0000";
            //alert("validShot()\nHit\nPre-strike blueShipGrid[" + cell + "]=" + blueShipGrid[cell]);
			blueShipGrid[cell] = 0;
		  }	
          else {
            //--- Miss in Blue territory ---
	        obj.bgColor = "#c0c0c0";
            //alert("validShot()\nMissed\nblueShipGrid[" + cell + "]=" + blueShipGrid[cell]);
		  }	
          showGrid(blueShipGrid, "divBlueShipGrid");
          //alert("validShot()\nAfter showGrid()");
        }
        else { //--- red board ---
          redShotGrid[cell] = 1;
          //alert("redShotGrid[" + cell + "]=" + redShotGrid[cell]);
          if (redShipGrid[cell] && redShipGrid[cell] != 0) {
            //--- Hit in Red territory ---
	        obj.bgColor = "#ff0000";
			//redShipGrid[cell] = 0;  //--- Let recolorRedBoard do this ---
		  }	
          else {
            //--- Miss in Red territory ---
	        obj.bgColor = "silver";
		  }	
          showGrid(redShipGrid, "divRedShipGrid");
          //alert("redShipGrid[" + cell + "]=" + redShipGrid[cell]);
        }
	  }	
      //alert("validShot() returning TRUE");
      return true;
	}  
    else
	  return false;  
  }

//------------------------------------------------------------------------------

  function randomIncoming(board) {
    var attacker;
    var shotGrid;
    if (board == "blue") {
	  attacker = "red";
      shotGrid = blueShotGrid;
      redShots  = getShipsOnBoard("red"); 
	}  
	else {
	  attacker = "blue";
      shotGrid = redShotGrid;
      blueShots = getShipsOnBoard("blue");
	}    
    var remainingShots = getShipsOnBoard(attacker); 
    var attempts = 0;
    while(remainingShots) {
      var cell = Math.round(boardCellsX * boardCellsY * Math.random());
      if (validShot(board, cell)) {
        remainingShots--;
		attempts = 0;
        //alert("randomIncoming()\nvalidShot\nRemaining Shots=" +  remainingShots + "\nIncoming hit cell " + cell);	
	  }	
	  else {
	    //alert("Already hit that square (" + cell + ")");
        attempts++;
		if (attempts > 10) { // walk the grid and hit the first open cell
	      //alert("Max attempts exceeded - walking the grid");
          for (cell = 0; cell < shotGrid.length && attempts; cell++) {
            if (validShot(board, cell)) {
              remainingShots--;
              attempts = 0;
	        }	
		  }	
		}
	  }		
	}
    redShots  = getShipsOnBoard("red"); 
    blueShots = getShipsOnBoard("blue");
    //alert("randomIncoming()\nResetting shot counters\nblueShots=" + blueShots + "\nredShots=" + redShots);
    showMode();
    showGrid(blueShipGrid, "divBlueShipGrid");
    showGrid(redShipGrid,  "divRedShipGrid");
    return true;
  }
  
//------------------------------------------------------------------------------

  var cornerTL = 0;
  var cornerTR = boardCellsX;
  var cornerBL = boardCellsX * (boardCellsY - 1);
  var cornerBR = boardCellsX * boardCellsY - 1;
  var xDir = 1;
  var yDir = 1;
  var lastShot = -1;
  
//------------------------------------------------------------------------------

  function smartShot(board, numberShots) {
    var remainingShots = numberShots;
    //alert("smartShot()\nremainingShots=" + remainingShots);
    var row;
	var col;
	var cellStr;
	var numberCells = boardCellsX * boardCellsY;
    //alert("smartShot()\nnumberCells=" + numberCells);
    for (var cell = 0 ; cell < numberCells; cell++) {
      if (remainingShots <= 0) {
        //alert("smartShot()\nOut of ammo");
	    return 0;
	  }	
      row = Math.floor(cell / boardCellsX);
	  col = cell % boardCellsX;
      cellStr = board + "-r_" + row + "-c_" + col;
      //alert("smartShot()\ncell=" + cell + "\nrow=" + row + "\ncol=" + col + "\ncellStr-" + cellStr);
      var cellObj = document.getElementById(cellStr);
      if (cellObj && cellObj.bgColor && cellObj.bgColor == "#ff0000") { // red (ship hit in this cell) 
        //alert("smartShot()\nHit: cell=" + cell + "\nrow=" + row + "\ncol=" + col + "\nTrying surrounding cells");
        if (cell > 0) {
          if (validShot(board, cell - 1)) 
            remainingShots--;
		}
        if (cell < numberCells - 1) {
          if (validShot(board, cell + 1)) 
            remainingShots--;
		}
        if (row > 0) {
          if (validShot(board, cell - boardCellsX)) 
            remainingShots--;
		}
        if (row < boardCellsY - 1) {
          if (validShot(board, cell + boardCellsX)) 
            remainingShots--;
		}
      }
      if (!cellObj) {  
        ; //alert("smartShot()\ncellObj INVALID\ncellStr=" + cellStr + "\nrow=" + row + "\ncol=" + col);
	  }
	  //remainingShots--;	
	} 
	return remainingShots;   
  }
  
//------------------------------------------------------------------------------

  function pattern_1_Incoming(board) {
    var attacker;
    var shotGrid;
    var cell;
    var row;
	var col;
    if (board == "blue") {
	  attacker = "red";
      shotGrid = blueShotGrid;
      redShots  = getShipsOnBoard("red"); 
	}  
	else {
	  attacker = "blue";
      shotGrid = redShotGrid;
      blueShots = getShipsOnBoard("blue");
	}    
    var remainingShots = smartShot(board, getShipsOnBoard(attacker));
    //alert("After smartShot()\nremainingShots=" + remainingShots);
    var attempts = 0;
    var maxAttempts = Math.ceil(boardCellsX * boardCellsY) ;  // / 2;
    while(remainingShots) {
      //if (attempts >= maxAttempts - 5)
	  //  alert("pattern_1_Incoming()\nmaxAttempts=" + maxAttempts + "\nattempts=" + attempts + "\nremainingShots=" + remainingShots + "\nlastShot=" + lastShot);
      if (attempts < maxAttempts) {

        if (lastShot < 0) {
          cell = Math.round(boardCellsX * boardCellsY * Math.random());
		  col = cell % boardCellsX;
          row = Math.floor(cell / boardCellsX);
        }
	    else {
          cell = lastShot;	  
		  col = cell % boardCellsX;
          row = Math.floor(cell / boardCellsX);
          if (cell == cornerTL) 
            cell = cell + 2;
		  else if (cell == cornerTR) 
            cell = cell - 2;
		  else if (cell == cornerBL) 
            cell = cell + 2;
		  else if (cell == cornerBR) 
            cell = cell - 2;
		  else {
            if (row == 0) 
		      yDir = 1;
            if (row == boardCellsY - 1) 
		      yDir = -1;
            if (col == 0) 
		      xDir = 1;
            if (col == boardCellsX - 1) 
		      xDir = -1;
 	        cell += xDir + (yDir * boardCellsX);
          }
	    }      
        if (attempts == 0)
          firstCellTried = cell;	    
        else {
          if (cell == firstCellTried) { // jump to other diagonal set of squares
            //alert("pattern_1_Incoming()\ncell == firstCellTried\Switching diagonals\nlastShot=" +  lastShot + "\ncol=" + col + "\nrow=" + row + "\nxDir=" + xDir + "\nyDir=" + yDir + "\ncell=" + cell + "\nShots=" +  remainingShots + "\nAttempts= " + attempts);	
            if (cell < (boardCellsX * boardCellsY) - 1)
		      cell++;
		    else
		      cell--;
	      }			
        }
	    attempts++;
        //alert("pattern_1_Incoming()\nlastShot=" +  lastShot + "\ncol=" + col + "\nrow=" + row + "\nxDir=" + xDir + "\nyDir=" + yDir + "\ncell=" + cell + "\nShots=" +  remainingShots + "\nAttempts= " + attempts);
      }
	  else { //-- At maxAttempts, walk the grid and shoot on each square, try validShot() etc. --- 
        if (attempts == maxAttempts)
		  cell = 0;
		else
		  cell++;  	  
        if (cell >= boardCellsX * boardCellsY) {
		  remainingShots = 0;
		  break;
		}  
	    attempts++;
	  }			
      if (validShot(board, cell)) {
        //if (attempts > 70)
        //  alert("pattern_1_Incoming()\nvalidShot\nlastShot=" +  lastShot + "\ncol=" + col + "\nrow=" + row + "\nxDir=" + xDir + "\nyDir=" + yDir + "\ncell=" + cell + "\nShots=" +  remainingShots + "\nAttempts= " + attempts);	
        remainingShots--;
        attempts = 0;
        //alert("pattern_1_Incoming()\nvalidShot\nRemaining Shots=" +  remainingShots + "\nIncoming hit cell " + cell);	
	  }	
      lastShot = cell;
	}
	
    redShots  = getShipsOnBoard("red"); 
    blueShots = getShipsOnBoard("blue");
    showMode();
    showGrid(blueShipGrid, "divBlueShipGrid");
    showGrid(redShipGrid,  "divRedShipGrid");
    return true;
  }
  
//------------------------------------------------------------------------------

  function getOpenCells(board) {
    var targetGrid;
    if (board == "red") 
	  targetGrid = redShotGrid;
	else
	  targetGrid = blueShotGrid;  
    var openCells = 0;
    for (var i = 0 ; i < targetGrid.length; i++) {
	  if (!targetGrid[i] || targetGrid[i] == 0)
	    openCells++;
	}
    //if (openCells < 5)
	//  alert("getOpenCells()\nopenCells=" + openCells);
	return openCells;	
  }  
  
//------------------------------------------------------------------------------

  function shot(imgObj) {
    if (mode == "done") {
      alert ("Peace has broken out. Get over it and stop trying to shoot.")
	  return;
	}  
    if (mode == "setup") {
      alert ("Place your Fleet on the board before firing on your enemy.")
	  return;
	}  
    if (mode == "ready") {
	  mode = "play";
    }
	
    var cellStr = "red" + imgObj.id.substring(6);
    //alert("shot()\nimgObj.id=" + imgObj.id + "\ncellStr=" + cellStr);
    var cellObj = document.getElementById(cellStr);
    //alert("shot()\cellObj.id=" + cellObj.id + "\ncellObj.bgColor=" + cellObj.bgColor);
    if (!cellObj.bgColor || 
	   (cellObj.bgColor != "#ff0000" &&   // red (ship sunk in this cell) 
	    cellObj.bgColor != "#ffff00" &&   // yellow (one or more shots struck)
	    cellObj.bgColor != "#c0c0c0")) {  // silver (shot landed in this cell)

      var row = getIdValue(imgObj.id, "-r_", "-") - 0;
      var col = getIdValue(imgObj.id, "-c_", "-") - 0;
      var cell = row * boardCellsX + col;
      //alert("shot()\nrow=" + row + ", col=" + col + ", cell=" + cell);
      if (validShot("red", cell)) {
  	    blueShots--;
	    cellObj.bgColor = "#ffff00"; // yellow
	  }	

      //currentShots[blueShots] = cell;
      var openCells = getOpenCells("red");
	  if (openCells < blueShots)
	    blueShots = openCells;
      if (blueShots <= 0) {
        recolorRedBoard();
	    //randomIncoming("blue");
	    pattern_1_Incoming("blue");
      }		
    }	
    showGrid(blueShipGrid, "divBlueShipGrid");
    showGrid(redShipGrid,  "divRedShipGrid");
    showMode();

    if (getShipsOnBoard("red") < 1) {
	  mode = "done";
      showMode();
      helpDone();
	} 
    if (getShipsOnBoard("blue") < 1) {
	  mode = "done";
      showMode();
      helpDone();
	} 
  }
  
//------------------------------------------------------------------------------

  function recolorRedBoard() {
    //alert("recolorRedBoard()\nredShipGrid.length=" + redShipGrid.length);
    for (var r = 0; r < redShipGrid.length; r++) {
      if (redShotGrid[r] > 0) {
        var row = Math.floor(r / boardCellsX);
	    var col = r % boardCellsX;
        var id = "red-r_" + row + "-c_" + col;
        //alert("recolorRedBoard()\nid=" + id + "\nredShipGrid[r]=" + redShipGrid[r] + "\nredShotGrid[r]=" + redShotGrid[r]);
        var cellObj = document.getElementById(id);
        if (cellObj && cellObj.bgColor == "#ffff00") { // If yellow... 
		  //alert("cellObj.id=" + cellObj.id + "\ncellObj.bgColor=" + cellObj.bgColor + "\nredShipGrid[r]=" + redShipGrid[r]);  
          //cellObj.bgColor = "#00ff00";
       	  if (redShipGrid[r] && redShipGrid[r] != 0) 
			cellObj.bgColor = "#ff0000"; // red
  		  else 
		    cellObj.bgColor = "#c0c0c0"; // silver
        }
        redShipGrid[r] = 0;			
	  }
	}
  }  
  
//------------------------------------------------------------------------------
  
  function randomSetupShip(board, idType, width, height, mask) {
    var shipGrid;
    if (board == "red")
	  shipGrid = redShipGrid;
	else  
	  shipGrid = blueShipGrid;
    var cell;
	var top;
	var left;
	var ok = false;
	var attempt = 0;
	while (!ok && attempt < 10) {
      cell = Math.round(boardCellsX * boardCellsY * Math.random());
      top  = Math.floor(cell / boardCellsX);
	  left = cell % boardCellsX;
	  if (top + height < boardCellsY &&
	      left + width < boardCellsX) {
        //alert("randomShipSetup() OK\nboard=" + board + "\nboardCellsY=" + boardCellsY + "  boardCellsX=" + boardCellsX + "\nidType=" + idType + "\nleft=" + left + "  width=" + width + "\ntop=" + top + "  height=" + height + "\nmask=" + mask + "\nattempt=" + attempt);
        ok = setGrid(shipGrid, left, top, width, height, mask, idType);      
        attempt++;
	    if (attempt >= 10) {
          for (var cell = 0; !ok  || cell < shipGrid.length; cell++) {
            top  = Math.floor(cell / boardCellsX);
	        left = cell % boardCellsX;
	        if (top + height < boardCellsY &&
	            left + width < boardCellsX) {
              ok = setGrid(shipGrid, left, top, width, height, mask, idType);
			}        
          }		
		} 
	  }
	  else {
        ; //alert("randomShipSetup() INVALID\nboard=" + board + "\nboardCellsY=" + boardCellsY + "  boardCellsX=" + boardCellsX + "\nidType=" + idType + "\nleft=" + left + "  width=" + width + "\ntop=" + top + "  height=" + height + "\nmask=" + mask + "\nattempt=" + attempt);
      }	  
    }	
  }
  
//------------------------------------------------------------------------------
  
  function randomSetup(board) {
    //--- Battleship ---
    if (Math.random() <= 0.5) 
      randomSetupShip(board, "b", 5, 1,"11111");
    else	  
      randomSetupShip(board, "b", 1, 5,"11111");

    //--- Cruiser ---
    if (Math.random() <= 0.5) 
      randomSetupShip(board, "c", 4, 1,"1111");
    else
      randomSetupShip(board, "c", 1, 4,"1111");

    //--- Destroyer ---
    if (Math.random() <= 0.5) 
      randomSetupShip(board, "d", 3, 1,"111");
	else  
      randomSetupShip(board, "d", 1, 3,"111");

    //--- Frigate ---
    if (Math.random() <= 0.5) 
      randomSetupShip(board, "f", 2, 1,"11");
    else
      randomSetupShip(board, "f", 1, 2,"11");

    //--- Patrol Boat ---
    randomSetupShip(board, "p", 1, 1,"1");

    showGrid(redShipGrid, "divRedShipGrid");
  }
  
//------------------------------------------------------------------------------
  
  function help() {
    helpCounter++;
    if (mode == "setup")
	  helpStart();
    if (mode == "ready")
      helpReady();
    if (mode == "play")
      helpPlay();
    if (mode == "done")
      helpDone();
  }
  
//------------------------------------------------------------------------------

  function helpStart() {
    var str = "Welcome to BATTLESHIP. Copyright 2003-2004 by Mark Carson, all rights reserved.\n\n";
    str += "Drag and drop one ship of each type (either horizontal or vertical orientation)\n"
    str += "into your territory. You can reposition ships by dragging them around on the board\n";
    str += "or you can return them to the harbor by dragging them off Your Territory board.\n";
    str += "After all of your ships are positioned, you may commence firing on the enemy by\n";
    str += "clicking on squares in the Enemy Territory board.\n";
    alert (str);
  }
  
//------------------------------------------------------------------------------

  function helpReady() {
    var str = "You have positioned all of your ships into your territory.\n";
    str += "You may now commence firing on your enemy by clicking on squares in the Enemy\n";
    str += "Territory board, or you may reposition your ships before taking your first shot.\n";
    alert (str);
  }

//------------------------------------------------------------------------------

  function helpPlay() {
    var str = "Click on an open square in Enemy Territory.\n\n";
    str += "You may click as many times as you have shots.\n";
    str += "Each of your ships (which is not sunk) has a shot.\n";
    str += "When you have fired all of your shots, your enemy takes a turn\n";
    str += "and also gets a shot for each ship he/she has.\n";
    str += "Keep playing until one of you sinks all of the other\'s ships.\n";
    alert (str);
  }
  
//------------------------------------------------------------------------------

  function helpDone() {
    var str = "Game over!";
    if (getShipsOnBoard("blue") < 1) 
	  str = "You lost the battle!\nHow could you have allowed every single of your ships to get sunk?\n\n";
    if (getShipsOnBoard("red") < 1) 
	  str = "Congratulations, You have won the battle!\n\n";
	str += "Want to play again?";  
    var answer = confirm(str);
	if (answer == true)
	  document.location.href = document.location.href; // cause a page reload
  }
  
//------------------------------------------------------------------------------

  function getShipsOnBoard(board) {
    var shipGrid;
    if (board == "red") {
      //return 5; // temp
      shipGrid = redShipGrid;
	}        
	else
      shipGrid = blueShipGrid;      
    var shipTypes = ""; 
	var pos;
	var chr;
    //alert("getShipsOnBoard(" + board + ")\nshipGrid.length=" + shipGrid.length);
    for (cell = 0 ; cell < shipGrid.length; cell++) {
      if (!shipGrid[cell] || shipGrid[cell] == 0)
	    continue;
      //alert("getShipsOnBoard(" + board + ")\nshipGrid[" + cell + "]=" + shipGrid[cell]);
      pos = shipTypes.indexOf(shipGrid[cell]);
	  if (pos < 0)
	    shipTypes += shipGrid[cell];
	}
    //alert("getShipsOnBoard(" + board + ")\nshipTypes=" + shipTypes);

    if (mode == "play" || mode == "done") {
      var allShipTypes = "bcdfp";
      for (var i = 0; i < allShipTypes.length; i++) {
  	    if (shipTypes.indexOf(allShipTypes.charAt(i)) < 0) {
  	      var obj = document.getElementById("scoreboard-" + board + "-" + allShipTypes.charAt(i));
	  	  if (obj) {
		    obj.src = obj.src.substring(0,obj.src.length - 8) + "sunk.gif";
          }
	    }		
	  }  
	}

	return shipTypes.length;	
  }

//------------------------------------------------------------------------------

  function showSimilar(id) {
	for (var i = 0 ; i < document.images.length; i++) {
      var currentID = document.images[i].id;
      if (currentID && 
	      currentID.substring(0,14) == id.substring(0, 14) &&
		  currentID != id) {
	    //alert ("Show this one!\ni=" + i + "\nid=" + id + "\ncurrentID=" + currentID);
        document.images[i].style.visibility = 'visible';
	  }
    }
  }

//------------------------------------------------------------------------------

  function hideSimilar(id) {
	for (var i = 0 ; i < document.images.length; i++) {
      var currentID = document.images[i].id;
      if (currentID && 
	      currentID.substring(0,14) == id.substring(0, 14) &&
		  currentID != id) {
	    //alert ("Hide this one!\ni=" + i + "\nid=" + id + "\ncurrentID=" + currentID);
        document.images[i].style.visibility = 'hidden';
	  }
    }
  }

//------------------------------------------------------------------------------

  function showMode() {
    var strBlue;
    var strRed;
    //var modeObj = document.getElementById("divMode");
    //if (modeObj)
    //  modeObj.innerHTML = "&nbsp; Mode=" + mode + "&nbsp;";
    var blueStatus = document.getElementById("blueStatus");
    var tableRedStatus  = document.getElementById("table-redStatus");
    var redStatus  = document.getElementById("redStatus");
    var blueHarbor = document.getElementById("blueHarbor");
    var redHarbor  = document.getElementById("redHarbor");
    if (blueStatus && redStatus) {
      //alert("showMode(): mode=" + mode);
	  if (mode == "setup") {
        /*
        var obj = document.getElementById("divred"); 
        if (obj)
		  obj.style.visibility = "hidden";
        obj = document.getElementById("tablered"); 
        if (obj)
		  obj.style.visibility = "hidden";
        */
        strBlue =  "Deploy your forces!<hr>";
		strBlue += "Ships in position: " + getShipsOnBoard("blue");
        blueStatus.innerHTML = strBlue;
        tableRedStatus.style.visibility = "hidden";
        redStatus.style.visibility = "hidden";
        redHarbor.style.visibility = "hidden";
        scoreboardVisibility("hidden");
      }
	  if (mode == "ready") {
        var obj = document.getElementById("divred"); 
        if (obj)
		  obj.style.visibility = "visible";
        obj = document.getElementById("tablered"); 
        if (obj)
		  obj.style.visibility = "visible";
        strBlue =  "All ships in position!<hr>";
		strBlue += "Commence firing into Enemy Territory";
		strBlue += "<br>or reposition your ships before taking a shot.";
        blueStatus.innerHTML = strBlue;
        tableRedStatus.style.visibility = "visible";
        redStatus.style.visibility = "visible";
        redHarbor.style.visibility = "visible";
        scoreboardVisibility("visible");
        helpReady();
      }
	  if (mode == "play") {
        var blueShips = getShipsOnBoard("blue");
        strBlue =  "You may fire when ready!<hr>";
	    strBlue += "Shots remaining: " + blueShots + "<hr>";
        //alert("showMode()\nblueShots=" + blueShots);         
	    strBlue += "You have " + blueShips + " ships<hr>";
        strBlue += "Total incoming: " + (blueShotGrid.length - getOpenCells("blue")) + "<br>";
        blueStatus.innerHTML = strBlue;
	
        var redShips = getShipsOnBoard("red");
	    strRed =  "Enemy Shots per volley: " + redShips + "<hr>";
        strRed += "The Enemy has " + redShips + " ships<hr>";
        strRed += "Total outgoing: " + (redShotGrid.length - getOpenCells("red"))+ "<br>";
        tableRedStatus.style.visibility = "visible";
        redStatus.style.visibility = "visible";
        redStatus.innerHTML = strRed;
        redHarbor.style.visibility = "visible";
      }
	  if (mode == "done") {
        if (getShipsOnBoard("blue") < 1) 
          strBlue =  "You lost!<hr>";
		else  
          strBlue =  "You won!<hr>";
        strBlue += "Total incoming: " + (blueShotGrid.length - getOpenCells("blue")) + "<br>";
        blueStatus.innerHTML = strBlue;
	
        if (getShipsOnBoard("red") < 1)
          strRed =  "The enemy has lost!<hr>";
		else  
          strRed =  "The enemy has won!<hr>";
        strRed += "Total outgoing: " + (redShotGrid.length - getOpenCells("red"))+ "<br>";
        redStatus.innerHTML = strRed;
      }
	}  
    else
      ; //alert("showMode(): blueStatus or redStatus is invalid");
  }

//------------------------------------------------------------------------------

  function wipeGrid(grid) {
    for (var i = 0 ; i < boardCellsX * boardCellsY; i++)
      grid[i] = 0;
  }
  
//------------------------------------------------------------------------------

  function getGridX(left) {
    if (left < boardLeft || left > boardRight) 
      return -1;
    return (left - boardLeft) / boardCellWidth;
  }

//------------------------------------------------------------------------------

  function getGridY(top) {
    if (top < boardTop || top > boardBottom) 
      return -1;
    return (top  - boardTop) / boardCellHeight;
  }

//------------------------------------------------------------------------------

  function getGrid(left, top) {
    var x = getGridX(left);
    var y = getGridY(top);
    if (x < 0 || y < 0) 
      return -1;
    else
      return x + (y * boardCellsX);
  }    

//------------------------------------------------------------------------------

  function setGrid(grid, left, top, width, height, mask, value) {
    //alert("setGrid()\nleft=" + left + "\ntop=" + top + "\nwidth=" + width + " \nheight=" + height + "\nmask=" + mask);    
    if (!mask)
	  return;
    var pos;
    var col = new Number(left);   
    var row = new Number(top);
    var right  = col + new Number(width);
    var bottom = row + new Number(height);
    //--- Range test ---
    if (right  > boardCellsX ||
        bottom > boardCellsY) {
      //alert("setGrid()\nOUT OF RANGE\n\nright=" + right+ "\nbottom=" + bottom +"\nwidth=" + width +"\nheight=" + height + "\ncol=" + col + "\nrow=" + row + "\nboardCellsX=" + boardCellsX + "\nboardCellsY=" + boardCellsY);    
	  return false;	
    }
    else {
      ; //alert("setGrid()\nIN RANGE\n\nright=" + right+ "\nbottom=" + bottom +"\nwidth=" + width +"\nheight=" + height + "\ncol=" + col + "\nrow=" + row + "\nboardCellsX=" + boardCellsX + "\nboardCellsY=" + boardCellsY);    
    }	  

    //--- Test pass, look for overlaps ---
    for (var i = 0; i < mask.length; i++) {
      if (i > 0 && i % width == 0) { 
        row++;
		col = left;
      }		
	  else 
	    col = left + i;	
      pos = boardCellsX * row + col;
      if (mask.charAt(i) == '1') { 
        //alert("setGrid(..." + left + "," + top + "...) grid[" + pos + "]=" + grid[pos]);    
        if (grid[pos] && grid[pos] != 0)
          return false;
	  }	
    }
    //--- Set value pass ---
    row = top;
    for (var i = 0; i < mask.length; i++) {
      if (i > 0 && i % width == 0) { 
        row++;
		col = left;
      }		
	  else 
	    col = left + i;	
      pos = boardCellsX * row + col;
      //alert("setGrid()\nwidth=" + width +"\nheight=" + height + "\ncol=" + col + "\nrow=" + row + "\ngrid[" + pos + "]=" + grid[pos]);    
      if (mask.charAt(i) == '1') { 
        grid[pos] = value;
	  }	
    }
    return true;
  }
  
//------------------------------------------------------------------------------

  function clearGrid(grid, x, y, width, height, mask) {
    var i = 0;
    for (var row = 0; row < height; row++) {
      var offsetY = (row + y) * boardCellsX;
      for (var col = 0; col < width; col++) {
        var offsetX = (col + x);
        pos = offsetX + offsetY;
        if (mask && mask.charAt(i) == '1') 
          grid[pos]--;    
        if (grid[pos] < 0)
          grid[pos] = 0;
        i++;  
      }
    }         
  }
  
//------------------------------------------------------------------------------

   function radar (on) {
     //alert("radar(" + on + ")");
     var scope = document.getElementById("divRedShipGrid");
     if (!scope)
	   return;
     if (on && helpCounter >= 3)
	   scope.style.visibility = "visible";
     else	   
	   scope.style.visibility = "hidden";
   }

//------------------------------------------------------------------------------

  function showGrid(grid, divID) {
    //alert("showGrid()\ndivID=" + divID);
    var divGrid = document.getElementById(divID);
    if (!divGrid) {
      //alert("showGrid()\nInvalid divID (" + divID + ")");
      return;
	}  

    //alert("showGrid()\nValid divID (" + divID + ")");
    var display = "<table border=1 cellpadding=0 cellspacing=0>";
    var pos;
    var chr;
    for (var row = 0; row < boardCellsY; row++) {
      display += "<tr>";
      for (var col = 0; col < boardCellsX; col++) { 
        pos = row * boardCellsX + col;
        //if (grid[pos] > 0)
		//  alert("grid[" + pos + "]=" + grid[pos]); 
        if (!grid[pos]       || 
		    grid[pos] == 0   || 
		    grid[pos] == " " || 
			grid[pos] == "")
		  chr = "&nbsp;";
		else
		  chr = grid[pos];  
        display += "<td>" + chr + "<\/td>";
	  }	
      display += "<\/tr>";
    }        
    display += "<\/table>";
    divGrid.innerHTML = display;    
  }
  
//------------------------------------------------------------------------------

  function removeParams(url) {
    var target = url
    var urlArray = url.split("?")
    if (urlArray.length > 1) {
      target = urlArray[0]
      var paramArray = urlArray[1].split("&")
      var first = true
      var i
      for (i = 0 ; i < paramArray.length; i++) {
        if (paramArray[i].substring (0, 7) != "deltaX=" &&
            paramArray[i].substring (0, 7) != "deltaY=") {
          if (first) {
            target = target + "?" + paramArray[i]
            first = false
          } // end if first param
          else  
            target = target + "&" + paramArray[i]
        } // end if not deltaX or deltaY param      
      } // end for
      //--- Guards against '??'
      var qm = target.indexOf("?")
      if (qm >= 0) {
        //target = target + "&QuestionMark=" + qm
        if (qm == target.length - 1) {
          //target = target + "&TrailingQuestionMark=" + qm
          target = target.substring(0, qm - 1)
        }  
        else {  
          //target = target + "&EmbeddedQuestionMark=" + qm
        }
      } // end if question mark found
    } // end if urlArray > 1
    return target
  } // end function

//------------------------------------------------------------------------------

  function getIdValue(id, attr, term) {
    var value = "";
    var temp;
    var iStart;
	var iEnd;
    var iStart = id.indexOf(attr);
	if (iStart >= 0) {
      temp = id.substring(iStart + attr.length);	  
      iEnd = temp.indexOf(term);
	  if (iEnd >= 0)
	    value = temp.substring(0,iEnd);
      else
	    value = temp;
	}			
    //alert("getIdValue(" + id + "," + attr + "," + term + ")=" + value);
    return value;  
  }  

//------------------------------------------------------------------------------

  var idMask;
  var idTop;
  var idLeft;
  var idWidth;
  var idHeight; 
  var idType;
  
  function decodeID (id) {
    idMask   = getIdValue(id, "-m_", "-");
    idTop    = getIdValue(id, "-t_", "-");
    idLeft   = getIdValue(id, "-l_", "-");
    idWidth  = getIdValue(id, "-w_", "-");
    idHeight = getIdValue(id, "-h_", "-");
    idType   = getIdValue(id, "-ship_", "-");
  }

//------------------------------------------------------------------------------

  var DRAG_begindrag = function(e) {

    if (mode == "ready") {
	  mode = "setup";
      showMode();
    }
    if (mode != "setup" && mode != "ready") {
	  alert ("You are not allowed to move your ships once firing has commenced.");
      return;	  
    }  

    if (el.DRAG_dragging == true) {
	  //alert("Already in drag mode"); 
      return false
	}  
    if (!el.nodeName || !el.id || !el.style)
      return false
    decodeID (el.id);
    var nodeName = el.nodeName
    var id = el.id.substring(nodeName.length)
    var strOldLeft = el.style.left
    var strOldTop  = el.style.top
    oldLeft = strOldLeft.substring(0, strOldLeft.length-2) - 0
    oldTop  = strOldTop.substring (0, strOldTop.length-2)  - 0
    //alert("id=" + id + "<br>oldLeft=" + oldLeft + "<br>oldTop=" + oldTop);
    //alert("Object=" + id);

    var gridPos = getGrid(oldLeft, oldTop);
    //alert("getGrid()=" + gridPos);
    if (gridPos >= 0) {
      //--- Currently within target area ---
      var width  = idWidth;
      var height = idHeight;
      clearGrid(blueShipGrid, getGridX(oldLeft), getGridY(oldTop), width, height, idMask);      
    }      
	
    //engageLeft = cs.isNS() ? e.pageX : event.x
    //engageTop  = cs.isNS() ? e.pageY : event.y
    engageLeft = cs.isIE() ? event.x : el.x
    engageTop  = cs.isIE() ? event.y : el.y
    var btn = cs.isNS() ? e.button : event.button
    if (btn <= 1) {
      document.onmousemove = DRAG_drag
      document.onmouseup   = DRAG_enddrag
      el.DRAG_dragging = true
      el.style.zIndex += 1000;
      //el.originalLeft = oldLeft;
      //el.originalTop  = oldTop;
    } // end if btn <= 1
    if (nodeName == "A") {  // HTML <A> tag
      linkElement = el
      linkHref = removeParams(el.href)          
    } // end if anchor tag
    else { // Not an HTML <A> tag, look an <A> tag with the same ID suffix
      var anchorElement = document.getElementById("A" + id)
      if (anchorElement) {
        linkElement = anchorElement
        linkHref = removeParams(anchorElement.href)          
      } // end if anchorElement  
    } // end else
    return true
  }
//------------------------------------------------------------------------------

  var DRAG_drag = function(e) {
    if (el.DRAG_dragging == true) {
      var evtX = cs.isNS() ? e.pageX : event.x
      var evtY = cs.isNS() ? e.pageY : event.y
      //var evtX = cs.isIE() ? event.x : el.x
      //var evtY = cs.isIE() ? event.y : el.y
      var deltaX  = evtX - engageLeft
      var deltaY  = evtY - engageTop
      //alert("evtX=" + evtX + "<br>evtY=" + evtY + "<br>deltaX=" + deltaX + "<br>deltaY=" + deltaY);
      //alert("X=" + evtX + "<br>Y=" + evtY + "<br>zIndex=" + el.style.zIndex);
      newLeft = oldLeft + deltaX
      newTop  = oldTop  + deltaY
      el.style.left = newLeft + "px"
      el.style.top  = newTop  + "px"

      var msg = " oldLeft=" + oldLeft + 
              "\n oldTop="  + oldTop +
              "\n newLeft=" + newLeft +
              "\n newTop="  + newTop;
      
      return false;
    } // end if el.DRAG_dragging
    else
      return true
  }

//------------------------------------------------------------------------------

  var DRAG_enddrag = function(dragEl, e) {
    //var evtX = cs.isNS() ? e.pageX : event.x
    //var evtY = cs.isNS() ? e.pageY : event.y
    var evtX = cs.isIE() ? event.x : dragEl.x
    var evtY = cs.isIE() ? event.y : dragEl.y
    var deltaX = evtX - engageLeft
    var deltaY = evtY - engageTop
    var nodeName = el.nodeName;

    decodeID (el.id);

    //alert("DRAG_enddrag: " + el.id);

    el.style.zIndex -= 1000; 
    
    if (newTop > boardBottom ||
        newLeft > boardRight) {
      el.style.left = idLeft + "px"
      el.style.top  = idTop  + "px"
      clearGrid(blueShipGrid, getGridX(oldLeft), getGridY(oldTop), idWidth, idHeight, idMask);      
      showSimilar(el.id);
      //alert(el.id + " was returned to the palette\nidLeft=" + idLeft + "\nidTop=" + idTop);
      showGrid(blueShipGrid, "divBlueShipGrid");
      el.DRAG_dragging = false
      el = null
      document.onmousemove = null
      document.onmouseup = null

      if (mode == "setup" && getShipsOnBoard("blue") == 5) {
        mode = "ready"; 
      }
      showMode();
	  
      return true
    }    
        
    //--- Snap To Grid ---------------------------------
    var offLeft = (newLeft - boardLeft) % boardCellWidth;
    if (offLeft > boardCellWidth / 2)
      newLeft = newLeft + (boardCellWidth - offLeft);
    else  
      newLeft = newLeft - offLeft;

    var offTop = (newTop - boardTop) % boardCellHeight;
    if (offTop > boardCellHeight / 2)
      newTop = newTop + (boardCellHeight - offTop);
    else  
      newTop = newTop - offTop;
    //alert("DRAG_enddrag: " + el.id + "\nAfter Snap To Grid");
    //--- end Snap To Grid -----------------------------
    
    //--- Valid drop coordinate check ---
    if (newLeft < boardLeft ||
        newTop  < boardTop  ||
        newLeft + el.width > boardRight ||
        newTop + el.height > boardBottom) 
      validMove = false;
    else 
      validMove = true;
    //alert ("enddrag()\nAfter valid drop coordinate check\nvalidMove=" + validMove);
       
    if (validMove) {
      //alert ("enddrag() validMove");
      hideSimilar(el.id);
      el.style.left = newLeft + "px"
      el.style.top  = newTop  + "px"
      //alert("DRAG_enddrag()\nid=" + el.id + "\nnewLeft=" + newLeft + "\nnewTop=" + newTop + "\nleft : getGridX(newLeft)=" + getGridX(newLeft) + "\ntop : getGridY(newTop)=" + getGridY(newTop));
      if (!setGrid(blueShipGrid, getGridX(newLeft), getGridY(newTop), idWidth, idHeight, idMask, idType)) {      
        //alert("DRAG_enddrag: " + el.id + "\nsetGrid() returned FALSE");
        validMove = false;
        if (oldTop > boardBottom ||
            oldLeft > boardRight) {
          showSimilar(el.id);
	    }  
      }
      else {
        //alert("DRAG_enddrag: " + el.id + "\nsetGrid() returned true, calling showGrid()");
        showGrid(blueShipGrid, "divBlueShipGrid");
      }
    }
    //alert ("enddrag()\nAfter setGrid()\nvalidMove=" + validMove);

    if (!validMove) {
      alert("I'm sorry, but you can't move it there! Try again.");
      el.style.left = oldLeft + "px"
      el.style.top  = oldTop + "px"
      var x = getGridX(oldLeft);
      var y = getGridY(oldTop);
      if (x >= 0 && y >= 0) { //--- former position was ok, restore grid fill ---
        //alert("restoring grid fill: x=" + x + ", y=" + y + ", width=" + idWidth + " , height=" + idHeight);
        setGrid(blueShipGrid, x, y, idWidth, idHeight, idMask, idType);
	  }	      
      showGrid(blueShipGrid, "divBlueShipGrid");
      //alert(el.id + " was returned to its previous position");
    } // end if (reset position)  
    else {
      //clearGrid(blueShipGrid, getGridX(oldLeft), getGridY(oldTop), idWidth, idHeight, idMask);      
    }	
	
    //--- Debugging info ---    
    var msg = "validMove=" + validMove +
            "\n oldLeft=" + oldLeft + 
            "\n oldTop="  + oldTop +
            "\n newLeft=" + el.style.left +
            "\n newTop="  + el.style.top +
            "\n el.width=" + el.width +
            "\n el.height=" + el.height +
            "\n idMask=" + idMask;
    //alert (msg);

    showGrid(blueShipGrid, "divBlueShipGrid");
    
    el.DRAG_dragging = false;
    //alert("dragging FALSE");
    el = null;
    document.onmousemove = null
    document.onmouseup = null
    //alert("New postion: " + el.style.left + "," + el.style.top);
    //alert("DRAG_enddrag");

    if (mode == "setup" && getShipsOnBoard("blue") == 5) {
      mode = "ready"; 
    }
    showMode();

    return true
  }

//------------------------------------------------------------------------------

  this.allowDrag = function(dragEl, e) {
    el = dragEl
    DRAG_begindrag(e)
  }

//------------------------------------------------------------------------------
// clientSniffer: 
//    Original code from Wrox Professional JavaScript, 2nd Editon, Chapter 17
//------------------------------------------------------------------------------

function clientSniffer() {
   var agent = navigator.appName
   this.isIE = function() {
     return (agent == "Microsoft Internet Explorer" && document.all)
   }
   this.isNS = function() { 
     return (agent == "Netscape") 
   }
   this.getVersion = function() {
     if (this.isNS()) return parseInt(navigator.appVersion)
       if (this.isIE()) {
         var vIdx = navigator.appVersion.indexOf("MSIE ") + ("MSIE ").length
		     return parseInt(navigator.appVersion.substring(vIdx, vIdx+3))
       }
       return 0
   }
   this.isDOM = function() {
     return document.getElementById ? true : false
   }
}

//------------------------------------------------------------------------------

var cs = new clientSniffer()

//------------------------------------------------------------------------------

function writeImage (baseID, left, top, width, height, mask, src, title) {
  var id = baseID + "-m_" + mask + "-w_" + width + "-h_" + height + "-t_" + top + "-l_" + left;
  document.write("<img id=" + id + " onmousedown=\"allowDrag(this, event);\"");
  document.write(" style=\"position:absolute; left:" + left + "; top:" + top + ";"); 
  document.write(" visiblity:visible; zIndex:2;\""); 
  document.write(" src=\"" + src + "\" title=\"" + title + "\" alt=\"" + title + "\">");
}

//------------------------------------------------------------------------------

function scoreboardVisibility (visibility) {
  //alert("scoreboardVisibility(" + visibility + ")");
  for (var i = 0; i < document.images.length; i++) {
    if (document.images[i].id.substring(0,11) == "scoreboard-") {
      document.images[i].style.visibility = visibility;	
	}
  }
}

//------------------------------------------------------------------------------

function drawScoreboardShip (id, left, top, title, src) {
  document.write("<img id=" + id + " zIndex:1;");
  document.write(" style=\"position:absolute; left:" + left + "; top:" + top + ";"); 
  document.write(" visibility:hidden; \""); 
  //document.write(" visibility:visible; \""); 
  document.write(" src=\"" + src + "\" alt=\"" + title + "\" title=\"" + title + "\">");
}

//------------------------------------------------------------------------------

function drawScoreboard () {
  var left = boardLeft + boardWidth + 18;
  drawScoreboardShip ("scoreboard-blue-b", left +   0, boardTop + 135, "Your Battleship", "Battleship_Horz.gif");
  drawScoreboardShip ("scoreboard-blue-c", left +  15, boardTop + 165, "Your Cruiser", "Cruiser_Horz.gif");
  drawScoreboardShip ("scoreboard-blue-d", left +  30, boardTop + 195, "Your Destroyer", "Destroyer_Horz.gif");
  drawScoreboardShip ("scoreboard-blue-f", left +  45, boardTop + 225, "Your Frigate", "Frigate_Horz.gif");
  drawScoreboardShip ("scoreboard-blue-p", left +  60, boardTop + 255, "Your Patrol Boat", "PT_Horz.gif");

  var top = boardTop + boardHeight + boardSpacing;
  left = boardLeft + boardWidth + 18;
  drawScoreboardShip ("scoreboard-red-b", left +   0, top + 135, "Enemy Battleship", "Battleship_Horz.gif");
  drawScoreboardShip ("scoreboard-red-c", left +  15, top + 165, "Enemy Cruiser", "Cruiser_Horz.gif");
  drawScoreboardShip ("scoreboard-red-d", left +  30, top + 195, "Enemy Destroyer", "Destroyer_Horz.gif");
  drawScoreboardShip ("scoreboard-red-f", left +  45, top + 225, "Enemy Frigate", "Frigate_Horz.gif");
  drawScoreboardShip ("scoreboard-red-p", left +  60, top + 255, "Enemy Patrol Boat", "PT_Horz.gif");

}

//------------------------------------------------------------------------------

function drawGrid(board) {
  document.write ("<table width=" + ((boardCellsX * boardCellWidth) + 1) + " cellpadding=0 cellspacing=1 border=0>");
  for (var row = 0; row < boardCellsY; row++) {
    document.write("<tr>");
    for (var col = 0; col < boardCellsX; col++) { 
      document.write("<td id=" + board + "-r_" + row + "-c_" + col + " bgColor=#ffffff width=" + (boardCellWidth - 1) + " height=" + (boardCellHeight - 1) + " >");
      if (board == "red")
        document.write("<img id=redImg-r_" + row + "-c_" + col + " width=" + (boardCellWidth-1) + " height=" + (boardCellHeight-1) + " src=ClearDot.gif alt=\"" + row + ":" + col + "\" border=0 onClick=shot(this);>");
      else
        document.write("&nbsp;");
      document.write("</td>");
    }
    document.write("</tr>");
  }
  document.write ("</table>");
}

//------------------------------------------------------------------------------

function drawBoard(board, visibility) {
  var top = boardTop;
  var title = "Your Territory";
  if (board == "red") {
    top = boardTop + boardHeight + boardSpacing;
    title = "Enemy Territory";
  }
  document.write("<div id=div" + board);
  document.write(" style=\"position:absolute; visibility:" + visibility + ";"); 
  document.write(" text-align:center; font-family:Arial; font-weight:bold;"); 
  document.write(" top:" + (top - boardTitleHeight) + "; left:" + boardLeft + ";"); 
  document.write(" height:" + boardTitleHeight + "; width:" + boardWidth + ";"); 
  document.write(" color:white; background-color:" + board + ";\">" + title + "</div>");

  document.write("<table id=table" + board + " width=" + boardWidth + " cellpadding=0 cellspacing=0 border=0");
  document.write(" style=\"position:absolute; left:" + boardLeft + "; top:" + top + ";"); 
  document.write(" zIndex:1; visibility:" + visibility + ";\">");
  document.write("<tr>");
  document.write("  <td bgcolor=gray>");
  drawGrid(board);
  document.write("    </td>");  
  document.write("  </tr>");
  document.write("</table>");

  document.write("<table id=table-" + board + "Status"); 
  document.write(" cellpadding=4 cellspacing=0 border=0"); 
  document.write(" style=\"position:absolute; font-weight:bold; font-family:Arial;");
  document.write(" height:135; width:180; visibility:" + visibility +";");
  document.write(" top:" + (top - boardTitleHeight) + "; left:" + (boardLeft + boardWidth + 5) + ";");
  document.write(" color:white; background-color:" + board + ";\">");
  document.write(" <tr><td class=status id=" + board + "Status valign=top>&nbsp;</td></tr></table>");
}

//------------------------------------------------------------------------------

function drawShips() {
  var left = boardLeft + boardWidth + 5;

  writeImage("id=blue-ship_b", left, (boardTop + 120), 5, 1, "11111", "Battleship_Horz.gif", "Battleship");
  writeImage("id=blue-ship_c", left, (boardTop + 150), 4, 1, "1111",  "Cruiser_Horz.gif",    "Cruiser");
  writeImage("id=blue-ship_d", left, (boardTop + 180), 3, 1, "111",   "Destroyer_Horz.gif",  "Destroyer");
  writeImage("id=blue-ship_f", left, (boardTop + 210), 2, 1, "11",    "Frigate_Horz.gif",    "Frigate");
  writeImage("id=blue-ship_p", left, (boardTop + 240), 1, 1, "1",     "PT_Horz.gif",         "Patrol Boat");

  writeImage("id=blue-ship_b", (left + 150), (boardTop + 150), 1, 5, "11111", "Battleship_Vert.gif", "Battleship");
  writeImage("id=blue-ship_c", (left + 120), (boardTop + 180), 1, 4, "1111",  "Cruiser_Vert.gif",    "Cruiser");
  writeImage("id=blue-ship_d", (left +  90), (boardTop + 210), 1, 3, "111",   "Destroyer_Vert.gif",  "Destroyer");
  writeImage("id=blue-ship_f", (left +  60), (boardTop + 240), 1, 2, "11",    "Frigate_Vert.gif",    "Frigate");
}

//------------------------------------------------------------------------------

function drawMenu () {
  document.write ("<table border=1 cellpadding=4 cellspacing=0 id=divMenu style=\"position:absolute;");
  document.write (" left:5; top:" + (boardTop - boardTitleHeight) + "; width:120;");
  document.write (" height:" + (boardHeight * 2 + boardTitleHeight + boardSpacing) + ";");  
  document.write (" font-family:Arial; font-weight:bold; text-align:center;");
  document.write (" font-family:Arial; font-weight:bold; text-align:center;");
  document.write (" color:white; background-color:gray;\">");
  document.write ("<tr>");
  document.write ("<td class=status align=center valign=top");
  document.write (" background=\"battleship_banner.png\" >");
  document.write ("BATTLESHIP<br><small><i>by Mark Carson</i></small>");
  document.write ("</td></tr></table>");
  document.write ("<button style=\"position:absolute; left:25; top:80; width:80;\" onClick=\"javascript:help();\">Help</button>");
  document.write ("<button style=\"position:absolute; left:25; top:110; width:80;\" onClick=\"document.location.href = document.location.href;\">Reset</button>");
  document.write ("<div id=divBlueShipGrid style=\"visibility:hidden; top:5;   left:800; position:absolute; font-family:Courier; \"></div>");
  document.write ("<div id=divRedShipGrid  style=\"visibility:hidden; top:325; left:800; position:absolute; font-family:Courier; \"></div>");
  document.write ("<a style=\"position:absolute; left:5; top:" + (boardHeight * 2 + boardTitleHeight + boardSpacing) + ";\">");
  document.write ("<img src=\"ClearDot.gif\" width=5 height=5 border=0 onMouseover=\"radar(true);\" onMouseout=\"radar(false);\"></a>");
  //document.write ("<a class=menuDebug style=\"position:absolute; left:25; top:500;\" href=\"javascript:window.resizeTo(800,600);\" title=\"Resize window to 800x600\">800x600</a>");
  //document.write ("<a class=menuDebug style=\"position:absolute; left:25; top:520;\" href=\"javascript:window.resizeTo(1024,768);\" title=\"Resize window to 1024x768\">1024x768</a>");
}

//------------------------------------------------------------------------------

function drawHarbor(board) {
  var left = boardLeft + boardWidth + 5;
  var top = boardTop + 120;
  var bgColor = "#cfcfff";
  var vis = "visible";
  if (board == "red") {
    top = boardTop + boardHeight + boardSpacing + 120;
    bgColor = "#ffcfcf";
    vis = "hidden";
  }
  document.write ("<div id=" + board + "Harbor style=\"visibility:" + vis + "; z-index:0; position:absolute; left:" + left + "; top:" + top + "; width:180; height:180; background-color:" + bgColor + "\" >&nbsp;</div>");
}  

//------------------------------------------------------------------------------

function drawGame() {
  drawMenu();
  drawBoard("blue", "visible");
  drawBoard("red", "hidden");
  drawHarbor("blue");
  drawHarbor("red");
  drawShips();
  drawScoreboard();
}

//------------------------------------------------------------------------------

function init() {
  randomSetup("red");
  showMode();
  showGrid(blueShipGrid, "divBlueShipGrid"); 
  helpStart(); 
}

//------------------------------------------------------------------------------
