/*  Copyright Chad Miller, 2008.  All rights reserved.
 *
 *
 *  NO REDISTRIBUTION.
 */


ord_position = { "a":0, "b":1, "c":2, "d":3, "e":4, "f":5, "g":6, "h":7, "i":8, "j":9, "k":10, "l":11, "m":12, "n":13, "o":14, "p":15, "q":16, "r":17, "s":18, "t":19, "u":20, "v":21, "w":22, "x":23, "y":24, "z":25 }


var st_el = {
	"b": { "dead": '<img src="/jsgf/stone-bdead.png" />', "alive": '<img src="/jsgf/stone-b.png" />' },
	"w": { "dead": '<img src="/jsgf/stone-wdead.png" />', "alive": '<img src="/jsgf/stone-w.png" />' }
};


function make_board(game, size) {
	game.board_size = size*1; 
	game.board = new Array(size);

	var row;
	for (row = 0; row < size; row++) {
		$("#board").append("<tr></tr>");
		game.board[row] = Array(size);
		for (column = 0; column < size; column++) {
			game.board[row][column] = "";
			$("#board tr:last").append("<td><img src=\"jsgf/empty-square.png\" /></td>");
		}
	}
}

function log_message(message) {
	$("#status").append(String("<br/>" + message));
}

function add_note(message) {
	$("#gamenotes").append(String("<p><pre>" + message + "</pre></p>"));
}

function consider_captures(game, seen_list, not_color, row, column) {
	var key = String(row + ":" + column);

	if (seen_list[key]) {
		return true;
	}
	if (row < 0) return;
	if (column < 0) return;
	if (row > game.board_size-1) return;
	if (column > game.board_size-1) return;

	if (game.board[row][column] == "") {
		return false;  // found liberty
	}

	if (game.board[row][column] == not_color) {
		return true;  // found self
	}

	seen_list[key] = key;  // before recursing, mark ourselves

	if (consider_captures(game, seen_list, not_color, row-1, column) == false) return false;
	if (consider_captures(game, seen_list, not_color, row, column-1) == false) return false;
	if (consider_captures(game, seen_list, not_color, row+1, column) == false) return false;
	if (consider_captures(game, seen_list, not_color, row, column+1) == false) return false;
	
	return true;
}

function remove_all(game, owner, capture_list) {
	var key, row, column;
	for (key in capture_list) {
		row = key.split(":")[0] * 1;
		column = key.split(":")[1] * 1;

		var target_square = $("#board tr").eq(row).children().eq(column);
		target_square.empty();
		game.board[row][column] = "";

		var capture_container = $("#"+owner+"captures");
		capture_container.append("<it>" + st_el[opposite_player(owner)]["dead"] + "</it>");
	}
}

function opposite_player(us) {
	if (us == "w")
		return "b";
	else
		return "w";
}


function bootstrap_capturing(game, color, row, column) {
	var capture_list = Object();
	var is_surrounded;

	is_surrounded = consider_captures(game, capture_list, color, row, column);

	if (is_surrounded == true) {
		remove_all(game, color, capture_list);
	}
}

function place_stone(game, color, coords) {
	var column, row;
	if (coords.length != 2) 
		return  // It may be a pass.

	column = ord_position[coords[0]];
	row = ord_position[coords[1]];

	game.board[row][column] = color;
	$("#board tr").eq(row).children().eq(column).empty().append(st_el[color]["alive"]);

	if (bootstrap_capturing(game, color, row-1, column)) return true;
	if (bootstrap_capturing(game, color, row+1, column)) return true;
	if (bootstrap_capturing(game, color, row, column-1)) return true;
	if (bootstrap_capturing(game, color, row, column+1)) return true;

}

function mark_stone_dead(game, color, coords) {
	var column, row;
	column = ord_position[coords[0]];
	row = ord_position[coords[1]];

	var old_contents = game.board[row][column];

	if (old_contents != "")
		$("#board tr").eq(row).children().eq(column).empty().append(st_el[old_contents]["dead"]);
	else
		$("#board tr").eq(row).children().eq(column).empty().append("<span class=\"point pointfor" + color + "\">+1</span>");
}


var sgf_actions = {
	//"PB" : function (game, content){},
	"C" : function (game, content){ add_note(content[0]); },
	"SZ" : function (game, content){ make_board(game, content[0]*1); },
	"HA" : function (game, content){ game.handicap = content[0]*1; },
	"AB" : function (game, content){ for (var i = 0; i < content.length; i++) place_stone(game, "b", content[i]); },
	"B"  : function (game, content){ place_stone(game, "b", content[0]); },
	"W"  : function (game, content){ place_stone(game, "w", content[0]); },
	"TB" : function (game, content){ for (var i = 0; i < content.length; i++) mark_stone_dead(game, "b", content[i]); },
	"TW" : function (game, content){ for (var i = 0; i < content.length; i++) mark_stone_dead(game, "w", content[i]); },
};	

function finish(game) {
}

function interpret_step(game, text, offset, sleep_msec) {
	var f;
	var verb;
	var parts;
	do {
		// seek verb
		while (! text[offset].match(/[a-z]/i)) { offset++; if (offset == text.length-1) return finish(game); }  // skip junk
		verb = text.slice(offset).match(/[a-z][a-z]*/i)[0];
		offset += verb.length;
		
		// seek arguments
		parts = Array();
		while (text[offset] == "[") {
			offset += 1; // skip opening brace
			var part = text.slice(offset).match(/[^\]]*/)[0];
			offset += part.length;
			offset += 1; // skip closing brace
			parts.push(part);
		}

		f = sgf_actions[verb];
	} while (!f);

	if (f) { 
		if (f(game, parts)) { return true; }
	}

	return setTimeout(function() { interpret_step(game, text, offset, sleep_msec); }, sleep_msec); 
}


function interpret_sgf(http) {
	var game = new Object();

	var lines = Array();
	lines = http.responseText.split("\n");

	interpret_step(game, http.responseText, 0, 333);
}


$(document).ready(function(){

	var gamelist = Array();
	gamelist = [ "/jsgf/dragon291547.sgf", "/jsgf/dragon179117.sgf", "/jsgf/dragon179129.sgf", "/jsgf/dragon187981.sgf", "/jsgf/dragon232813.sgf", "/jsgf/dragon232918.sgf", "/jsgf/dragon236582.sgf", "/jsgf/dragon236585.sgf", "/jsgf/dragon257942.sgf", "/jsgf/dragon270501.sgf", "/jsgf/dragon273138.sgf", "/jsgf/dragon273140.sgf", "/jsgf/dragon285821.sgf", "/jsgf/dragon291546.sgf", "/jsgf/dragon291547.sgf", "/jsgf/dragon317099.sgf" ];

	var choice = Math.floor(Math.random() * gamelist.length);
//	$("#gamenotes").append(String("<p>" + gamelist[choice] + "</p>"));

	jifGet(gamelist[choice], false, interpret_sgf, false);
});
