diff --git a/code/game/machinery/constructable_frame.dm b/code/game/machinery/constructable_frame.dm
index 200b21d441d..43c42ac19bf 100644
--- a/code/game/machinery/constructable_frame.dm
+++ b/code/game/machinery/constructable_frame.dm
@@ -890,6 +890,15 @@ obj/item/weapon/circuitboard/rdserver
/obj/item/weapon/stock_parts/manipulator = 1,
/obj/item/weapon/stock_parts/console_screen = 1)
+/obj/item/weapon/circuitboard/gameboard
+ name = "circuit board (Virtual Gameboard)"
+ build_path = /obj/machinery/gameboard
+ board_type = "machine"
+ origin_tech = "programming=2"
+ req_components = list(
+ /obj/item/weapon/stock_parts/micro_laser = 1,
+ /obj/item/stack/cable_coil = 3,
+ /obj/item/stack/sheet/glass = 1)
//Selectable mode board, like vending machine boards
/obj/item/weapon/circuitboard/logic_gate
diff --git a/code/game/machinery/gameboard.dm b/code/game/machinery/gameboard.dm
new file mode 100644
index 00000000000..b331930b325
--- /dev/null
+++ b/code/game/machinery/gameboard.dm
@@ -0,0 +1,79 @@
+/obj/machinery/gameboard
+ name = "Virtual Gameboard"
+ icon = 'icons/obj/stationobjs.dmi'
+ icon_state = "gboard_on"
+ desc = "A holographic table allowing the crew to have fun™ on boring shifts! One player per board."
+ density = 1
+ anchored = 1
+ use_power = 1
+
+/obj/machinery/gameboard/New()
+ ..()
+ component_parts = list()
+ component_parts += new /obj/item/weapon/circuitboard/gameboard(null)
+ component_parts += new /obj/item/weapon/stock_parts/micro_laser(null)
+ component_parts += new /obj/item/stack/cable_coil(null, 3)
+ component_parts += new /obj/item/stack/sheet/glass(null, 1)
+ RefreshParts()
+
+/obj/machinery/gameboard/power_change()
+ . = ..()
+ update_icon()
+
+/obj/machinery/gameboard/update_icon()
+ if(stat & NOPOWER)
+ icon_state = "gboard_off"
+ else
+ icon_state = "gboard_on"
+
+/obj/machinery/gameboard/attack_hand(mob/user)
+ . = ..()
+ if(.)
+ return
+ if(src.in_use)
+ to_chat(user, "This gameboard is already in use!")
+ return
+ interact(user)
+
+/obj/machinery/gameboard/interact(mob/user)
+ . = ..()
+ if(.)
+ return
+
+ var/dat
+ dat = replacetext(file2text('html/chess.html'), "\[hsrc]", "\ref[src]")
+ var/datum/asset/simple/chess/assets = get_asset_datum(/datum/asset/simple/chess)
+ assets.send(user)
+
+ var/datum/browser/popup = new(user, "SpessChess", name, 500, 800, src)
+ popup.set_content(dat)
+ popup.add_stylesheet("chess.css", 'html/browser/chess.css')
+ popup.add_script("garbochess.js", 'html/browser/garbochess.js')
+ //popup.add_script("boardui.js", 'html/browser/boardui.js')
+ popup.add_script("jquery-1.8.2.min.js", 'html/browser/jquery-1.8.2.min.js')
+ popup.add_script("jquery-ui-1.8.24.custom.min.js", 'html/browser/jquery-ui-1.8.24.custom.min.js')
+ popup.set_window_options("titlebar=0")
+ popup.open()
+ user.set_machine(src)
+
+/obj/machinery/gameboard/proc/close_game() //yes, shamelessly copied over from arcade_base
+ in_use = 0
+ for(var/mob/user in viewers(world.view, src)) // I don't know who you are.
+ if(user.client && user.machine == src) // I will look for you,
+ user.unset_machine() // I will find you,
+ user << browse(null, "window=SpessChess") // And I will kill you.
+ return
+
+/obj/machinery/gameboard/Topic(var/href, var/list/href_list)
+ . = ..()
+ var/prize = /obj/item/stack/tickets
+ if (.)
+ return
+
+ if (href_list["checkmate"])
+ visible_message("[src.name] beeps, \"WINNER!\"")
+ new prize(get_turf(src), 80)
+ close_game()
+
+ if (href_list["close"])
+ close_game()
\ No newline at end of file
diff --git a/code/modules/client/asset_cache.dm b/code/modules/client/asset_cache.dm
index 33254cc7d2d..ac4a426fe08 100644
--- a/code/modules/client/asset_cache.dm
+++ b/code/modules/client/asset_cache.dm
@@ -204,6 +204,27 @@ proc/getFilesSlow(var/client/client, var/list/files, var/register_asset = TRUE)
"ntlogo.png" = 'icons/paper_icons/ntlogo.png'
)
+/datum/asset/simple/chess
+ assets = list(
+ "bishop_black.png" = 'icons/chess_pieces/bishop_black.png',
+ "bishop_white.png" = 'icons/chess_pieces/bishop_white.png',
+ "king_black.png" = 'icons/chess_pieces/king_black.png',
+ "king_white.png" = 'icons/chess_pieces/king_white.png',
+ "knight_black.png" = 'icons/chess_pieces/knight_black.png',
+ "knight_white.png" = 'icons/chess_pieces/knight_white.png',
+ "pawn_black.png" = 'icons/chess_pieces/pawn_black.png',
+ "pawn_white.png" = 'icons/chess_pieces/pawn_white.png',
+ "queen_black.png" = 'icons/chess_pieces/queen_black.png',
+ "queen_white.png" = 'icons/chess_pieces/queen_white.png',
+ "rook_black.png" = 'icons/chess_pieces/rook_black.png',
+ "rook_white.png" = 'icons/chess_pieces/rook_white.png',
+ "sprites.png" = 'icons/chess_pieces/sprites.png',
+ "blank.gif" = 'icons/chess_pieces/blank.gif',
+ "background.png" = 'nano/images/uiBackground.png',
+ "garbochess.js" = 'html/browser/garbochess.js',
+ "boardui.js" = 'html/browser/boardui.js'
+ )
+
/datum/asset/nanoui
var/list/common = list()
diff --git a/html/browser/boardui.js b/html/browser/boardui.js
new file mode 100644
index 00000000000..68ee667a355
--- /dev/null
+++ b/html/browser/boardui.js
@@ -0,0 +1,395 @@
+var g_startOffset = null;
+var g_selectedPiece = null;
+var moveNumber = 1;
+
+var g_allMoves = [];
+var g_playerWhite = true;
+var g_changingFen = false;
+var g_analyzing = false;
+
+var g_uiBoard;
+var g_cellSize = 45;
+
+function UINewGame() {
+ moveNumber = 1;
+
+ var pgnTextBox = document.getElementById("PgnTextBox");
+ pgnTextBox.value = "";
+
+ EnsureAnalysisStopped();
+ ResetGame();
+ if (InitializeBackgroundEngine()) {
+ g_backgroundEngine.postMessage("go");
+ }
+ g_allMoves = [];
+ RedrawBoard();
+
+ if (!g_playerWhite) {
+ SearchAndRedraw();
+ }
+}
+
+function UIClose() {
+ window.location = "byond://?src=" + hSrc + ";close=1";
+}
+
+function EnsureAnalysisStopped() {
+ if (g_analyzing && g_backgroundEngine != null) {
+ g_backgroundEngine.terminate();
+ g_backgroundEngine = null;
+ }
+}
+
+function UIAnalyzeToggle() {
+ if (InitializeBackgroundEngine()) {
+ if (!g_analyzing) {
+ g_backgroundEngine.postMessage("analyze");
+ } else {
+ EnsureAnalysisStopped();
+ }
+ g_analyzing = !g_analyzing;
+ document.getElementById("AnalysisToggleLink").innerText = g_analyzing ? "Analysis: On" : "Analysis: Off";
+ } else {
+ alert("Your browser must support web workers for analysis - (chrome4, ff4, safari)");
+ }
+}
+
+function UIChangeFEN() {
+ if (!g_changingFen) {
+ var fenTextBox = document.getElementById("FenTextBox");
+ var result = InitializeFromFen(fenTextBox.value);
+ if (result.length != 0) {
+ UpdatePVDisplay(result);
+ return;
+ } else {
+ UpdatePVDisplay('');
+ }
+ g_allMoves = [];
+
+ EnsureAnalysisStopped();
+ InitializeBackgroundEngine();
+
+ g_playerWhite = !!g_toMove;
+ g_backgroundEngine.postMessage("position " + GetFen());
+
+ RedrawBoard();
+ }
+}
+
+function UIChangeStartPlayer() {
+ g_playerWhite = !g_playerWhite;
+ RedrawBoard();
+}
+
+function UpdatePgnTextBox(move) {
+ var pgnTextBox = document.getElementById("PgnTextBox");
+ if (g_toMove != 0) {
+ pgnTextBox.value += moveNumber + ". ";
+ moveNumber++;
+ }
+ pgnTextBox.value += GetMoveSAN(move) + " ";
+}
+
+function UIChangeTimePerMove() {
+ var timePerMove = document.getElementById("TimePerMove");
+ g_timeout = parseInt(timePerMove.value, 10);
+}
+
+function FinishMove(bestMove, value, timeTaken, ply) {
+ if (bestMove != null) {
+ UIPlayMove(bestMove, BuildPVMessage(bestMove, value, timeTaken, ply));
+ } else {
+ window.location = "byond://?src=" + hSrc + ";checkmate=1";
+ }
+}
+
+function UIPlayMove(move, pv) {
+ UpdatePgnTextBox(move);
+
+ g_allMoves[g_allMoves.length] = move;
+ MakeMove(move);
+
+ UpdatePVDisplay(pv);
+
+ UpdateFromMove(move);
+}
+
+function UIUndoMove() {
+ if (g_allMoves.length == 0) {
+ return;
+ }
+
+ if (g_backgroundEngine != null) {
+ g_backgroundEngine.terminate();
+ g_backgroundEngine = null;
+ }
+
+ UnmakeMove(g_allMoves[g_allMoves.length - 1]);
+ g_allMoves.pop();
+
+ if (g_playerWhite != !!g_toMove && g_allMoves.length != 0) {
+ UnmakeMove(g_allMoves[g_allMoves.length - 1]);
+ g_allMoves.pop();
+ }
+
+ RedrawBoard();
+}
+
+function UpdatePVDisplay(pv) {
+ if (pv != null) {
+ var outputDiv = document.getElementById("output");
+ if (outputDiv.firstChild != null) {
+ outputDiv.removeChild(outputDiv.firstChild);
+ }
+ outputDiv.appendChild(document.createTextNode(pv));
+ }
+}
+
+function SearchAndRedraw() {
+ if (g_analyzing) {
+ EnsureAnalysisStopped();
+ InitializeBackgroundEngine();
+ g_backgroundEngine.postMessage("position " + GetFen());
+ g_backgroundEngine.postMessage("analyze");
+ return;
+ }
+
+ if (InitializeBackgroundEngine()) {
+ g_backgroundEngine.postMessage("search " + g_timeout);
+ } else {
+ Search(FinishMove, 99, null);
+ }
+}
+
+var g_backgroundEngineValid = true;
+var g_backgroundEngine;
+
+function InitializeBackgroundEngine() {
+ if (!g_backgroundEngineValid) {
+ return false;
+ }
+
+ if (g_backgroundEngine == null) {
+ g_backgroundEngineValid = true;
+ try {
+ g_backgroundEngine = new Worker("garbochess.js");
+ g_backgroundEngine.onmessage = function (e) {
+ if (e.data.match("^pv") == "pv") {
+ UpdatePVDisplay(e.data.substr(3, e.data.length - 3));
+ } else if (e.data.match("^message") == "message") {
+ EnsureAnalysisStopped();
+ UpdatePVDisplay(e.data.substr(8, e.data.length - 8));
+ } else {
+ UIPlayMove(GetMoveFromString(e.data), null);
+ }
+ }
+ g_backgroundEngine.error = function (e) {
+ alert("Error from background worker:" + e.message);
+ }
+ g_backgroundEngine.postMessage("position " + GetFen());
+ } catch (error) {
+ g_backgroundEngineValid = false;
+ }
+ }
+
+ return g_backgroundEngineValid;
+}
+
+function UpdateFromMove(move) {
+ var fromX = (move & 0xF) - 4;
+ var fromY = ((move >> 4) & 0xF) - 2;
+ var toX = ((move >> 8) & 0xF) - 4;
+ var toY = ((move >> 12) & 0xF) - 2;
+
+ if (!g_playerWhite) {
+ fromY = 7 - fromY;
+ toY = 7 - toY;
+ fromX = 7 - fromX;
+ toX = 7 - toX;
+ }
+
+ if ((move & moveflagCastleKing) ||
+ (move & moveflagCastleQueen) ||
+ (move & moveflagEPC) ||
+ (move & moveflagPromotion)) {
+ RedrawPieces();
+ } else {
+ var fromSquare = g_uiBoard[fromY * 8 + fromX];
+ $(g_uiBoard[toY * 8 + toX])
+ .empty()
+ .append($(fromSquare).children());
+ }
+}
+
+function RedrawPieces() {
+ for (y = 0; y < 8; ++y) {
+ for (x = 0; x < 8; ++x) {
+ var td = g_uiBoard[y * 8 + x];
+ var pieceY = g_playerWhite ? y : 7 - y;
+ var piece = g_board[((pieceY + 2) * 0x10) + (g_playerWhite ? x : 7 - x) + 4];
+ var pieceName = null;
+ switch (piece & 0x7) {
+ case piecePawn: pieceName = "pawn"; break;
+ case pieceKnight: pieceName = "knight"; break;
+ case pieceBishop: pieceName = "bishop"; break;
+ case pieceRook: pieceName = "rook"; break;
+ case pieceQueen: pieceName = "queen"; break;
+ case pieceKing: pieceName = "king"; break;
+ }
+ if (pieceName != null) {
+ pieceName += "_";
+ pieceName += (piece & 0x8) ? "white" : "black";
+ }
+
+ if (pieceName != null) {
+ var img = document.createElement("div");
+ $(img).addClass('sprite-' + pieceName);
+ img.style.backgroundImage = "url('sprites.png')";
+ img.width = g_cellSize;
+ img.height = g_cellSize;
+ var divimg = document.createElement("div");
+ divimg.appendChild(img);
+
+ $(divimg).draggable({ start: function (e, ui) {
+ if (g_selectedPiece === null) {
+ g_selectedPiece = this;
+ var offset = $(this).closest('table').offset();
+ g_startOffset = {
+ left: e.pageX - offset.left,
+ top: e.pageY - offset.top
+ };
+ } else {
+ return g_selectedPiece == this;
+ }
+ }});
+
+ $(divimg).mousedown(function(e) {
+ if (g_selectedPiece === null) {
+ var offset = $(this).closest('table').offset();
+ g_startOffset = {
+ left: e.pageX - offset.left,
+ top: e.pageY - offset.top
+ };
+ e.stopPropagation();
+ g_selectedPiece = this;
+ g_selectedPiece.style.backgroundImage = "url('img/transpBlue50.png')";
+ } else if (g_selectedPiece === this) {
+ g_selectedPiece.style.backgroundImage = null;
+ g_selectedPiece = null;
+ }
+ });
+
+ $(td).empty().append(divimg);
+ } else {
+ $(td).empty();
+ }
+ }
+ }
+}
+
+function RedrawBoard() {
+ var div = $("#board")[0];
+
+ var table = document.createElement("table");
+ table.cellPadding = "0px";
+ table.cellSpacing = "0px";
+ $(table).addClass('no-highlight');
+
+ var tbody = document.createElement("tbody");
+
+ g_uiBoard = [];
+
+ var dropPiece = function (e, ui) {
+ var endX = e.pageX - $(table).offset().left;
+ var endY = e.pageY - $(table).offset().top;
+
+ endX = Math.floor(endX / g_cellSize);
+ endY = Math.floor(endY / g_cellSize);
+
+ var startX = Math.floor(g_startOffset.left / g_cellSize);
+ var startY = Math.floor(g_startOffset.top / g_cellSize);
+
+ if (!g_playerWhite) {
+ startY = 7 - startY;
+ endY = 7 - endY;
+ startX = 7 - startX;
+ endX = 7 - endX;
+ }
+
+ var moves = GenerateValidMoves();
+ var move = null;
+ for (var i = 0; i < moves.length; i++) {
+ if ((moves[i] & 0xFF) == MakeSquare(startY, startX) &&
+ ((moves[i] >> 8) & 0xFF) == MakeSquare(endY, endX)) {
+ move = moves[i];
+ }
+ }
+
+ if (!g_playerWhite) {
+ startY = 7 - startY;
+ endY = 7 - endY;
+ startX = 7 - startX;
+ endX = 7 - endX;
+ }
+
+ g_selectedPiece.style.left = 0;
+ g_selectedPiece.style.top = 0;
+
+ if (!(startX == endX && startY == endY) && move != null) {
+ UpdatePgnTextBox(move);
+
+ if (InitializeBackgroundEngine()) {
+ g_backgroundEngine.postMessage(FormatMove(move));
+ }
+
+ g_allMoves[g_allMoves.length] = move;
+ MakeMove(move);
+
+ UpdateFromMove(move);
+
+ g_selectedPiece.style.backgroundImage = null;
+ g_selectedPiece = null;
+
+ var fen = GetFen();
+ document.getElementById("FenTextBox").value = fen;
+
+ setTimeout("SearchAndRedraw()", 0);
+ } else {
+ g_selectedPiece.style.backgroundImage = null;
+ g_selectedPiece = null;
+ }
+ };
+
+ for (y = 0; y < 8; ++y) {
+ var tr = document.createElement("tr");
+
+ for (x = 0; x < 8; ++x) {
+ var td = document.createElement("td");
+ td.style.width = g_cellSize + "px";
+ td.style.height = g_cellSize + "px";
+ td.style.backgroundColor = ((y ^ x) & 1) ? "#D18947" : "#FFCE9E";
+ tr.appendChild(td);
+ g_uiBoard[y * 8 + x] = td;
+ }
+
+ tbody.appendChild(tr);
+ }
+
+ table.appendChild(tbody);
+
+ $('body').droppable({ drop: dropPiece });
+ $(table).mousedown(function(e) {
+ if (g_selectedPiece !== null) {
+ dropPiece(e);
+ }
+ });
+
+ RedrawPieces();
+
+ $(div).empty();
+ div.appendChild(table);
+
+ g_changingFen = true;
+ document.getElementById("FenTextBox").value = GetFen();
+ g_changingFen = false;
+}
diff --git a/html/browser/chess.css b/html/browser/chess.css
new file mode 100644
index 00000000000..43c61a04cf4
--- /dev/null
+++ b/html/browser/chess.css
@@ -0,0 +1,23 @@
+ #FenTextBox {
+ width: 400px;
+ }
+ #TimePerMove {
+ width: 50px;
+ }
+ .no-highlight {
+ -webkit-tap-highlight-color: rgba(0,0,0,0);
+ }
+ .sprite-bishop_black{ background-position: 0 0; width: 45px; height: 45px; }
+ .sprite-bishop_white{ background-position: 0 -95px; width: 45px; height: 45px; }
+ .sprite-king_black{ background-position: 0 -190px; width: 45px; height: 45px; }
+ .sprite-king_white{ background-position: 0 -285px; width: 45px; height: 45px; }
+ .sprite-knight_black{ background-position: 0 -380px; width: 45px; height: 45px; }
+ .sprite-knight_white{ background-position: 0 -475px; width: 45px; height: 45px; }
+ .sprite-pawn_black{ background-position: 0 -570px; width: 45px; height: 45px; }
+ .sprite-pawn_white{ background-position: 0 -665px; width: 45px; height: 45px; }
+ .sprite-queen_black{ background-position: 0 -760px; width: 45px; height: 45px; }
+ .sprite-queen_white{ background-position: 0 -855px; width: 45px; height: 45px; }
+ .sprite-rook_black{ background-position: 0 -950px; width: 45px; height: 45px; }
+ .sprite-rook_white{ background-position: 0 -1045px; width: 45px; height: 45px; }
+ background-image:url(background.png) no-repeat center center fixed;
+ background-size:cover;
\ No newline at end of file
diff --git a/html/browser/garbochess.js b/html/browser/garbochess.js
new file mode 100644
index 00000000000..7e94bea53d9
--- /dev/null
+++ b/html/browser/garbochess.js
@@ -0,0 +1,2515 @@
+"use strict";
+
+// Perf TODO:
+// Merge material updating with psq values
+// Put move scoring inline in generator
+// Remove need for fliptable in psq tables. Access them by color
+// Optimize pawn move generation
+
+// Non-perf todo:
+// Checks in first q?
+// Pawn eval.
+// Better king evaluation
+// Better move sorting in PV nodes (especially root)
+
+var g_debug = true;
+var g_timeout = 40;
+
+function GetFen(){
+ var result = "";
+ for (var row = 0; row < 8; row++) {
+ if (row != 0)
+ result += '/';
+ var empty = 0;
+ for (var col = 0; col < 8; col++) {
+ var piece = g_board[((row + 2) << 4) + col + 4];
+ if (piece == 0) {
+ empty++;
+ }
+ else {
+ if (empty != 0)
+ result += empty;
+ empty = 0;
+
+ var pieceChar = [" ", "p", "n", "b", "r", "q", "k", " "][(piece & 0x7)];
+ result += ((piece & colorWhite) != 0) ? pieceChar.toUpperCase() : pieceChar;
+ }
+ }
+ if (empty != 0) {
+ result += empty;
+ }
+ }
+
+ result += g_toMove == colorWhite ? " w" : " b";
+ result += " ";
+ if (g_castleRights == 0) {
+ result += "-";
+ }
+ else {
+ if ((g_castleRights & 1) != 0)
+ result += "K";
+ if ((g_castleRights & 2) != 0)
+ result += "Q";
+ if ((g_castleRights & 4) != 0)
+ result += "k";
+ if ((g_castleRights & 8) != 0)
+ result += "q";
+ }
+
+ result += " ";
+
+ if (g_enPassentSquare == -1) {
+ result += '-';
+ }
+ else {
+ result += FormatSquare(g_enPassentSquare);
+ }
+
+ return result;
+}
+
+function GetMoveSAN(move, validMoves) {
+ var from = move & 0xFF;
+ var to = (move >> 8) & 0xFF;
+
+ if (move & moveflagCastleKing) return "O-O";
+ if (move & moveflagCastleQueen) return "O-O-O";
+
+ var pieceType = g_board[from] & 0x7;
+ var result = ["", "", "N", "B", "R", "Q", "K", ""][pieceType];
+
+ var dupe = false, rowDiff = true, colDiff = true;
+ if (validMoves == null) {
+ validMoves = GenerateValidMoves();
+ }
+ for (var i = 0; i < validMoves.length; i++) {
+ var moveFrom = validMoves[i] & 0xFF;
+ var moveTo = (validMoves[i] >> 8) & 0xFF;
+ if (moveFrom != from &&
+ moveTo == to &&
+ (g_board[moveFrom] & 0x7) == pieceType) {
+ dupe = true;
+ if ((moveFrom & 0xF0) == (from & 0xF0)) {
+ rowDiff = false;
+ }
+ if ((moveFrom & 0x0F) == (from & 0x0F)) {
+ colDiff = false;
+ }
+ }
+ }
+
+ if (dupe) {
+ if (colDiff) {
+ result += FormatSquare(from).charAt(0);
+ } else if (rowDiff) {
+ result += FormatSquare(from).charAt(1);
+ } else {
+ result += FormatSquare(from);
+ }
+ } else if (pieceType == piecePawn && (g_board[to] != 0 || (move & moveflagEPC))) {
+ result += FormatSquare(from).charAt(0);
+ }
+
+ if (g_board[to] != 0 || (move & moveflagEPC)) {
+ result += "x";
+ }
+
+ result += FormatSquare(to);
+
+ if (move & moveflagPromotion) {
+ if (move & moveflagPromoteBishop) result += "=B";
+ else if (move & moveflagPromoteKnight) result += "=N";
+ else if (move & moveflagPromoteQueen) result += "=Q";
+ else result += "=R";
+ }
+
+ MakeMove(move);
+ if (g_inCheck) {
+ result += GenerateValidMoves().length == 0 ? "#" : "+";
+ }
+ UnmakeMove(move);
+
+ return result;
+}
+
+function FormatSquare(square) {
+ var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
+ return letters[(square & 0xF) - 4] + ((9 - (square >> 4)) + 1);
+}
+
+function FormatMove(move) {
+ var result = FormatSquare(move & 0xFF) + FormatSquare((move >> 8) & 0xFF);
+ if (move & moveflagPromotion) {
+ if (move & moveflagPromoteBishop) result += "b";
+ else if (move & moveflagPromoteKnight) result += "n";
+ else if (move & moveflagPromoteQueen) result += "q";
+ else result += "r";
+ }
+ return result;
+}
+
+function GetMoveFromString(moveString) {
+ var moves = GenerateValidMoves();
+ for (var i = 0; i < moves.length; i++) {
+ if (FormatMove(moves[i]) == moveString) {
+ return moves[i];
+ }
+ }
+ alert("busted! ->" + moveString + " fen:" + GetFen());
+}
+
+function PVFromHash(move, ply) {
+ if (ply == 0)
+ return "";
+
+ if (move == 0) {
+ if (g_inCheck) return "checkmate";
+ return "stalemate";
+ }
+
+ var pvString = " " + GetMoveSAN(move);
+ MakeMove(move);
+
+ var hashNode = g_hashTable[g_hashKeyLow & g_hashMask];
+ if (hashNode != null && hashNode.lock == g_hashKeyHigh && hashNode.bestMove != null) {
+ pvString += PVFromHash(hashNode.bestMove, ply - 1);
+ }
+
+ UnmakeMove(move);
+
+ return pvString;
+}
+
+//
+// Searching code
+//
+
+var g_startTime;
+
+var g_nodeCount;
+var g_qNodeCount;
+var g_searchValid;
+var g_globalPly = 0;
+
+function Search(finishMoveCallback, maxPly, finishPlyCallback) {
+ var lastEval;
+ var alpha = minEval;
+ var beta = maxEval;
+
+ g_globalPly++;
+ g_nodeCount = 0;
+ g_qNodeCount = 0;
+ g_searchValid = true;
+
+ var bestMove = 0;
+ var value;
+
+ g_startTime = (new Date()).getTime();
+
+ var i;
+ for (i = 1; i <= maxPly && g_searchValid; i++) {
+ var tmp = AlphaBeta(i, 0, alpha, beta);
+ if (!g_searchValid) break;
+
+ value = tmp;
+
+ if (value > alpha && value < beta) {
+ alpha = value - 500;
+ beta = value + 500;
+
+ if (alpha < minEval) alpha = minEval;
+ if (beta > maxEval) beta = maxEval;
+ } else if (alpha != minEval) {
+ alpha = minEval;
+ beta = maxEval;
+ i--;
+ }
+
+ if (g_hashTable[g_hashKeyLow & g_hashMask] != null) {
+ bestMove = g_hashTable[g_hashKeyLow & g_hashMask].bestMove;
+ }
+
+ if (finishPlyCallback != null) {
+ finishPlyCallback(bestMove, value, (new Date()).getTime() - g_startTime, i);
+ }
+ }
+
+ if (finishMoveCallback != null) {
+ finishMoveCallback(bestMove, value, (new Date()).getTime() - g_startTime, i - 1);
+ }
+}
+
+var minEval = -2000000;
+var maxEval = +2000000;
+
+var minMateBuffer = minEval + 2000;
+var maxMateBuffer = maxEval - 2000;
+
+var materialTable = [0, 800, 3350, 3450, 5000, 9750, 600000];
+
+var pawnAdj =
+[
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ -25, 105, 135, 270, 270, 135, 105, -25,
+ -80, 0, 30, 176, 176, 30, 0, -80,
+ -85, -5, 25, 175, 175, 25, -5, -85,
+ -90, -10, 20, 125, 125, 20, -10, -90,
+ -95, -15, 15, 75, 75, 15, -15, -95,
+ -100, -20, 10, 70, 70, 10, -20, -100,
+ 0, 0, 0, 0, 0, 0, 0, 0
+];
+
+var knightAdj =
+ [-200, -100, -50, -50, -50, -50, -100, -200,
+ -100, 0, 0, 0, 0, 0, 0, -100,
+ -50, 0, 60, 60, 60, 60, 0, -50,
+ -50, 0, 30, 60, 60, 30, 0, -50,
+ -50, 0, 30, 60, 60, 30, 0, -50,
+ -50, 0, 30, 30, 30, 30, 0, -50,
+ -100, 0, 0, 0, 0, 0, 0, -100,
+ -200, -50, -25, -25, -25, -25, -50, -200
+ ];
+
+var bishopAdj =
+ [ -50,-50,-25,-10,-10,-25,-50,-50,
+ -50,-25,-10, 0, 0,-10,-25,-50,
+ -25,-10, 0, 25, 25, 0,-10,-25,
+ -10, 0, 25, 40, 40, 25, 0,-10,
+ -10, 0, 25, 40, 40, 25, 0,-10,
+ -25,-10, 0, 25, 25, 0,-10,-25,
+ -50,-25,-10, 0, 0,-10,-25,-50,
+ -50,-50,-25,-10,-10,-25,-50,-50
+ ];
+
+var rookAdj =
+ [ -60, -30, -10, 20, 20, -10, -30, -60,
+ 40, 70, 90,120,120, 90, 70, 40,
+ -60, -30, -10, 20, 20, -10, -30, -60,
+ -60, -30, -10, 20, 20, -10, -30, -60,
+ -60, -30, -10, 20, 20, -10, -30, -60,
+ -60, -30, -10, 20, 20, -10, -30, -60,
+ -60, -30, -10, 20, 20, -10, -30, -60,
+ -60, -30, -10, 20, 20, -10, -30, -60
+ ];
+
+var kingAdj =
+ [ 50, 150, -25, -125, -125, -25, 150, 50,
+ 50, 150, -25, -125, -125, -25, 150, 50,
+ 50, 150, -25, -125, -125, -25, 150, 50,
+ 50, 150, -25, -125, -125, -25, 150, 50,
+ 50, 150, -25, -125, -125, -25, 150, 50,
+ 50, 150, -25, -125, -125, -25, 150, 50,
+ 50, 150, -25, -125, -125, -25, 150, 50,
+ 150, 250, 75, -25, -25, 75, 250, 150
+ ];
+
+var emptyAdj =
+ [0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0,
+ ];
+
+var pieceSquareAdj = new Array(8);
+
+// Returns the square flipped
+var flipTable = new Array(256);
+
+function PawnEval(color) {
+ var pieceIdx = (color | 1) << 4;
+ var from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ from = g_pieceList[pieceIdx++];
+ }
+}
+
+function Mobility(color) {
+ var result = 0;
+ var from, to, mob, pieceIdx;
+ var enemy = color == 8 ? 0x10 : 0x8
+ var mobUnit = color == 8 ? g_mobUnit[0] : g_mobUnit[1];
+
+ // Knight mobility
+ mob = -3;
+ pieceIdx = (color | 2) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ mob += mobUnit[g_board[from + 31]];
+ mob += mobUnit[g_board[from + 33]];
+ mob += mobUnit[g_board[from + 14]];
+ mob += mobUnit[g_board[from - 14]];
+ mob += mobUnit[g_board[from - 31]];
+ mob += mobUnit[g_board[from - 33]];
+ mob += mobUnit[g_board[from + 18]];
+ mob += mobUnit[g_board[from - 18]];
+ from = g_pieceList[pieceIdx++];
+ }
+ result += 65 * mob;
+
+ // Bishop mobility
+ mob = -4;
+ pieceIdx = (color | 3) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from - 15; while (g_board[to] == 0) { to -= 15; mob++; }
+ if (g_board[to] & enemy) {
+ mob++;
+ if (!(g_board[to] & piecePawn)) {
+ to -= 15; while (g_board[to] == 0) to -= 15;
+ mob += mobUnit[g_board[to]] << 2;
+ }
+ }
+
+ to = from - 17; while (g_board[to] == 0) { to -= 17; mob++; }
+ if (g_board[to] & enemy) {
+ mob++;
+ if (!(g_board[to] & piecePawn)) {
+ to -= 17; while (g_board[to] == 0) to -= 17;
+ mob += mobUnit[g_board[to]] << 2;
+ }
+ }
+
+ to = from + 15; while (g_board[to] == 0) { to += 15; mob++; }
+ if (g_board[to] & enemy) {
+ mob++;
+ if (!(g_board[to] & piecePawn)) {
+ to += 15; while (g_board[to] == 0) to += 15;
+ mob += mobUnit[g_board[to]] << 2;
+ }
+ }
+
+ to = from + 17; while (g_board[to] == 0) { to += 17; mob++; }
+ if (g_board[to] & enemy) {
+ mob++;
+ if (!(g_board[to] & piecePawn)) {
+ to += 17; while (g_board[to] == 0) to += 17;
+ mob += mobUnit[g_board[to]] << 2;
+ }
+ }
+
+ from = g_pieceList[pieceIdx++];
+ }
+ result += 44 * mob;
+
+ // Rook mobility
+ mob = -4;
+ pieceIdx = (color | 4) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from - 1; while (g_board[to] == 0) { to--; mob++;} if (g_board[to] & enemy) mob++;
+ to = from + 1; while (g_board[to] == 0) { to++; mob++; } if (g_board[to] & enemy) mob++;
+ to = from + 16; while (g_board[to] == 0) { to += 16; mob++; } if (g_board[to] & enemy) mob++;
+ to = from - 16; while (g_board[to] == 0) { to -= 16; mob++; } if (g_board[to] & enemy) mob++;
+ from = g_pieceList[pieceIdx++];
+ }
+ result += 25 * mob;
+
+ // Queen mobility
+ mob = -2;
+ pieceIdx = (color | 5) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from - 15; while (g_board[to] == 0) { to -= 15; mob++; } if (g_board[to] & enemy) mob++;
+ to = from - 17; while (g_board[to] == 0) { to -= 17; mob++; } if (g_board[to] & enemy) mob++;
+ to = from + 15; while (g_board[to] == 0) { to += 15; mob++; } if (g_board[to] & enemy) mob++;
+ to = from + 17; while (g_board[to] == 0) { to += 17; mob++; } if (g_board[to] & enemy) mob++;
+ to = from - 1; while (g_board[to] == 0) { to--; mob++; } if (g_board[to] & enemy) mob++;
+ to = from + 1; while (g_board[to] == 0) { to++; mob++; } if (g_board[to] & enemy) mob++;
+ to = from + 16; while (g_board[to] == 0) { to += 16; mob++; } if (g_board[to] & enemy) mob++;
+ to = from - 16; while (g_board[to] == 0) { to -= 16; mob++; } if (g_board[to] & enemy) mob++;
+ from = g_pieceList[pieceIdx++];
+ }
+ result += 22 * mob;
+
+ return result;
+}
+
+function Evaluate() {
+ var curEval = g_baseEval;
+
+ var evalAdjust = 0;
+ // Black queen gone, then cancel white's penalty for king movement
+ if (g_pieceList[pieceQueen << 4] == 0)
+ evalAdjust -= pieceSquareAdj[pieceKing][g_pieceList[(colorWhite | pieceKing) << 4]];
+ // White queen gone, then cancel black's penalty for king movement
+ if (g_pieceList[(colorWhite | pieceQueen) << 4] == 0)
+ evalAdjust += pieceSquareAdj[pieceKing][flipTable[g_pieceList[pieceKing << 4]]];
+
+ // Black bishop pair
+ if (g_pieceCount[pieceBishop] >= 2)
+ evalAdjust -= 500;
+ // White bishop pair
+ if (g_pieceCount[pieceBishop | colorWhite] >= 2)
+ evalAdjust += 500;
+
+ var mobility = Mobility(8) - Mobility(0);
+
+ if (g_toMove == 0) {
+ // Black
+ curEval -= mobility;
+ curEval -= evalAdjust;
+ }
+ else {
+ curEval += mobility;
+ curEval += evalAdjust;
+ }
+
+ return curEval;
+}
+
+function ScoreMove(move){
+ var moveTo = (move >> 8) & 0xFF;
+ var captured = g_board[moveTo] & 0x7;
+ var piece = g_board[move & 0xFF];
+ var score;
+ if (captured != 0) {
+ var pieceType = piece & 0x7;
+ score = (captured << 5) - pieceType;
+ } else {
+ score = historyTable[piece & 0xF][moveTo];
+ }
+ return score;
+}
+
+function QSearch(alpha, beta, ply) {
+ g_qNodeCount++;
+
+ var realEval = g_inCheck ? (minEval + 1) : Evaluate();
+
+ if (realEval >= beta)
+ return realEval;
+
+ if (realEval > alpha)
+ alpha = realEval;
+
+ var moves = new Array();
+ var moveScores = new Array();
+ var wasInCheck = g_inCheck;
+
+ if (wasInCheck) {
+ // TODO: Fast check escape generator and fast checking moves generator
+ GenerateCaptureMoves(moves, null);
+ GenerateAllMoves(moves);
+
+ for (var i = 0; i < moves.length; i++) {
+ moveScores[i] = ScoreMove(moves[i]);
+ }
+ } else {
+ GenerateCaptureMoves(moves, null);
+
+ for (var i = 0; i < moves.length; i++) {
+ var captured = g_board[(moves[i] >> 8) & 0xFF] & 0x7;
+ var pieceType = g_board[moves[i] & 0xFF] & 0x7;
+
+ moveScores[i] = (captured << 5) - pieceType;
+ }
+ }
+
+ for (var i = 0; i < moves.length; i++) {
+ var bestMove = i;
+ for (var j = moves.length - 1; j > i; j--) {
+ if (moveScores[j] > moveScores[bestMove]) {
+ bestMove = j;
+ }
+ }
+ {
+ var tmpMove = moves[i];
+ moves[i] = moves[bestMove];
+ moves[bestMove] = tmpMove;
+
+ var tmpScore = moveScores[i];
+ moveScores[i] = moveScores[bestMove];
+ moveScores[bestMove] = tmpScore;
+ }
+
+ if (!wasInCheck && !See(moves[i])) {
+ continue;
+ }
+
+ if (!MakeMove(moves[i])) {
+ continue;
+ }
+
+ var value = -QSearch(-beta, -alpha, ply - 1);
+
+ UnmakeMove(moves[i]);
+
+ if (value > realEval) {
+ if (value >= beta)
+ return value;
+
+ if (value > alpha)
+ alpha = value;
+
+ realEval = value;
+ }
+ }
+
+ /* Disable checks... Too slow currently
+
+ if (ply == 0 && !wasInCheck) {
+ moves = new Array();
+ GenerateAllMoves(moves);
+
+ for (var i = 0; i < moves.length; i++) {
+ moveScores[i] = ScoreMove(moves[i]);
+ }
+
+ for (var i = 0; i < moves.length; i++) {
+ var bestMove = i;
+ for (var j = moves.length - 1; j > i; j--) {
+ if (moveScores[j] > moveScores[bestMove]) {
+ bestMove = j;
+ }
+ }
+ {
+ var tmpMove = moves[i];
+ moves[i] = moves[bestMove];
+ moves[bestMove] = tmpMove;
+
+ var tmpScore = moveScores[i];
+ moveScores[i] = moveScores[bestMove];
+ moveScores[bestMove] = tmpScore;
+ }
+
+ if (!MakeMove(moves[i])) {
+ continue;
+ }
+ var checking = g_inCheck;
+ UnmakeMove(moves[i]);
+
+ if (!checking) {
+ continue;
+ }
+
+ if (!See(moves[i])) {
+ continue;
+ }
+
+ MakeMove(moves[i]);
+
+ var value = -QSearch(-beta, -alpha, ply - 1);
+
+ UnmakeMove(moves[i]);
+
+ if (value > realEval) {
+ if (value >= beta)
+ return value;
+
+ if (value > alpha)
+ alpha = value;
+
+ realEval = value;
+ }
+ }
+ }
+ */
+
+ return realEval;
+}
+
+function StoreHash(value, flags, ply, move, depth) {
+ if (value >= maxMateBuffer)
+ value += depth;
+ else if (value <= minMateBuffer)
+ value -= depth;
+ g_hashTable[g_hashKeyLow & g_hashMask] = new HashEntry(g_hashKeyHigh, value, flags, ply, move);
+}
+
+function IsHashMoveValid(hashMove) {
+ var from = hashMove & 0xFF;
+ var to = (hashMove >> 8) & 0xFF;
+ var ourPiece = g_board[from];
+ var pieceType = ourPiece & 0x7;
+ if (pieceType < piecePawn || pieceType > pieceKing) return false;
+ // Can't move a piece we don't control
+ if (g_toMove != (ourPiece & 0x8))
+ return false;
+ // Can't move to a square that has something of the same color
+ if (g_board[to] != 0 && (g_toMove == (g_board[to] & 0x8)))
+ return false;
+ if (pieceType == piecePawn) {
+ if (hashMove & moveflagEPC) {
+ return false;
+ }
+
+ // Valid moves are push, capture, double push, promotions
+ var dir = to - from;
+ if ((g_toMove == colorWhite) != (dir < 0)) {
+ // Pawns have to move in the right direction
+ return false;
+ }
+
+ var row = to & 0xF0;
+ if (((row == 0x90 && !g_toMove) ||
+ (row == 0x20 && g_toMove)) != (hashMove & moveflagPromotion)) {
+ // Handle promotions
+ return false;
+ }
+
+ if (dir == -16 || dir == 16) {
+ // White/Black push
+ return g_board[to] == 0;
+ } else if (dir == -15 || dir == -17 || dir == 15 || dir == 17) {
+ // White/Black capture
+ return g_board[to] != 0;
+ } else if (dir == -32) {
+ // Double white push
+ if (row != 0x60) return false;
+ if (g_board[to] != 0) return false;
+ if (g_board[from - 16] != 0) return false;
+ } else if (dir == 32) {
+ // Double black push
+ if (row != 0x50) return false;
+ if (g_board[to] != 0) return false;
+ if (g_board[from + 16] != 0) return false;
+ } else {
+ return false;
+ }
+
+ return true;
+ } else {
+ // This validates that this piece type can actually make the attack
+ if (hashMove >> 16) return false;
+ return IsSquareAttackableFrom(to, from);
+ }
+}
+
+function IsRepDraw() {
+ var stop = g_moveCount - 1 - g_move50;
+ stop = stop < 0 ? 0 : stop;
+ for (var i = g_moveCount - 5; i >= stop; i -= 2) {
+ if (g_repMoveStack[i] == g_hashKeyLow)
+ return true;
+ }
+ return false;
+}
+
+function MovePicker(hashMove, depth, killer1, killer2) {
+ this.hashMove = hashMove;
+ this.depth = depth;
+ this.killer1 = killer1;
+ this.killer2 = killer2;
+
+ this.moves = new Array();
+ this.losingCaptures = null;
+ this.moveCount = 0;
+ this.atMove = -1;
+ this.moveScores = null;
+ this.stage = 0;
+
+ this.nextMove = function () {
+ if (++this.atMove == this.moveCount) {
+ this.stage++;
+ if (this.stage == 1) {
+ if (this.hashMove != null && IsHashMoveValid(hashMove)) {
+ this.moves[0] = hashMove;
+ this.moveCount = 1;
+ }
+ if (this.moveCount != 1) {
+ this.hashMove = null;
+ this.stage++;
+ }
+ }
+
+ if (this.stage == 2) {
+ GenerateCaptureMoves(this.moves, null);
+ this.moveCount = this.moves.length;
+ this.moveScores = new Array(this.moveCount);
+ // Move ordering
+ for (var i = this.atMove; i < this.moveCount; i++) {
+ var captured = g_board[(this.moves[i] >> 8) & 0xFF] & 0x7;
+ var pieceType = g_board[this.moves[i] & 0xFF] & 0x7;
+ this.moveScores[i] = (captured << 5) - pieceType;
+ }
+ // No moves, onto next stage
+ if (this.atMove == this.moveCount) this.stage++;
+ }
+
+ if (this.stage == 3) {
+ if (IsHashMoveValid(this.killer1) &&
+ this.killer1 != this.hashMove) {
+ this.moves[this.moves.length] = this.killer1;
+ this.moveCount = this.moves.length;
+ } else {
+ this.killer1 = 0;
+ this.stage++;
+ }
+ }
+
+ if (this.stage == 4) {
+ if (IsHashMoveValid(this.killer2) &&
+ this.killer2 != this.hashMove) {
+ this.moves[this.moves.length] = this.killer2;
+ this.moveCount = this.moves.length;
+ } else {
+ this.killer2 = 0;
+ this.stage++;
+ }
+ }
+
+ if (this.stage == 5) {
+ GenerateAllMoves(this.moves);
+ this.moveCount = this.moves.length;
+ // Move ordering
+ for (var i = this.atMove; i < this.moveCount; i++) this.moveScores[i] = ScoreMove(this.moves[i]);
+ // No moves, onto next stage
+ if (this.atMove == this.moveCount) this.stage++;
+ }
+
+ if (this.stage == 6) {
+ // Losing captures
+ if (this.losingCaptures != null) {
+ for (var i = 0; i < this.losingCaptures.length; i++) {
+ this.moves[this.moves.length] = this.losingCaptures[i];
+ }
+ for (var i = this.atMove; i < this.moveCount; i++) this.moveScores[i] = ScoreMove(this.moves[i]);
+ this.moveCount = this.moves.length;
+ }
+ // No moves, onto next stage
+ if (this.atMove == this.moveCount) this.stage++;
+ }
+
+ if (this.stage == 7)
+ return 0;
+ }
+
+ var bestMove = this.atMove;
+ for (var j = this.atMove + 1; j < this.moveCount; j++) {
+ if (this.moveScores[j] > this.moveScores[bestMove]) {
+ bestMove = j;
+ }
+ }
+
+ if (bestMove != this.atMove) {
+ var tmpMove = this.moves[this.atMove];
+ this.moves[this.atMove] = this.moves[bestMove];
+ this.moves[bestMove] = tmpMove;
+
+ var tmpScore = this.moveScores[this.atMove];
+ this.moveScores[this.atMove] = this.moveScores[bestMove];
+ this.moveScores[bestMove] = tmpScore;
+ }
+
+ var candidateMove = this.moves[this.atMove];
+ if ((this.stage > 1 && candidateMove == this.hashMove) ||
+ (this.stage > 3 && candidateMove == this.killer1) ||
+ (this.stage > 4 && candidateMove == this.killer2)) {
+ return this.nextMove();
+ }
+
+ if (this.stage == 2 && !See(candidateMove)) {
+ if (this.losingCaptures == null) {
+ this.losingCaptures = new Array();
+ }
+ this.losingCaptures[this.losingCaptures.length] = candidateMove;
+ return this.nextMove();
+ }
+
+ return this.moves[this.atMove];
+ }
+}
+
+function AllCutNode(ply, depth, beta, allowNull) {
+ if (ply <= 0) {
+ return QSearch(beta - 1, beta, 0);
+ }
+
+ if ((g_nodeCount & 127) == 127) {
+ if ((new Date()).getTime() - g_startTime > g_timeout) {
+ // Time cutoff
+ g_searchValid = false;
+ return beta - 1;
+ }
+ }
+
+ g_nodeCount++;
+
+ if (IsRepDraw())
+ return 0;
+
+ // Mate distance pruning
+ if (minEval + depth >= beta)
+ return beta;
+
+ if (maxEval - (depth + 1) < beta)
+ return beta - 1;
+
+ var hashMove = null;
+ var hashNode = g_hashTable[g_hashKeyLow & g_hashMask];
+ if (hashNode != null && hashNode.lock == g_hashKeyHigh) {
+ hashMove = hashNode.bestMove;
+ if (hashNode.hashDepth >= ply) {
+ var hashValue = hashNode.value;
+
+ // Fixup mate scores
+ if (hashValue >= maxMateBuffer)
+ hashValue -= depth;
+ else if (hashValue <= minMateBuffer)
+ hashValue += depth;
+
+ if (hashNode.flags == hashflagExact)
+ return hashValue;
+ if (hashNode.flags == hashflagAlpha && hashValue < beta)
+ return hashValue;
+ if (hashNode.flags == hashflagBeta && hashValue >= beta)
+ return hashValue;
+ }
+ }
+
+ // TODO - positional gain?
+
+ if (!g_inCheck &&
+ allowNull &&
+ beta > minMateBuffer &&
+ beta < maxMateBuffer) {
+ // Try some razoring
+ if (hashMove == null &&
+ ply < 4) {
+ var razorMargin = 2500 + 200 * ply;
+ if (g_baseEval < beta - razorMargin) {
+ var razorBeta = beta - razorMargin;
+ var v = QSearch(razorBeta - 1, razorBeta, 0);
+ if (v < razorBeta)
+ return v;
+ }
+ }
+
+ // TODO - static null move
+
+ // Null move
+ if (ply > 1 &&
+ g_baseEval >= beta - (ply >= 4 ? 2500 : 0) &&
+ // Disable null move if potential zugzwang (no big pieces)
+ (g_pieceCount[pieceBishop | g_toMove] != 0 ||
+ g_pieceCount[pieceKnight | g_toMove] != 0 ||
+ g_pieceCount[pieceRook | g_toMove] != 0 ||
+ g_pieceCount[pieceQueen | g_toMove] != 0)) {
+ var r = 3 + (ply >= 5 ? 1 : ply / 4);
+ if (g_baseEval - beta > 1500) r++;
+
+ g_toMove = 8 - g_toMove;
+ g_baseEval = -g_baseEval;
+ g_hashKeyLow ^= g_zobristBlackLow;
+ g_hashKeyHigh ^= g_zobristBlackHigh;
+
+ var value = -AllCutNode(ply - r, depth + 1, -(beta - 1), false);
+
+ g_hashKeyLow ^= g_zobristBlackLow;
+ g_hashKeyHigh ^= g_zobristBlackHigh;
+ g_toMove = 8 - g_toMove;
+ g_baseEval = -g_baseEval;
+
+ if (value >= beta)
+ return beta;
+ }
+ }
+
+ var moveMade = false;
+ var realEval = minEval - 1;
+ var inCheck = g_inCheck;
+
+ var movePicker = new MovePicker(hashMove, depth, g_killers[depth][0], g_killers[depth][1]);
+
+ for (;;) {
+ var currentMove = movePicker.nextMove();
+ if (currentMove == 0) {
+ break;
+ }
+
+ var plyToSearch = ply - 1;
+
+ if (!MakeMove(currentMove)) {
+ continue;
+ }
+
+ var value;
+ var doFullSearch = true;
+
+ if (g_inCheck) {
+ // Check extensions
+ plyToSearch++;
+ } else {
+ var reduced = plyToSearch - (movePicker.atMove > 14 ? 2 : 1);
+
+ // Futility pruning
+/* if (movePicker.stage == 5 && !inCheck) {
+ if (movePicker.atMove >= (15 + (1 << (5 * ply) >> 2)) &&
+ realEval > minMateBuffer) {
+ UnmakeMove(currentMove);
+ continue;
+ }
+
+ if (ply < 7) {
+ var reducedPly = reduced <= 0 ? 0 : reduced;
+ var futilityValue = -g_baseEval + (900 * (reducedPly + 2)) - (movePicker.atMove * 10);
+ if (futilityValue < beta) {
+ if (futilityValue > realEval) {
+ realEval = futilityValue;
+ }
+ UnmakeMove(currentMove);
+ continue;
+ }
+ }
+ }*/
+
+ // Late move reductions
+ if (movePicker.stage == 5 && movePicker.atMove > 5 && ply >= 3) {
+ value = -AllCutNode(reduced, depth + 1, -(beta - 1), true);
+ doFullSearch = (value >= beta);
+ }
+ }
+
+ if (doFullSearch) {
+ value = -AllCutNode(plyToSearch, depth + 1, -(beta - 1), true);
+ }
+
+ moveMade = true;
+
+ UnmakeMove(currentMove);
+
+ if (!g_searchValid) {
+ return beta - 1;
+ }
+
+ if (value > realEval) {
+ if (value >= beta) {
+ var histTo = (currentMove >> 8) & 0xFF;
+ if (g_board[histTo] == 0) {
+ var histPiece = g_board[currentMove & 0xFF] & 0xF;
+ historyTable[histPiece][histTo] += ply * ply;
+ if (historyTable[histPiece][histTo] > 32767) {
+ historyTable[histPiece][histTo] >>= 1;
+ }
+
+ if (g_killers[depth][0] != currentMove) {
+ g_killers[depth][1] = g_killers[depth][0];
+ g_killers[depth][0] = currentMove;
+ }
+ }
+
+ StoreHash(value, hashflagBeta, ply, currentMove, depth);
+ return value;
+ }
+
+ realEval = value;
+ hashMove = currentMove;
+ }
+ }
+
+ if (!moveMade) {
+ // If we have no valid moves it's either stalemate or checkmate
+ if (g_inCheck)
+ // Checkmate.
+ return minEval + depth;
+ else
+ // Stalemate
+ return 0;
+ }
+
+ StoreHash(realEval, hashflagAlpha, ply, hashMove, depth);
+
+ return realEval;
+}
+
+function AlphaBeta(ply, depth, alpha, beta) {
+ if (ply <= 0) {
+ return QSearch(alpha, beta, 0);
+ }
+
+ g_nodeCount++;
+
+ if (depth > 0 && IsRepDraw())
+ return 0;
+
+ // Mate distance pruning
+ var oldAlpha = alpha;
+ alpha = alpha < minEval + depth ? alpha : minEval + depth;
+ beta = beta > maxEval - (depth + 1) ? beta : maxEval - (depth + 1);
+ if (alpha >= beta)
+ return alpha;
+
+ var hashMove = null;
+ var hashFlag = hashflagAlpha;
+ var hashNode = g_hashTable[g_hashKeyLow & g_hashMask];
+ if (hashNode != null && hashNode.lock == g_hashKeyHigh) {
+ hashMove = hashNode.bestMove;
+ }
+
+ var inCheck = g_inCheck;
+
+ var moveMade = false;
+ var realEval = minEval;
+
+ var movePicker = new MovePicker(hashMove, depth, g_killers[depth][0], g_killers[depth][1]);
+
+ for (;;) {
+ var currentMove = movePicker.nextMove();
+ if (currentMove == 0) {
+ break;
+ }
+
+ var plyToSearch = ply - 1;
+
+ if (!MakeMove(currentMove)) {
+ continue;
+ }
+
+ if (g_inCheck) {
+ // Check extensions
+ plyToSearch++;
+ }
+
+ var value;
+ if (moveMade) {
+ value = -AllCutNode(plyToSearch, depth + 1, -alpha, true);
+ if (value > alpha) {
+ value = -AlphaBeta(plyToSearch, depth + 1, -beta, -alpha);
+ }
+ } else {
+ value = -AlphaBeta(plyToSearch, depth + 1, -beta, -alpha);
+ }
+
+ moveMade = true;
+
+ UnmakeMove(currentMove);
+
+ if (!g_searchValid) {
+ return alpha;
+ }
+
+ if (value > realEval) {
+ if (value >= beta) {
+ var histTo = (currentMove >> 8) & 0xFF;
+ if (g_board[histTo] == 0) {
+ var histPiece = g_board[currentMove & 0xFF] & 0xF;
+ historyTable[histPiece][histTo] += ply * ply;
+ if (historyTable[histPiece][histTo] > 32767) {
+ historyTable[histPiece][histTo] >>= 1;
+ }
+
+ if (g_killers[depth][0] != currentMove) {
+ g_killers[depth][1] = g_killers[depth][0];
+ g_killers[depth][0] = currentMove;
+ }
+ }
+
+ StoreHash(value, hashflagBeta, ply, currentMove, depth);
+ return value;
+ }
+
+ if (value > oldAlpha) {
+ hashFlag = hashflagExact;
+ alpha = value;
+ }
+
+ realEval = value;
+ hashMove = currentMove;
+ }
+ }
+
+ if (!moveMade) {
+ // If we have no valid moves it's either stalemate or checkmate
+ if (inCheck)
+ // Checkmate.
+ return minEval + depth;
+ else
+ // Stalemate
+ return 0;
+ }
+
+ StoreHash(realEval, hashFlag, ply, hashMove, depth);
+
+ return realEval;
+}
+
+//
+// Board code
+//
+
+// This somewhat funky scheme means that a piece is indexed by it's lower 4 bits when accessing in arrays. The fifth bit (black bit)
+// is used to allow quick edge testing on the board.
+var colorBlack = 0x10;
+var colorWhite = 0x08;
+
+var pieceEmpty = 0x00;
+var piecePawn = 0x01;
+var pieceKnight = 0x02;
+var pieceBishop = 0x03;
+var pieceRook = 0x04;
+var pieceQueen = 0x05;
+var pieceKing = 0x06;
+
+var g_vectorDelta = new Array(256);
+
+var g_bishopDeltas = [-15, -17, 15, 17];
+var g_knightDeltas = [31, 33, 14, -14, -31, -33, 18, -18];
+var g_rookDeltas = [-1, +1, -16, +16];
+var g_queenDeltas = [-1, +1, -15, +15, -17, +17, -16, +16];
+
+var g_castleRightsMask = [
+0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+0, 0, 0, 0, 7,15,15,15, 3,15,15,11, 0, 0, 0, 0,
+0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
+0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
+0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
+0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
+0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
+0, 0, 0, 0,15,15,15,15,15,15,15,15, 0, 0, 0, 0,
+0, 0, 0, 0,13,15,15,15,12,15,15,14, 0, 0, 0, 0,
+0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
+
+var moveflagEPC = 0x2 << 16;
+var moveflagCastleKing = 0x4 << 16;
+var moveflagCastleQueen = 0x8 << 16;
+var moveflagPromotion = 0x10 << 16;
+var moveflagPromoteKnight = 0x20 << 16;
+var moveflagPromoteQueen = 0x40 << 16;
+var moveflagPromoteBishop = 0x80 << 16;
+
+function MT() {
+ var N = 624;
+ var M = 397;
+ var MAG01 = [0x0, 0x9908b0df];
+
+ this.mt = new Array(N);
+ this.mti = N + 1;
+
+ this.setSeed = function()
+ {
+ var a = arguments;
+ switch (a.length) {
+ case 1:
+ if (a[0].constructor === Number) {
+ this.mt[0]= a[0];
+ for (var i = 1; i < N; ++i) {
+ var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
+ this.mt[i] = ((1812433253 * ((s & 0xffff0000) >>> 16))
+ << 16)
+ + 1812433253 * (s & 0x0000ffff)
+ + i;
+ }
+ this.mti = N;
+ return;
+ }
+
+ this.setSeed(19650218);
+
+ var l = a[0].length;
+ var i = 1;
+ var j = 0;
+
+ for (var k = N > l ? N : l; k != 0; --k) {
+ var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30)
+ this.mt[i] = (this.mt[i]
+ ^ (((1664525 * ((s & 0xffff0000) >>> 16)) << 16)
+ + 1664525 * (s & 0x0000ffff)))
+ + a[0][j]
+ + j;
+ if (++i >= N) {
+ this.mt[0] = this.mt[N - 1];
+ i = 1;
+ }
+ if (++j >= l) {
+ j = 0;
+ }
+ }
+
+ for (var k = N - 1; k != 0; --k) {
+ var s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
+ this.mt[i] = (this.mt[i]
+ ^ (((1566083941 * ((s & 0xffff0000) >>> 16)) << 16)
+ + 1566083941 * (s & 0x0000ffff)))
+ - i;
+ if (++i >= N) {
+ this.mt[0] = this.mt[N-1];
+ i = 1;
+ }
+ }
+
+ this.mt[0] = 0x80000000;
+ return;
+ default:
+ var seeds = new Array();
+ for (var i = 0; i < a.length; ++i) {
+ seeds.push(a[i]);
+ }
+ this.setSeed(seeds);
+ return;
+ }
+ }
+
+ this.setSeed(0x1BADF00D);
+
+ this.next = function (bits)
+ {
+ if (this.mti >= N) {
+ var x = 0;
+
+ for (var k = 0; k < N - M; ++k) {
+ x = (this.mt[k] & 0x80000000) | (this.mt[k + 1] & 0x7fffffff);
+ this.mt[k] = this.mt[k + M] ^ (x >>> 1) ^ MAG01[x & 0x1];
+ }
+ for (var k = N - M; k < N - 1; ++k) {
+ x = (this.mt[k] & 0x80000000) | (this.mt[k + 1] & 0x7fffffff);
+ this.mt[k] = this.mt[k + (M - N)] ^ (x >>> 1) ^ MAG01[x & 0x1];
+ }
+ x = (this.mt[N - 1] & 0x80000000) | (this.mt[0] & 0x7fffffff);
+ this.mt[N - 1] = this.mt[M - 1] ^ (x >>> 1) ^ MAG01[x & 0x1];
+
+ this.mti = 0;
+ }
+
+ var y = this.mt[this.mti++];
+ y ^= y >>> 11;
+ y ^= (y << 7) & 0x9d2c5680;
+ y ^= (y << 15) & 0xefc60000;
+ y ^= y >>> 18;
+ return (y >>> (32 - bits)) & 0xFFFFFFFF;
+ }
+}
+
+// Position variables
+var g_board = new Array(256); // Sentinel 0x80, pieces are in low 4 bits, 0x8 for color, 0x7 bits for piece type
+var g_toMove; // side to move, 0 or 8, 0 = black, 8 = white
+var g_castleRights; // bitmask representing castling rights, 1 = wk, 2 = wq, 4 = bk, 8 = bq
+var g_enPassentSquare;
+var g_baseEval;
+var g_hashKeyLow, g_hashKeyHigh;
+var g_inCheck;
+
+// Utility variables
+var g_moveCount = 0;
+var g_moveUndoStack = new Array();
+
+var g_move50 = 0;
+var g_repMoveStack = new Array();
+
+var g_hashSize = 1 << 22;
+var g_hashMask = g_hashSize - 1;
+var g_hashTable;
+
+var g_killers;
+var historyTable = new Array(32);
+
+var g_zobristLow;
+var g_zobristHigh;
+var g_zobristBlackLow;
+var g_zobristBlackHigh;
+
+// Evaulation variables
+var g_mobUnit;
+
+var hashflagAlpha = 1;
+var hashflagBeta = 2;
+var hashflagExact = 3;
+
+function HashEntry(lock, value, flags, hashDepth, bestMove, globalPly) {
+ this.lock = lock;
+ this.value = value;
+ this.flags = flags;
+ this.hashDepth = hashDepth;
+ this.bestMove = bestMove;
+}
+
+function MakeSquare(row, column) {
+ return ((row + 2) << 4) | (column + 4);
+}
+
+function MakeTable(table) {
+ var result = new Array(256);
+ for (var i = 0; i < 256; i++) {
+ result[i] = 0;
+ }
+ for (var row = 0; row < 8; row++) {
+ for (var col = 0; col < 8; col++) {
+ result[MakeSquare(row, col)] = table[row * 8 + col];
+ }
+ }
+ return result;
+}
+
+function ResetGame() {
+ g_killers = new Array(128);
+ for (var i = 0; i < 128; i++) {
+ g_killers[i] = [0, 0];
+ }
+
+ g_hashTable = new Array(g_hashSize);
+
+ for (var i = 0; i < 32; i++) {
+ historyTable[i] = new Array(256);
+ for (var j = 0; j < 256; j++)
+ historyTable[i][j] = 0;
+ }
+
+ var mt = new MT(0x1badf00d);
+
+ g_zobristLow = new Array(256);
+ g_zobristHigh = new Array(256);
+ for (var i = 0; i < 256; i++) {
+ g_zobristLow[i] = new Array(16);
+ g_zobristHigh[i] = new Array(16);
+ for (var j = 0; j < 16; j++) {
+ g_zobristLow[i][j] = mt.next(32);
+ g_zobristHigh[i][j] = mt.next(32);
+ }
+ }
+ g_zobristBlackLow = mt.next(32);
+ g_zobristBlackHigh = mt.next(32);
+
+ for (var row = 0; row < 8; row++) {
+ for (var col = 0; col < 8; col++) {
+ var square = MakeSquare(row, col);
+ flipTable[square] = MakeSquare(7 - row, col);
+ }
+ }
+
+ pieceSquareAdj[piecePawn] = MakeTable(pawnAdj);
+ pieceSquareAdj[pieceKnight] = MakeTable(knightAdj);
+ pieceSquareAdj[pieceBishop] = MakeTable(bishopAdj);
+ pieceSquareAdj[pieceRook] = MakeTable(rookAdj);
+ pieceSquareAdj[pieceQueen] = MakeTable(emptyAdj);
+ pieceSquareAdj[pieceKing] = MakeTable(kingAdj);
+
+ var pieceDeltas = [[], [], g_knightDeltas, g_bishopDeltas, g_rookDeltas, g_queenDeltas, g_queenDeltas];
+
+ for (var i = 0; i < 256; i++) {
+ g_vectorDelta[i] = new Object();
+ g_vectorDelta[i].delta = 0;
+ g_vectorDelta[i].pieceMask = new Array(2);
+ g_vectorDelta[i].pieceMask[0] = 0;
+ g_vectorDelta[i].pieceMask[1] = 0;
+ }
+
+ // Initialize the vector delta table
+ for (var row = 0; row < 0x80; row += 0x10)
+ for (var col = 0; col < 0x8; col++) {
+ var square = row | col;
+
+ // Pawn moves
+ var index = square - (square - 17) + 128;
+ g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << piecePawn);
+ index = square - (square - 15) + 128;
+ g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << piecePawn);
+
+ index = square - (square + 17) + 128;
+ g_vectorDelta[index].pieceMask[0] |= (1 << piecePawn);
+ index = square - (square + 15) + 128;
+ g_vectorDelta[index].pieceMask[0] |= (1 << piecePawn);
+
+ for (var i = pieceKnight; i <= pieceKing; i++) {
+ for (var dir = 0; dir < pieceDeltas[i].length; dir++) {
+ var target = square + pieceDeltas[i][dir];
+ while (!(target & 0x88)) {
+ index = square - target + 128;
+
+ g_vectorDelta[index].pieceMask[colorWhite >> 3] |= (1 << i);
+ g_vectorDelta[index].pieceMask[0] |= (1 << i);
+
+ var flip = -1;
+ if (square < target)
+ flip = 1;
+
+ if ((square & 0xF0) == (target & 0xF0)) {
+ // On the same row
+ g_vectorDelta[index].delta = flip * 1;
+ } else if ((square & 0x0F) == (target & 0x0F)) {
+ // On the same column
+ g_vectorDelta[index].delta = flip * 16;
+ } else if ((square % 15) == (target % 15)) {
+ g_vectorDelta[index].delta = flip * 15;
+ } else if ((square % 17) == (target % 17)) {
+ g_vectorDelta[index].delta = flip * 17;
+ }
+
+ if (i == pieceKnight) {
+ g_vectorDelta[index].delta = pieceDeltas[i][dir];
+ break;
+ }
+
+ if (i == pieceKing)
+ break;
+
+ target += pieceDeltas[i][dir];
+ }
+ }
+ }
+ }
+
+ InitializeEval();
+ InitializeFromFen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
+}
+
+function InitializeEval() {
+ g_mobUnit = new Array(2);
+ for (var i = 0; i < 2; i++) {
+ g_mobUnit[i] = new Array();
+ var enemy = i == 0 ? 0x10 : 8;
+ var friend = i == 0 ? 8 : 0x10;
+ g_mobUnit[i][0] = 1;
+ g_mobUnit[i][0x80] = 0;
+ g_mobUnit[i][enemy | piecePawn] = 1;
+ g_mobUnit[i][enemy | pieceBishop] = 2;
+ g_mobUnit[i][enemy | pieceKnight] = 2;
+ g_mobUnit[i][enemy | pieceRook] = 4;
+ g_mobUnit[i][enemy | pieceQueen] = 6;
+ g_mobUnit[i][enemy | pieceKing] = 6;
+ g_mobUnit[i][friend | piecePawn] = 0;
+ g_mobUnit[i][friend | pieceBishop] = 0;
+ g_mobUnit[i][friend | pieceKnight] = 0;
+ g_mobUnit[i][friend | pieceRook] = 0;
+ g_mobUnit[i][friend | pieceQueen] = 0;
+ g_mobUnit[i][friend | pieceKing] = 0;
+ }
+}
+
+function SetHash() {
+ var result = new Object();
+ result.hashKeyLow = 0;
+ result.hashKeyHigh = 0;
+
+ for (var i = 0; i < 256; i++) {
+ var piece = g_board[i];
+ if (piece & 0x18) {
+ result.hashKeyLow ^= g_zobristLow[i][piece & 0xF]
+ result.hashKeyHigh ^= g_zobristHigh[i][piece & 0xF]
+ }
+ }
+
+ if (!g_toMove) {
+ result.hashKeyLow ^= g_zobristBlackLow;
+ result.hashKeyHigh ^= g_zobristBlackHigh;
+ }
+
+ return result;
+}
+
+function InitializeFromFen(fen) {
+ var chunks = fen.split(' ');
+
+ for (var i = 0; i < 256; i++)
+ g_board[i] = 0x80;
+
+ var row = 0;
+ var col = 0;
+
+ var pieces = chunks[0];
+ for (var i = 0; i < pieces.length; i++) {
+ var c = pieces.charAt(i);
+
+ if (c == '/') {
+ row++;
+ col = 0;
+ }
+ else {
+ if (c >= '0' && c <= '9') {
+ for (var j = 0; j < parseInt(c); j++) {
+ g_board[MakeSquare(row, col)] = 0;
+ col++;
+ }
+ }
+ else {
+ var isBlack = c >= 'a' && c <= 'z';
+ var piece = isBlack ? colorBlack : colorWhite;
+ if (!isBlack)
+ c = pieces.toLowerCase().charAt(i);
+ switch (c) {
+ case 'p':
+ piece |= piecePawn;
+ break;
+ case 'b':
+ piece |= pieceBishop;
+ break;
+ case 'n':
+ piece |= pieceKnight;
+ break;
+ case 'r':
+ piece |= pieceRook;
+ break;
+ case 'q':
+ piece |= pieceQueen;
+ break;
+ case 'k':
+ piece |= pieceKing;
+ break;
+ }
+
+ g_board[MakeSquare(row, col)] = piece;
+ col++;
+ }
+ }
+ }
+
+ InitializePieceList();
+
+ g_toMove = chunks[1].charAt(0) == 'w' ? colorWhite : 0;
+ var them = 8 - g_toMove;
+
+ g_castleRights = 0;
+ if (chunks[2].indexOf('K') != -1) {
+ if (g_board[MakeSquare(7, 4)] != (pieceKing | colorWhite) ||
+ g_board[MakeSquare(7, 7)] != (pieceRook | colorWhite)) {
+ return 'Invalid FEN: White kingside castling not allowed';
+ }
+ g_castleRights |= 1;
+ }
+ if (chunks[2].indexOf('Q') != -1) {
+ if (g_board[MakeSquare(7, 4)] != (pieceKing | colorWhite) ||
+ g_board[MakeSquare(7, 0)] != (pieceRook | colorWhite)) {
+ return 'Invalid FEN: White queenside castling not allowed';
+ }
+ g_castleRights |= 2;
+ }
+ if (chunks[2].indexOf('k') != -1) {
+ if (g_board[MakeSquare(0, 4)] != (pieceKing | colorBlack) ||
+ g_board[MakeSquare(0, 7)] != (pieceRook | colorBlack)) {
+ return 'Invalid FEN: Black kingside castling not allowed';
+ }
+ g_castleRights |= 4;
+ }
+ if (chunks[2].indexOf('q') != -1) {
+ if (g_board[MakeSquare(0, 4)] != (pieceKing | colorBlack) ||
+ g_board[MakeSquare(0, 0)] != (pieceRook | colorBlack)) {
+ return 'Invalid FEN: Black queenside castling not allowed';
+ }
+ g_castleRights |= 8;
+ }
+
+ g_enPassentSquare = -1;
+ if (chunks[3].indexOf('-') == -1) {
+ var col = chunks[3].charAt(0).charCodeAt() - 'a'.charCodeAt();
+ var row = 8 - (chunks[3].charAt(1).charCodeAt() - '0'.charCodeAt());
+ g_enPassentSquare = MakeSquare(row, col);
+ }
+
+ var hashResult = SetHash();
+ g_hashKeyLow = hashResult.hashKeyLow;
+ g_hashKeyHigh = hashResult.hashKeyHigh;
+
+ g_baseEval = 0;
+ for (var i = 0; i < 256; i++) {
+ if (g_board[i] & colorWhite) {
+ g_baseEval += pieceSquareAdj[g_board[i] & 0x7][i];
+ g_baseEval += materialTable[g_board[i] & 0x7];
+ } else if (g_board[i] & colorBlack) {
+ g_baseEval -= pieceSquareAdj[g_board[i] & 0x7][flipTable[i]];
+ g_baseEval -= materialTable[g_board[i] & 0x7];
+ }
+ }
+ if (!g_toMove) g_baseEval = -g_baseEval;
+
+ g_move50 = 0;
+ g_inCheck = IsSquareAttackable(g_pieceList[(g_toMove | pieceKing) << 4], them);
+
+ // Check for king capture (invalid FEN)
+ if (IsSquareAttackable(g_pieceList[(them | pieceKing) << 4], g_toMove)) {
+ return 'Invalid FEN: Can capture king';
+ }
+
+ // Checkmate/stalemate
+ if (GenerateValidMoves().length == 0) {
+ return g_inCheck ? 'Checkmate' : 'Stalemate';
+ }
+
+ return '';
+}
+
+var g_pieceIndex = new Array(256);
+var g_pieceList = new Array(2 * 8 * 16);
+var g_pieceCount = new Array(2 * 8);
+
+function InitializePieceList() {
+ for (var i = 0; i < 16; i++) {
+ g_pieceCount[i] = 0;
+ for (var j = 0; j < 16; j++) {
+ // 0 is used as the terminator for piece lists
+ g_pieceList[(i << 4) | j] = 0;
+ }
+ }
+
+ for (var i = 0; i < 256; i++) {
+ g_pieceIndex[i] = 0;
+ if (g_board[i] & (colorWhite | colorBlack)) {
+ var piece = g_board[i] & 0xF;
+
+ g_pieceList[(piece << 4) | g_pieceCount[piece]] = i;
+ g_pieceIndex[i] = g_pieceCount[piece];
+ g_pieceCount[piece]++;
+ }
+ }
+}
+
+function MakeMove(move){
+ var me = g_toMove >> 3;
+ var otherColor = 8 - g_toMove;
+
+ var flags = move & 0xFF0000;
+ var to = (move >> 8) & 0xFF;
+ var from = move & 0xFF;
+ var captured = g_board[to];
+ var piece = g_board[from];
+ var epcEnd = to;
+
+ if (flags & moveflagEPC) {
+ epcEnd = me ? (to + 0x10) : (to - 0x10);
+ captured = g_board[epcEnd];
+ g_board[epcEnd] = pieceEmpty;
+ }
+
+ g_moveUndoStack[g_moveCount] = new UndoHistory(g_enPassentSquare, g_castleRights, g_inCheck, g_baseEval, g_hashKeyLow, g_hashKeyHigh, g_move50, captured);
+ g_moveCount++;
+
+ g_enPassentSquare = -1;
+
+ if (flags) {
+ if (flags & moveflagCastleKing) {
+ if (IsSquareAttackable(from + 1, otherColor) ||
+ IsSquareAttackable(from + 2, otherColor)) {
+ g_moveCount--;
+ return false;
+ }
+
+ var rook = g_board[to + 1];
+
+ g_hashKeyLow ^= g_zobristLow[to + 1][rook & 0xF];
+ g_hashKeyHigh ^= g_zobristHigh[to + 1][rook & 0xF];
+ g_hashKeyLow ^= g_zobristLow[to - 1][rook & 0xF];
+ g_hashKeyHigh ^= g_zobristHigh[to - 1][rook & 0xF];
+
+ g_board[to - 1] = rook;
+ g_board[to + 1] = pieceEmpty;
+
+ g_baseEval -= pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to + 1] : (to + 1)];
+ g_baseEval += pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to - 1] : (to - 1)];
+
+ var rookIndex = g_pieceIndex[to + 1];
+ g_pieceIndex[to - 1] = rookIndex;
+ g_pieceList[((rook & 0xF) << 4) | rookIndex] = to - 1;
+ } else if (flags & moveflagCastleQueen) {
+ if (IsSquareAttackable(from - 1, otherColor) ||
+ IsSquareAttackable(from - 2, otherColor)) {
+ g_moveCount--;
+ return false;
+ }
+
+ var rook = g_board[to - 2];
+
+ g_hashKeyLow ^= g_zobristLow[to -2][rook & 0xF];
+ g_hashKeyHigh ^= g_zobristHigh[to - 2][rook & 0xF];
+ g_hashKeyLow ^= g_zobristLow[to + 1][rook & 0xF];
+ g_hashKeyHigh ^= g_zobristHigh[to + 1][rook & 0xF];
+
+ g_board[to + 1] = rook;
+ g_board[to - 2] = pieceEmpty;
+
+ g_baseEval -= pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to - 2] : (to - 2)];
+ g_baseEval += pieceSquareAdj[rook & 0x7][me == 0 ? flipTable[to + 1] : (to + 1)];
+
+ var rookIndex = g_pieceIndex[to - 2];
+ g_pieceIndex[to + 1] = rookIndex;
+ g_pieceList[((rook & 0xF) << 4) | rookIndex] = to + 1;
+ }
+ }
+
+ if (captured) {
+ // Remove our piece from the piece list
+ var capturedType = captured & 0xF;
+ g_pieceCount[capturedType]--;
+ var lastPieceSquare = g_pieceList[(capturedType << 4) | g_pieceCount[capturedType]];
+ g_pieceIndex[lastPieceSquare] = g_pieceIndex[epcEnd];
+ g_pieceList[(capturedType << 4) | g_pieceIndex[lastPieceSquare]] = lastPieceSquare;
+ g_pieceList[(capturedType << 4) | g_pieceCount[capturedType]] = 0;
+
+ g_baseEval += materialTable[captured & 0x7];
+ g_baseEval += pieceSquareAdj[captured & 0x7][me ? flipTable[epcEnd] : epcEnd];
+
+ g_hashKeyLow ^= g_zobristLow[epcEnd][capturedType];
+ g_hashKeyHigh ^= g_zobristHigh[epcEnd][capturedType];
+ g_move50 = 0;
+ } else if ((piece & 0x7) == piecePawn) {
+ var diff = to - from;
+ if (diff < 0) diff = -diff;
+ if (diff > 16) {
+ g_enPassentSquare = me ? (to + 0x10) : (to - 0x10);
+ }
+ g_move50 = 0;
+ }
+
+ g_hashKeyLow ^= g_zobristLow[from][piece & 0xF];
+ g_hashKeyHigh ^= g_zobristHigh[from][piece & 0xF];
+ g_hashKeyLow ^= g_zobristLow[to][piece & 0xF];
+ g_hashKeyHigh ^= g_zobristHigh[to][piece & 0xF];
+ g_hashKeyLow ^= g_zobristBlackLow;
+ g_hashKeyHigh ^= g_zobristBlackHigh;
+
+ g_castleRights &= g_castleRightsMask[from] & g_castleRightsMask[to];
+
+ g_baseEval -= pieceSquareAdj[piece & 0x7][me == 0 ? flipTable[from] : from];
+
+ // Move our piece in the piece list
+ g_pieceIndex[to] = g_pieceIndex[from];
+ g_pieceList[((piece & 0xF) << 4) | g_pieceIndex[to]] = to;
+
+ if (flags & moveflagPromotion) {
+ var newPiece = piece & (~0x7);
+ if (flags & moveflagPromoteKnight)
+ newPiece |= pieceKnight;
+ else if (flags & moveflagPromoteQueen)
+ newPiece |= pieceQueen;
+ else if (flags & moveflagPromoteBishop)
+ newPiece |= pieceBishop;
+ else
+ newPiece |= pieceRook;
+
+ g_hashKeyLow ^= g_zobristLow[to][piece & 0xF];
+ g_hashKeyHigh ^= g_zobristHigh[to][piece & 0xF];
+ g_board[to] = newPiece;
+ g_hashKeyLow ^= g_zobristLow[to][newPiece & 0xF];
+ g_hashKeyHigh ^= g_zobristHigh[to][newPiece & 0xF];
+
+ g_baseEval += pieceSquareAdj[newPiece & 0x7][me == 0 ? flipTable[to] : to];
+ g_baseEval -= materialTable[piecePawn];
+ g_baseEval += materialTable[newPiece & 0x7];
+
+ var pawnType = piece & 0xF;
+ var promoteType = newPiece & 0xF;
+
+ g_pieceCount[pawnType]--;
+
+ var lastPawnSquare = g_pieceList[(pawnType << 4) | g_pieceCount[pawnType]];
+ g_pieceIndex[lastPawnSquare] = g_pieceIndex[to];
+ g_pieceList[(pawnType << 4) | g_pieceIndex[lastPawnSquare]] = lastPawnSquare;
+ g_pieceList[(pawnType << 4) | g_pieceCount[pawnType]] = 0;
+ g_pieceIndex[to] = g_pieceCount[promoteType];
+ g_pieceList[(promoteType << 4) | g_pieceIndex[to]] = to;
+ g_pieceCount[promoteType]++;
+ } else {
+ g_board[to] = g_board[from];
+
+ g_baseEval += pieceSquareAdj[piece & 0x7][me == 0 ? flipTable[to] : to];
+ }
+ g_board[from] = pieceEmpty;
+
+ g_toMove = otherColor;
+ g_baseEval = -g_baseEval;
+
+ if ((piece & 0x7) == pieceKing || g_inCheck) {
+ if (IsSquareAttackable(g_pieceList[(pieceKing | (8 - g_toMove)) << 4], otherColor)) {
+ UnmakeMove(move);
+ return false;
+ }
+ } else {
+ var kingPos = g_pieceList[(pieceKing | (8 - g_toMove)) << 4];
+
+ if (ExposesCheck(from, kingPos)) {
+ UnmakeMove(move);
+ return false;
+ }
+
+ if (epcEnd != to) {
+ if (ExposesCheck(epcEnd, kingPos)) {
+ UnmakeMove(move);
+ return false;
+ }
+ }
+ }
+
+ g_inCheck = false;
+
+ if (flags <= moveflagEPC) {
+ var theirKingPos = g_pieceList[(pieceKing | g_toMove) << 4];
+
+ // First check if the piece we moved can attack the enemy king
+ g_inCheck = IsSquareAttackableFrom(theirKingPos, to);
+
+ if (!g_inCheck) {
+ // Now check if the square we moved from exposes check on the enemy king
+ g_inCheck = ExposesCheck(from, theirKingPos);
+
+ if (!g_inCheck) {
+ // Finally, ep. capture can cause another square to be exposed
+ if (epcEnd != to) {
+ g_inCheck = ExposesCheck(epcEnd, theirKingPos);
+ }
+ }
+ }
+ }
+ else {
+ // Castle or promotion, slow check
+ g_inCheck = IsSquareAttackable(g_pieceList[(pieceKing | g_toMove) << 4], 8 - g_toMove);
+ }
+
+ g_repMoveStack[g_moveCount - 1] = g_hashKeyLow;
+ g_move50++;
+
+ return true;
+}
+
+function UnmakeMove(move){
+ g_toMove = 8 - g_toMove;
+ g_baseEval = -g_baseEval;
+
+ g_moveCount--;
+ g_enPassentSquare = g_moveUndoStack[g_moveCount].ep;
+ g_castleRights = g_moveUndoStack[g_moveCount].castleRights;
+ g_inCheck = g_moveUndoStack[g_moveCount].inCheck;
+ g_baseEval = g_moveUndoStack[g_moveCount].baseEval;
+ g_hashKeyLow = g_moveUndoStack[g_moveCount].hashKeyLow;
+ g_hashKeyHigh = g_moveUndoStack[g_moveCount].hashKeyHigh;
+ g_move50 = g_moveUndoStack[g_moveCount].move50;
+
+ var otherColor = 8 - g_toMove;
+ var me = g_toMove >> 3;
+ var them = otherColor >> 3;
+
+ var flags = move & 0xFF0000;
+ var captured = g_moveUndoStack[g_moveCount].captured;
+ var to = (move >> 8) & 0xFF;
+ var from = move & 0xFF;
+
+ var piece = g_board[to];
+
+ if (flags) {
+ if (flags & moveflagCastleKing) {
+ var rook = g_board[to - 1];
+ g_board[to + 1] = rook;
+ g_board[to - 1] = pieceEmpty;
+
+ var rookIndex = g_pieceIndex[to - 1];
+ g_pieceIndex[to + 1] = rookIndex;
+ g_pieceList[((rook & 0xF) << 4) | rookIndex] = to + 1;
+ }
+ else if (flags & moveflagCastleQueen) {
+ var rook = g_board[to + 1];
+ g_board[to - 2] = rook;
+ g_board[to + 1] = pieceEmpty;
+
+ var rookIndex = g_pieceIndex[to + 1];
+ g_pieceIndex[to - 2] = rookIndex;
+ g_pieceList[((rook & 0xF) << 4) | rookIndex] = to - 2;
+ }
+ }
+
+ if (flags & moveflagPromotion) {
+ piece = (g_board[to] & (~0x7)) | piecePawn;
+ g_board[from] = piece;
+
+ var pawnType = g_board[from] & 0xF;
+ var promoteType = g_board[to] & 0xF;
+
+ g_pieceCount[promoteType]--;
+
+ var lastPromoteSquare = g_pieceList[(promoteType << 4) | g_pieceCount[promoteType]];
+ g_pieceIndex[lastPromoteSquare] = g_pieceIndex[to];
+ g_pieceList[(promoteType << 4) | g_pieceIndex[lastPromoteSquare]] = lastPromoteSquare;
+ g_pieceList[(promoteType << 4) | g_pieceCount[promoteType]] = 0;
+ g_pieceIndex[to] = g_pieceCount[pawnType];
+ g_pieceList[(pawnType << 4) | g_pieceIndex[to]] = to;
+ g_pieceCount[pawnType]++;
+ }
+ else {
+ g_board[from] = g_board[to];
+ }
+
+ var epcEnd = to;
+ if (flags & moveflagEPC) {
+ if (g_toMove == colorWhite)
+ epcEnd = to + 0x10;
+ else
+ epcEnd = to - 0x10;
+ g_board[to] = pieceEmpty;
+ }
+
+ g_board[epcEnd] = captured;
+
+ // Move our piece in the piece list
+ g_pieceIndex[from] = g_pieceIndex[to];
+ g_pieceList[((piece & 0xF) << 4) | g_pieceIndex[from]] = from;
+
+ if (captured) {
+ // Restore our piece to the piece list
+ var captureType = captured & 0xF;
+ g_pieceIndex[epcEnd] = g_pieceCount[captureType];
+ g_pieceList[(captureType << 4) | g_pieceCount[captureType]] = epcEnd;
+ g_pieceCount[captureType]++;
+ }
+}
+
+function ExposesCheck(from, kingPos){
+ var index = kingPos - from + 128;
+ // If a queen can't reach it, nobody can!
+ if ((g_vectorDelta[index].pieceMask[0] & (1 << (pieceQueen))) != 0) {
+ var delta = g_vectorDelta[index].delta;
+ var pos = kingPos + delta;
+ while (g_board[pos] == 0) pos += delta;
+
+ var piece = g_board[pos];
+ if (((piece & (g_board[kingPos] ^ 0x18)) & 0x18) == 0)
+ return false;
+
+ // Now see if the piece can actually attack the king
+ var backwardIndex = pos - kingPos + 128;
+ return (g_vectorDelta[backwardIndex].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) != 0;
+ }
+ return false;
+}
+
+function IsSquareOnPieceLine(target, from) {
+ var index = from - target + 128;
+ var piece = g_board[from];
+ return (g_vectorDelta[index].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) ? true : false;
+}
+
+function IsSquareAttackableFrom(target, from){
+ var index = from - target + 128;
+ var piece = g_board[from];
+ if (g_vectorDelta[index].pieceMask[(piece >> 3) & 1] & (1 << (piece & 0x7))) {
+ // Yes, this square is pseudo-attackable. Now, check for real attack
+ var inc = g_vectorDelta[index].delta;
+ do {
+ from += inc;
+ if (from == target)
+ return true;
+ } while (g_board[from] == 0);
+ }
+
+ return false;
+}
+
+function IsSquareAttackable(target, color) {
+ // Attackable by pawns?
+ var inc = color ? -16 : 16;
+ var pawn = (color ? colorWhite : colorBlack) | 1;
+ if (g_board[target - (inc - 1)] == pawn)
+ return true;
+ if (g_board[target - (inc + 1)] == pawn)
+ return true;
+
+ // Attackable by pieces?
+ for (var i = 2; i <= 6; i++) {
+ var index = (color | i) << 4;
+ var square = g_pieceList[index];
+ while (square != 0) {
+ if (IsSquareAttackableFrom(target, square))
+ return true;
+ square = g_pieceList[++index];
+ }
+ }
+ return false;
+}
+
+function GenerateMove(from, to) {
+ return from | (to << 8);
+}
+
+function GenerateMove(from, to, flags){
+ return from | (to << 8) | flags;
+}
+
+function GenerateValidMoves() {
+ var moveList = new Array();
+ var allMoves = new Array();
+ GenerateCaptureMoves(allMoves, null);
+ GenerateAllMoves(allMoves);
+
+ for (var i = allMoves.length - 1; i >= 0; i--) {
+ if (MakeMove(allMoves[i])) {
+ moveList[moveList.length] = allMoves[i];
+ UnmakeMove(allMoves[i]);
+ }
+ }
+
+ return moveList;
+}
+
+function GenerateAllMoves(moveStack) {
+ var from, to, piece, pieceIdx;
+
+ // Pawn quiet moves
+ pieceIdx = (g_toMove | 1) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ GeneratePawnMoves(moveStack, from);
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // Knight quiet moves
+ pieceIdx = (g_toMove | 2) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from + 31; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 33; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 14; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 14; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 31; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 33; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 18; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 18; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // Bishop quiet moves
+ pieceIdx = (g_toMove | 3) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from - 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 15; }
+ to = from - 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 17; }
+ to = from + 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 15; }
+ to = from + 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 17; }
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // Rook quiet moves
+ pieceIdx = (g_toMove | 4) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from - 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to--; }
+ to = from + 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to++; }
+ to = from + 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 16; }
+ to = from - 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 16; }
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // Queen quiet moves
+ pieceIdx = (g_toMove | 5) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from - 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 15; }
+ to = from - 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 17; }
+ to = from + 15; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 15; }
+ to = from + 17; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 17; }
+ to = from - 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to--; }
+ to = from + 1; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to++; }
+ to = from + 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to += 16; }
+ to = from - 16; while (g_board[to] == 0) { moveStack[moveStack.length] = GenerateMove(from, to); to -= 16; }
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // King quiet moves
+ {
+ pieceIdx = (g_toMove | 6) << 4;
+ from = g_pieceList[pieceIdx];
+ to = from - 15; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 17; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 15; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 17; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 1; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 1; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 16; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 16; if (g_board[to] == 0) moveStack[moveStack.length] = GenerateMove(from, to);
+
+ if (!g_inCheck) {
+ var castleRights = g_castleRights;
+ if (!g_toMove)
+ castleRights >>= 2;
+ if (castleRights & 1) {
+ // Kingside castle
+ if (g_board[from + 1] == pieceEmpty && g_board[from + 2] == pieceEmpty) {
+ moveStack[moveStack.length] = GenerateMove(from, from + 0x02, moveflagCastleKing);
+ }
+ }
+ if (castleRights & 2) {
+ // Queenside castle
+ if (g_board[from - 1] == pieceEmpty && g_board[from - 2] == pieceEmpty && g_board[from - 3] == pieceEmpty) {
+ moveStack[moveStack.length] = GenerateMove(from, from - 0x02, moveflagCastleQueen);
+ }
+ }
+ }
+ }
+}
+
+function GenerateCaptureMoves(moveStack, moveScores) {
+ var from, to, piece, pieceIdx;
+ var inc = (g_toMove == 8) ? -16 : 16;
+ var enemy = g_toMove == 8 ? 0x10 : 0x8;
+
+ // Pawn captures
+ pieceIdx = (g_toMove | 1) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from + inc - 1;
+ if (g_board[to] & enemy) {
+ MovePawnTo(moveStack, from, to);
+ }
+
+ to = from + inc + 1;
+ if (g_board[to] & enemy) {
+ MovePawnTo(moveStack, from, to);
+ }
+
+ from = g_pieceList[pieceIdx++];
+ }
+
+ if (g_enPassentSquare != -1) {
+ var inc = (g_toMove == colorWhite) ? -16 : 16;
+ var pawn = g_toMove | piecePawn;
+
+ var from = g_enPassentSquare - (inc + 1);
+ if ((g_board[from] & 0xF) == pawn) {
+ moveStack[moveStack.length] = GenerateMove(from, g_enPassentSquare, moveflagEPC);
+ }
+
+ from = g_enPassentSquare - (inc - 1);
+ if ((g_board[from] & 0xF) == pawn) {
+ moveStack[moveStack.length] = GenerateMove(from, g_enPassentSquare, moveflagEPC);
+ }
+ }
+
+ // Knight captures
+ pieceIdx = (g_toMove | 2) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from + 31; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 33; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 14; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 14; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 31; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 33; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 18; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 18; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // Bishop captures
+ pieceIdx = (g_toMove | 3) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from; do { to -= 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to -= 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to += 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to += 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // Rook captures
+ pieceIdx = (g_toMove | 4) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from; do { to--; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to++; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to -= 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to += 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // Queen captures
+ pieceIdx = (g_toMove | 5) << 4;
+ from = g_pieceList[pieceIdx++];
+ while (from != 0) {
+ to = from; do { to -= 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to -= 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to += 15; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to += 17; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to--; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to++; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to -= 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from; do { to += 16; } while (g_board[to] == 0); if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ from = g_pieceList[pieceIdx++];
+ }
+
+ // King captures
+ {
+ pieceIdx = (g_toMove | 6) << 4;
+ from = g_pieceList[pieceIdx];
+ to = from - 15; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 17; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 15; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 17; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 1; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 1; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from - 16; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ to = from + 16; if (g_board[to] & enemy) moveStack[moveStack.length] = GenerateMove(from, to);
+ }
+}
+
+function MovePawnTo(moveStack, start, square) {
+ var row = square & 0xF0;
+ if ((row == 0x90) || (row == 0x20)) {
+ moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteQueen);
+ moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteKnight);
+ moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion | moveflagPromoteBishop);
+ moveStack[moveStack.length] = GenerateMove(start, square, moveflagPromotion);
+ }
+ else {
+ moveStack[moveStack.length] = GenerateMove(start, square, 0);
+ }
+}
+
+function GeneratePawnMoves(moveStack, from) {
+ var piece = g_board[from];
+ var color = piece & colorWhite;
+ var inc = (color == colorWhite) ? -16 : 16;
+
+ // Quiet pawn moves
+ var to = from + inc;
+ if (g_board[to] == 0) {
+ MovePawnTo(moveStack, from, to, pieceEmpty);
+
+ // Check if we can do a 2 square jump
+ if ((((from & 0xF0) == 0x30) && color != colorWhite) ||
+ (((from & 0xF0) == 0x80) && color == colorWhite)) {
+ to += inc;
+ if (g_board[to] == 0) {
+ moveStack[moveStack.length] = GenerateMove(from, to);
+ }
+ }
+ }
+}
+
+function UndoHistory(ep, castleRights, inCheck, baseEval, hashKeyLow, hashKeyHigh, move50, captured) {
+ this.ep = ep;
+ this.castleRights = castleRights;
+ this.inCheck = inCheck;
+ this.baseEval = baseEval;
+ this.hashKeyLow = hashKeyLow;
+ this.hashKeyHigh = hashKeyHigh;
+ this.move50 = move50;
+ this.captured = captured;
+}
+
+var g_seeValues = [0, 1, 3, 3, 5, 9, 900, 0,
+ 0, 1, 3, 3, 5, 9, 900, 0];
+
+function See(move) {
+ var from = move & 0xFF;
+ var to = (move >> 8) & 0xFF;
+
+ var fromPiece = g_board[from];
+
+ var fromValue = g_seeValues[fromPiece & 0xF];
+ var toValue = g_seeValues[g_board[to] & 0xF];
+
+ if (fromValue <= toValue) {
+ return true;
+ }
+
+ if (move >> 16) {
+ // Castles, promotion, ep are always good
+ return true;
+ }
+
+ var us = (fromPiece & colorWhite) ? colorWhite : 0;
+ var them = 8 - us;
+
+ // Pawn attacks
+ // If any opponent pawns can capture back, this capture is probably not worthwhile (as we must be using knight or above).
+ var inc = (fromPiece & colorWhite) ? -16 : 16; // Note: this is capture direction from to, so reversed from normal move direction
+ if (((g_board[to + inc + 1] & 0xF) == (piecePawn | them)) ||
+ ((g_board[to + inc - 1] & 0xF) == (piecePawn | them))) {
+ return false;
+ }
+
+ var themAttacks = new Array();
+
+ // Knight attacks
+ // If any opponent knights can capture back, and the deficit we have to make up is greater than the knights value,
+ // it's not worth it. We can capture on this square again, and the opponent doesn't have to capture back.
+ var captureDeficit = fromValue - toValue;
+ SeeAddKnightAttacks(to, them, themAttacks);
+ if (themAttacks.length != 0 && captureDeficit > g_seeValues[pieceKnight]) {
+ return false;
+ }
+
+ // Slider attacks
+ g_board[from] = 0;
+ for (var pieceType = pieceBishop; pieceType <= pieceQueen; pieceType++) {
+ if (SeeAddSliderAttacks(to, them, themAttacks, pieceType)) {
+ if (captureDeficit > g_seeValues[pieceType]) {
+ g_board[from] = fromPiece;
+ return false;
+ }
+ }
+ }
+
+ // Pawn defenses
+ // At this point, we are sure we are making a "losing" capture. The opponent can not capture back with a
+ // pawn. They cannot capture back with a minor/major and stand pat either. So, if we can capture with
+ // a pawn, it's got to be a winning or equal capture.
+ if (((g_board[to - inc + 1] & 0xF) == (piecePawn | us)) ||
+ ((g_board[to - inc - 1] & 0xF) == (piecePawn | us))) {
+ g_board[from] = fromPiece;
+ return true;
+ }
+
+ // King attacks
+ SeeAddSliderAttacks(to, them, themAttacks, pieceKing);
+
+ // Our attacks
+ var usAttacks = new Array();
+ SeeAddKnightAttacks(to, us, usAttacks);
+ for (var pieceType = pieceBishop; pieceType <= pieceKing; pieceType++) {
+ SeeAddSliderAttacks(to, us, usAttacks, pieceType);
+ }
+
+ g_board[from] = fromPiece;
+
+ // We are currently winning the amount of material of the captured piece, time to see if the opponent
+ // can get it back somehow. We assume the opponent can capture our current piece in this score, which
+ // simplifies the later code considerably.
+ var seeValue = toValue - fromValue;
+
+ for (; ; ) {
+ var capturingPieceValue = 1000;
+ var capturingPieceIndex = -1;
+
+ // Find the least valuable piece of the opponent that can attack the square
+ for (var i = 0; i < themAttacks.length; i++) {
+ if (themAttacks[i] != 0) {
+ var pieceValue = g_seeValues[g_board[themAttacks[i]] & 0x7];
+ if (pieceValue < capturingPieceValue) {
+ capturingPieceValue = pieceValue;
+ capturingPieceIndex = i;
+ }
+ }
+ }
+
+ if (capturingPieceIndex == -1) {
+ // Opponent can't capture back, we win
+ return true;
+ }
+
+ // Now, if seeValue < 0, the opponent is winning. If even after we take their piece,
+ // we can't bring it back to 0, then we have lost this battle.
+ seeValue += capturingPieceValue;
+ if (seeValue < 0) {
+ return false;
+ }
+
+ var capturingPieceSquare = themAttacks[capturingPieceIndex];
+ themAttacks[capturingPieceIndex] = 0;
+
+ // Add any x-ray attackers
+ SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks);
+
+ // Our turn to capture
+ capturingPieceValue = 1000;
+ capturingPieceIndex = -1;
+
+ // Find our least valuable piece that can attack the square
+ for (var i = 0; i < usAttacks.length; i++) {
+ if (usAttacks[i] != 0) {
+ var pieceValue = g_seeValues[g_board[usAttacks[i]] & 0x7];
+ if (pieceValue < capturingPieceValue) {
+ capturingPieceValue = pieceValue;
+ capturingPieceIndex = i;
+ }
+ }
+ }
+
+ if (capturingPieceIndex == -1) {
+ // We can't capture back, we lose :(
+ return false;
+ }
+
+ // Assume our opponent can capture us back, and if we are still winning, we can stand-pat
+ // here, and assume we've won.
+ seeValue -= capturingPieceValue;
+ if (seeValue >= 0) {
+ return true;
+ }
+
+ capturingPieceSquare = usAttacks[capturingPieceIndex];
+ usAttacks[capturingPieceIndex] = 0;
+
+ // Add any x-ray attackers
+ SeeAddXrayAttack(to, capturingPieceSquare, us, usAttacks, themAttacks);
+ }
+}
+
+function SeeAddXrayAttack(target, square, us, usAttacks, themAttacks) {
+ var index = square - target + 128;
+ var delta = -g_vectorDelta[index].delta;
+ if (delta == 0)
+ return;
+ square += delta;
+ while (g_board[square] == 0) {
+ square += delta;
+ }
+
+ if ((g_board[square] & 0x18) && IsSquareOnPieceLine(target, square)) {
+ if ((g_board[square] & 8) == us) {
+ usAttacks[usAttacks.length] = square;
+ } else {
+ themAttacks[themAttacks.length] = square;
+ }
+ }
+}
+
+// target = attacking square, us = color of knights to look for, attacks = array to add squares to
+function SeeAddKnightAttacks(target, us, attacks) {
+ var pieceIdx = (us | pieceKnight) << 4;
+ var attackerSq = g_pieceList[pieceIdx++];
+
+ while (attackerSq != 0) {
+ if (IsSquareOnPieceLine(target, attackerSq)) {
+ attacks[attacks.length] = attackerSq;
+ }
+ attackerSq = g_pieceList[pieceIdx++];
+ }
+}
+
+function SeeAddSliderAttacks(target, us, attacks, pieceType) {
+ var pieceIdx = (us | pieceType) << 4;
+ var attackerSq = g_pieceList[pieceIdx++];
+ var hit = false;
+
+ while (attackerSq != 0) {
+ if (IsSquareAttackableFrom(target, attackerSq)) {
+ attacks[attacks.length] = attackerSq;
+ hit = true;
+ }
+ attackerSq = g_pieceList[pieceIdx++];
+ }
+
+ return hit;
+}
+
+function BuildPVMessage(bestMove, value, timeTaken, ply) {
+ var totalNodes = g_nodeCount + g_qNodeCount;
+ return "Ply:" + ply + " Score:" + value + " Nodes:" + totalNodes + " NPS:" + ((totalNodes / (timeTaken / 1000)) | 0) + " " + PVFromHash(bestMove, 15);
+}
+
+//////////////////////////////////////////////////
+// Test Harness
+//////////////////////////////////////////////////
+function FinishPlyCallback(bestMove, value, timeTaken, ply) {
+ postMessage("pv " + BuildPVMessage(bestMove, value, timeTaken, ply));
+}
+
+function FinishMoveLocalTesting(bestMove, value, timeTaken, ply) {
+ if (bestMove != null) {
+ MakeMove(bestMove);
+ postMessage(FormatMove(bestMove));
+ }
+}
+
+var needsReset = true;
+self.onmessage = function (e) {
+ if (e.data == "go" || needsReset) {
+ ResetGame();
+ needsReset = false;
+ if (e.data == "go") return;
+ }
+ if (e.data.match("^position") == "position") {
+ ResetGame();
+ var result = InitializeFromFen(e.data.substr(9, e.data.length - 9));
+ if (result.length != 0) {
+ postMessage("message " + result);
+ }
+ } else if (e.data.match("^search") == "search") {
+ g_timeout = parseInt(e.data.substr(7, e.data.length - 7), 10);
+ Search(FinishMoveLocalTesting, 99, FinishPlyCallback);
+ } else if (e.data == "analyze") {
+ g_timeout = 99999999999;
+ Search(null, 99, FinishPlyCallback);
+ } else {
+ MakeMove(GetMoveFromString(e.data));
+ }
+}
diff --git a/html/browser/jquery-1.8.2.min.js b/html/browser/jquery-1.8.2.min.js
new file mode 100644
index 00000000000..bc3fbc81b26
--- /dev/null
+++ b/html/browser/jquery-1.8.2.min.js
@@ -0,0 +1,2 @@
+/*! jQuery v1.8.2 jquery.com | jquery.org/license */
+(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write(""),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;ba",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;be.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b0)for(e=d;e=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*\s*$/g,bz={option:[1,""],legend:[1,""],thead:[1,""],tr:[2,""],td:[3,""],col:[2,""],area:[1,""],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X","
"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1>$2>");try{for(;d1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1>$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]===""&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/
+
+
+
\ No newline at end of file
diff --git a/icons/chess_pieces/bishop_black.png b/icons/chess_pieces/bishop_black.png
new file mode 100644
index 00000000000..0fd2f0a15c5
Binary files /dev/null and b/icons/chess_pieces/bishop_black.png differ
diff --git a/icons/chess_pieces/bishop_white.png b/icons/chess_pieces/bishop_white.png
new file mode 100644
index 00000000000..34ded58a666
Binary files /dev/null and b/icons/chess_pieces/bishop_white.png differ
diff --git a/icons/chess_pieces/blank.gif b/icons/chess_pieces/blank.gif
new file mode 100644
index 00000000000..eaeb7b37d5e
Binary files /dev/null and b/icons/chess_pieces/blank.gif differ
diff --git a/icons/chess_pieces/king_black.png b/icons/chess_pieces/king_black.png
new file mode 100644
index 00000000000..68db4084314
Binary files /dev/null and b/icons/chess_pieces/king_black.png differ
diff --git a/icons/chess_pieces/king_white.png b/icons/chess_pieces/king_white.png
new file mode 100644
index 00000000000..fb4a71ec33c
Binary files /dev/null and b/icons/chess_pieces/king_white.png differ
diff --git a/icons/chess_pieces/knight_black.png b/icons/chess_pieces/knight_black.png
new file mode 100644
index 00000000000..18fa86f2f8a
Binary files /dev/null and b/icons/chess_pieces/knight_black.png differ
diff --git a/icons/chess_pieces/knight_white.png b/icons/chess_pieces/knight_white.png
new file mode 100644
index 00000000000..989bf85cba3
Binary files /dev/null and b/icons/chess_pieces/knight_white.png differ
diff --git a/icons/chess_pieces/pawn_black.png b/icons/chess_pieces/pawn_black.png
new file mode 100644
index 00000000000..47b6a161fe2
Binary files /dev/null and b/icons/chess_pieces/pawn_black.png differ
diff --git a/icons/chess_pieces/pawn_white.png b/icons/chess_pieces/pawn_white.png
new file mode 100644
index 00000000000..f0a324b835a
Binary files /dev/null and b/icons/chess_pieces/pawn_white.png differ
diff --git a/icons/chess_pieces/queen_black.png b/icons/chess_pieces/queen_black.png
new file mode 100644
index 00000000000..a6a971c8f86
Binary files /dev/null and b/icons/chess_pieces/queen_black.png differ
diff --git a/icons/chess_pieces/queen_white.png b/icons/chess_pieces/queen_white.png
new file mode 100644
index 00000000000..ac3335f6fff
Binary files /dev/null and b/icons/chess_pieces/queen_white.png differ
diff --git a/icons/chess_pieces/rook_black.png b/icons/chess_pieces/rook_black.png
new file mode 100644
index 00000000000..0c603e3d4d1
Binary files /dev/null and b/icons/chess_pieces/rook_black.png differ
diff --git a/icons/chess_pieces/rook_white.png b/icons/chess_pieces/rook_white.png
new file mode 100644
index 00000000000..9600ad0d42e
Binary files /dev/null and b/icons/chess_pieces/rook_white.png differ
diff --git a/icons/chess_pieces/sprites.png b/icons/chess_pieces/sprites.png
new file mode 100644
index 00000000000..0f3dc31dcca
Binary files /dev/null and b/icons/chess_pieces/sprites.png differ
diff --git a/icons/obj/stationobjs.dmi b/icons/obj/stationobjs.dmi
index d737faf3b0d..72084b5675b 100755
Binary files a/icons/obj/stationobjs.dmi and b/icons/obj/stationobjs.dmi differ
diff --git a/paradise.dme b/paradise.dme
index 9570aee485f..67af82f6adf 100644
--- a/paradise.dme
+++ b/paradise.dme
@@ -500,6 +500,7 @@
#include "code\game\machinery\flasher.dm"
#include "code\game\machinery\floodlight.dm"
#include "code\game\machinery\Freezer.dm"
+#include "code\game\machinery\gameboard.dm"
#include "code\game\machinery\guestpass.dm"
#include "code\game\machinery\hologram.dm"
#include "code\game\machinery\holosign.dm"