var curCell = -1;
var curRot = 0;
var clickCell = -1;
var celltds = new Array(width*height);
var tileImgs = new Array(width*height);
var backColors = new Array(width*height);
var tState = new Array(width*height);
var conState = new Array(width*height);
var moves = 0;
var servi = 0;
var puzDone = false;
var moveArr = new Array();
var curMoves = 0;

var req;
function recordScore() {
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (req) {
		var poststr = moveArr[0];
		for (var i = 1; i < curMoves; i++)
			poststr += '-' + moveArr[i];
		req.onreadystatechange = processReqChange;
		req.open("POST", "/netwalk/submit.php", true);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send('s='+curMoves + '&h='+poststr + '&t='+token);
	}
}

function processReqChange() {
	if (req.readyState == 4) {
/*		if (req.status == 200 && req.responseText == "Valid") {
			if (confirm("Would you like to participate in our 2008 US Presidential election poll?")) {
				document.poll.submit();
			}
		} else {*/
			alert("Congratulations!");
//		}
	}
}


function getConStates() {
	var q = new Array();
	var qh = 0;
	var qt = 0;

	var cs = new Array(width*height);
	for (var i = 0; i < width*height; i++) cs[i] = 0;

	var dx = Array(0, 1, 0, -1);
	var dy = Array(1, 0, -1, 0);
	var bm = Array(1, 2, 4, 8);

	puzDone = true;
	q[qh++] = servi;
	cs[servi] = 1;
	while (qh > qt) {
		var idx = q[qt++];
		var x = idx%width;
		var y = (idx-x)/width;
		for (var d = 0; d < 4; d++) if ((tState[idx]&bm[d]) == bm[d]) {
			var nx = (x+dx[d]+width)%width;
			var ny = (y+dy[d]+height)%height;
			var nd = (d+2)%4;
			var nidx = ny*width+nx;
			if ((tState[nidx]&bm[nd]) == bm[nd]) {
				if (cs[nidx] == 0) {
					cs[nidx] = 1;
					q[qh++] = nidx;
				}
			} else
				puzDone = false;
		}
	}
	if (puzDone) {
		for (var i = 0; i < width*height; i++)
			if (tState[i] > 0 && cs[i] == 0)
				puzDone = false;
	}
	return cs;
}

function getStates() {
	for (var i = 0; i < width*height; i++) {
		var cc = curpuz.charCodeAt(i);
		if (cc >= 97) cc -= 87;
		if (cc >= 65) cc -= 49;
		if (cc >= 48) cc -= 48;
		tState[i] = cc;
		if (cc >= 16) {
			servi = i;
		}
	}
}

function stateToImage(ts, cs) {
	var name = "images/";
	if (ts >= 16) name += "Server";
	name += (cs >= 1) ? "On" : "Off";
	if ((ts&8)  == 8) name += "Left";
	if ((ts&2)  == 2) name += "Right";
	if ((ts&1)  == 1) name += "Bottom";
	if ((ts&4)  == 4) name += "Top";
	name += ".png";
	return name;
}

function imgPreload() {
	var img = new Array();

	for (var i = 0; i < 32; i++) {
		img[i] = document.createElement('img');
		img[i].src = stateToImage(i, 1);
	}
	for (var i = 0; i < 16; i++) {
		img[i+32] = document.createElement('img');
		img[i+32].src = stateToImage(i, 0);
	}
}

function createTd(idx) {
	celltds[idx] = document.createElement('td');
	celltds[idx].id = "c" + idx;
	celltds[idx].style.height = "48px";
	celltds[idx].style.width = "48px";
	celltds[idx].style.border = "1px solid black";
/*	celltds[idx].onmouseover = mouseOver;
	celltds[idx].onmouseout = mouseOut;
	celltds[idx].onmouseup = mouseClick;
	celltds[idx].onmousedown = function(){return false};
	celltds[idx].oncontextmenu = function(){return false};*/

	celltds[idx].style.backgroundColor = "#FFFFFF";
	tileImgs[idx] = document.createElement('img');
	tileImgs[idx].id = "i" + idx;
	tileImgs[idx].onmouseover = mouseOver;
	tileImgs[idx].onmouseout = mouseOut;
	tileImgs[idx].onmouseup = mouseClick;
	tileImgs[idx].onmousedown = function(){return false};
	tileImgs[idx].onselectstart = function(){return false};
	tileImgs[idx].oncontextmenu = function(){return false};
	tileImgs[idx].src = stateToImage(tState[idx], conState[idx]);
	celltds[idx].appendChild(tileImgs[idx]);
	backColors[idx] = "#FFFFFF";
}

// create the table with all the netwalk tiles
function initNetwalkGrid() {
	getStates();
	conState = getConStates();
	imgPreload();

	var mydiv = document.getElementById('contain');
	var tbl = document.createElement('table');
	var tbody = document.createElement('tbody');

	for (var i = 0; i < height; i++) {
		var newtr = document.createElement('tr');
		for (var j = 0; j < width; j++) {
			createTd(i*width+j);
			newtr.appendChild(celltds[i*width+j]);
		}
		tbody.appendChild(newtr);
	}
	tbl.appendChild(tbody);
	mydiv.appendChild(tbl);

	initAfterGrid();
}

function getEventId(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) targ = targ.parentNode;
	return parseInt(targ.id.substring(1));
}

function mouseOver(e) {
	var idx = getEventId(e);
	curCell = idx;
}

function mouseOut(e) {
	var idx = getEventId(e);
	curCell = -1;
}



var timerID = 0;
var tstart = null;
var killTimer = false;

function updateTimer() {
	if (timerID) clearTimeout(timerID);
	if (!tstart) tstart = new Date();
	if (killTimer) return;

	var tdate = new Date();
	var tdiff = tdate.getTime() - tstart.getTime();

	var min = Math.floor(tdiff/60000), sec = Math.floor(tdiff/1000-60*min);
	var frmt = min + (sec > 9 ? ":" : ":0") + sec;
	document.getElementById('timer').innerHTML = "Time " + frmt;

	timerID = setTimeout("updateTimer()", 1000);
}

function initAfterGrid() {
	tstart = new Date();
	timerID = setTimeout("updateTimer()", 1000);
}

function toggleState(idx, right) {
	var nts = tState[idx] & 15;
	var straight = (nts == 5 || nts == 10);
	if (right) {
		if ((nts & 1) == 1)
			nts = (nts >> 1) + 8;
		else
			nts >>= 1;
	} else {
		nts <<= 1;
		if (nts > 15) nts -= 15;
	}
	if (tState[idx] > 15) nts += 16;
	tState[idx] = nts;
	moveArr[curMoves++] = idx + (right ? 'r' : 'l');
	var ncs = getConStates();
	for (var i = 0; i < width*height; i++)
		if (conState[i] != ncs[i] || i == idx) {
			tileImgs[i].src = stateToImage(tState[i], ncs[i]);
		}
	conState = ncs;
	moves++;
	var newRot = curRot+(right?-1:1);
	if (straight) {
		if (newRot == 0 || newRot == 2 || newRot == -2) {
			moves -= 2;
			curMoves -= 2;
			curRot = 0;
		} else
			curRot = newRot;
	} else {
		var modMove = false;
		if (newRot == 0 || (newRot == 1 && curRot == 2) || (newRot == -1 && curRot == -2)) {
			moves -= 2;
			curMoves -= 2;
			if (newRot != 0) modMove = true;
			curRot = newRot;
		} else if (newRot == 3) {
			moves -= 2;
			curMoves -= 2;
			modMove = true;
			curRot = -1;
		} else if (newRot == -3) {
			moves -= 2;
			curMoves -= 2;
			modMove = true;
			curRot = 1;
		} else
			curRot = newRot;
		if (modMove) moveArr[curMoves-1] = idx + (right ? 'l' : 'r');
	}
	document.getElementById('moves').innerHTML = "Moves: " + moves;
	if (puzDone) {
		killTimer = true;
		puzzleDone();
	}
}

function keyPressed(e) {
	var idx = curCell;
	if (idx < 0) return true;
	if (!e) var e = window.event;
	if (puzDone) return false;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var ch = String.fromCharCode(code);
	if (ch == ' ') {
		if (backColors[idx] == "#FFFFFF")
			backColors[idx] = "#CCCCFF";
		else
			backColors[idx] = "#FFFFFF";
		celltds[idx].style.backgroundColor =  backColors[idx];
		if (clickCell != idx) {
			clickCell = idx;
			curRot = 0;
		}
		return false;
/*	} else if (tState[idx] > 0 && backColors[idx] == "#FFFFFF") {
		if (code == 37) {
			toggleState(idx, false);
			return false;
		} else if (code == 39) {
			toggleState(idx, true);
			return false;
		}*/
	}
}

function mouseClick(e) {
	if (!e) var e = window.event;
	var idx = getEventId(e);
	if (curCell != idx) return true;
	if (puzDone) return false;
	var right = false;
	var middle = false;
	if (e.which) {
		right = (e.which == 3);
		middle = (e.which == 2);
	} else if (e.button) {
		right = (e.button == 2);
		middle = (e.button == 4);
	}
	if (clickCell != idx) {
		clickCell = idx;
		curRot = 0;
	}
	if (middle) {
		if (backColors[idx] == "#FFFFFF")
			backColors[idx] = "#CCCCFF";
		else
			backColors[idx] = "#FFFFFF";
		celltds[idx].style.backgroundColor =  backColors[idx];
	} else if (tState[idx] > 0 && backColors[idx] == "#FFFFFF") {
		toggleState(idx, right);
	}
	return false;
}

