/* global variables */
var height = 8; /* height of world - cannot really be changed as minimap size will not change */
var width = 8; /* width of world - cannot really be changed as minimap size will not change */
var posx = 1; /* our x position */
var posy = 1; /* our y position */
var world; /* the 2D array that will hold the world */

/* the contructor - what's run onload */
function construct() {
	makeWorld();
	updateViewPort();
	colourMiniMap();
	updateMiniMap();
	setStatus();
}

/* absolute move to coords */
function moveTo(x, y) {
	// check values
	if (x < 0) return;
	if (x > world.length-2) return;
	if (y < 0) return;
	if (y > world[0].length-2) return;
	posx = x;
	posy = y;
	updateViewPort();
	updateMiniMap();
	setStatus();
}

/* relative move from current position */
function move(x, y) {
	// check values
	if (x < 0 && posx <= 1) x = 0;
	if (x > 0 && posx >= world.length-2) x = 0;
	if (y < 0 && posy <= 1) y = 0;
	if (y > 0 && posy >= world[0].length-2) y = 0;
	posx += x;
	posy += y;
	updateViewPort();
	updateMiniMap();
	setStatus();
}

/* redraw the viewport colours */
function updateViewPort() {
	for (i = 0; i < 3; i++) {
		for (j = 0; j < 3; j++) {
			setSquareImage('square' + i + j, 'url(mapviewer/images/viewport'+ world[i+posx-1][j+posy-1] + '.jpg)');
		}
	}
}

/* colour the minimap (only needs done once) */
function colourMiniMap() {
	for (i = 0; i < width; i++) {
		for (j = 0; j < height; j++) {
			setSquareImage('minimap' + i + j, 'url(mapviewer/images/minimap' + world[i][j] + '.jpg)');
		}
	}
}

/* redraw the borders on the minimap */
function updateMiniMap() {
	for (i = 0; i < width; i++) {
		for (j = 0; j < height; j++) {
			set = 0;
			if (i-1 == posx && (j-1 == posy || j == posy || j+1 == posy)) set = 1;
			if (i+0 == posx && (j-1 == posy || j == posy || j+1 == posy)) set = 1;
			if (i+1 == posx && (j-1 == posy || j == posy || j+1 == posy)) set = 1;
			setBorder('minimap' + i + j, set);
		}
	}
}

/* initialise the 2D array */
function makeWorld() {
	// create 3D array
	world = new Array(width);
	for (i = 0; i < width; i++) {
		world[i] = new Array(height);
		for (j = 0; j < height; j++) {
			world[i][j] = "_"+j+i;
		}
	}
}

/* Takes id name and colour to set
* - This function is used for minimap and viewport colour setting
*/
function setSquareImage(name, image) {
	document.getElementById(name).style.background = image;
}

/* sets the status bar text */
function setStatus() {
	document.getElementById('status').value = "Current location is (" + posx + ", " + posy + ")";;
}

/* takes id name and border values 0 or 1 */
function setBorder(name, set) {
	(set)? border = "1px solid yellow" : border = "1px solid transparent";
	document.getElementById(name).style.border = border;
}

construct(); // this is run, pretty much onload.
