4 * Version of this script. If the server returns a version larger than
5 * this, it is a sign we should reload to upgrade ourselves.
10 var SCRIPT_VERSION = 2016032000;
13 * The current backend URL.
18 var backend_url = "/analysis.pl";
19 var backend_hash_url = "/hash";
21 /** @type {window.ChessBoard} @private */
24 /** @type {boolean} @private */
25 var board_is_animating = false;
28 * The most recent analysis data we have from the server
29 * (about the most recent position).
33 var current_analysis_data = null;
36 * If we are displaying previous analysis or from hash, this is non-null,
37 * and will override most of current_analysis_data.
42 var displayed_analysis_data = null;
45 * Games currently in progress, if any.
54 var current_games = null;
69 /** @type {Array.<Array.<boolean>>} */
70 var occupied_by_arrows = [];
72 /** Currently displayed refutation lines (on-screen).
73 * Can either come from the current_analysis_data, displayed_analysis_data,
74 * or hash_refutation_lines.
76 var refutation_lines = [];
78 /** Refutation lines from current hash probe.
80 * If non-null, will override refutation lines from the base position.
81 * Note that these are relative to display_fen, not base_fen.
83 var hash_refutation_lines = null;
85 /** @type {!number} @private */
88 /** @type {!string} @private */
91 /** @type {number} @private */
94 /** @type {boolean} @private */
95 var sort_refutation_lines_by_score = true;
97 /** @type {boolean} @private */
98 var truncate_display_history = true;
100 /** @type {!string|undefined} @private */
101 var highlight_from = undefined;
103 /** @type {!string|undefined} @private */
104 var highlight_to = undefined;
106 /** The HTML object of the move currently being highlighted (in red).
109 var highlighted_move = null;
111 /** @type {?number} @private */
114 /** @type {boolean} @private */
115 var enable_sound = false;
118 * Our best estimate of how many milliseconds we need to add to
119 * new Date() to get the true UTC time. Calibrated against the
125 var client_clock_offset_ms = null;
127 var clock_timer = null;
129 /** The current position being analyzed, represented as a FEN string.
130 * Note that this is not necessarily the same as display_fen.
136 /** The current position on the board, represented as a FEN string.
137 * Note that board.fen() does not contain e.g. who is to play.
141 var display_fen = null;
145 * pretty_pv: Array.<string>,
148 * start_display_move_num: number
151 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
154 /** All PVs that we currently know of.
156 * Element 0 is history (or null if no history).
157 * Element 1 is current main PV, or explored line if nowhere else on the screen.
158 * All remaining elements are refutation lines (multi-PV).
160 * @type {Array.<DisplayLine>}
163 var display_lines = [];
165 /** @type {?DisplayLine} @private */
166 var current_display_line = null;
168 /** @type {boolean} @private */
169 var current_display_line_is_history = false;
171 /** @type {?number} @private */
172 var current_display_move = null;
175 * The current backend request to get main analysis (not history), if any,
176 * so that we can abort it.
181 var current_analysis_xhr = null;
184 * The current timer to fire off a request to get main analysis (not history),
185 * if any, so that we can abort it.
190 var current_analysis_request_timer = null;
193 * The current backend request to get historic data, if any.
198 var current_historic_xhr = null;
201 * The current backend request to get hash probes, if any, so that we can abort it.
206 var current_hash_xhr = null;
209 * The current timer to display hash probe information (it could be waiting on the
210 * board to stop animating), if any, so that we can abort it.
215 var current_hash_display_timer = null;
217 var supports_html5_storage = function() {
219 return 'localStorage' in window && window['localStorage'] !== null;
225 // Make the unique token persistent so people refreshing the page won't count twice.
226 // Of course, you can never fully protect against people deliberately wanting to spam.
227 var get_unique = function() {
228 var use_local_storage = supports_html5_storage();
229 if (use_local_storage && localStorage['unique']) {
230 return localStorage['unique'];
232 var unique = Math.random();
233 if (use_local_storage) {
234 localStorage['unique'] = unique;
239 var request_update = function() {
240 current_analysis_request_timer = null;
242 current_analysis_xhr = $.ajax({
243 url: backend_url + "?ims=" + ims + "&unique=" + unique
244 }).done(function(data, textstatus, xhr) {
245 sync_server_clock(xhr.getResponseHeader('Date'));
246 ims = xhr.getResponseHeader('X-RGLM');
247 var num_viewers = xhr.getResponseHeader('X-RGNV');
249 if (Array.isArray(data)) {
250 new_data = JSON.parse(JSON.stringify(current_analysis_data));
251 JSON_delta.patch(new_data, data);
256 var minimum_version = xhr.getResponseHeader('X-RGMV');
257 if (minimum_version && minimum_version > SCRIPT_VERSION) {
258 // Upgrade to latest version with a force-reload.
259 location.reload(true);
262 possibly_play_sound(current_analysis_data, new_data);
263 current_analysis_data = new_data;
265 update_num_viewers(num_viewers);
268 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
269 }).fail(function(jqXHR, textStatus, errorThrown) {
270 if (textStatus === "abort") {
271 // Aborted because we are switching backends. Abandon and don't retry,
272 // because another one is already started for us.
274 // Backend error or similar. Wait ten seconds, then try again.
275 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
280 var possibly_play_sound = function(old_data, new_data) {
284 if (old_data === null) {
287 var ding = document.getElementById('ding');
288 if (ding && ding.play) {
289 if (old_data['position'] && old_data['position']['fen'] &&
290 new_data['position'] && new_data['position']['fen'] &&
291 (old_data['position']['fen'] !== new_data['position']['fen'] ||
292 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
299 * @type {!string} server_date_string
301 var sync_server_clock = function(server_date_string) {
302 var server_time_ms = new Date(server_date_string).getTime();
303 var client_time_ms = new Date().getTime();
304 var estimated_offset_ms = server_time_ms - client_time_ms;
306 // In order not to let the noise move us too much back and forth
307 // (the server only has one-second resolution anyway), we only
308 // change an existing skew if we are at least five seconds off.
309 if (client_clock_offset_ms === null ||
310 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
311 client_clock_offset_ms = estimated_offset_ms;
315 var clear_arrows = function() {
316 for (var i = 0; i < arrows.length; ++i) {
318 if (arrows[i].svg.parentElement) {
319 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
321 delete arrows[i].svg;
326 occupied_by_arrows = [];
327 for (var y = 0; y < 8; ++y) {
328 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
332 var redraw_arrows = function() {
333 for (var i = 0; i < arrows.length; ++i) {
334 position_arrow(arrows[i]);
338 /** @param {!number} x
341 var sign = function(x) {
351 /** See if drawing this arrow on the board would cause unduly amount of confusion.
352 * @param {!string} from The square the arrow is from (e.g. e4).
353 * @param {!string} to The square the arrow is to (e.g. e4).
356 var interfering_arrow = function(from, to) {
357 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
358 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
359 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
360 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
362 occupied_by_arrows[from_row][from_col] = true;
364 // Knight move: Just check that we haven't been at the destination before.
365 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
366 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
367 return occupied_by_arrows[to_row][to_col];
370 // Sliding piece: Check if anything except the from-square is seen before.
371 var dx = sign(to_col - from_col);
372 var dy = sign(to_row - from_row);
378 if (occupied_by_arrows[y][x]) {
381 occupied_by_arrows[y][x] = true;
382 } while (x != to_col || y != to_row);
387 /** Find a point along the coordinate system given by the given line,
388 * <t> units forward from the start of the line, <u> units to the right of it.
389 * @param {!number} x1
390 * @param {!number} x2
391 * @param {!number} y1
392 * @param {!number} y2
395 * @return {!string} The point in "x y" form, suitable for SVG paths.
397 var point_from_start = function(x1, y1, x2, y2, t, u) {
401 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
405 var x = x1 + dx * t + dy * u;
406 var y = y1 + dy * t - dx * u;
410 /** Find a point along the coordinate system given by the given line,
411 * <t> units forward from the end of the line, <u> units to the right of it.
412 * @param {!number} x1
413 * @param {!number} x2
414 * @param {!number} y1
415 * @param {!number} y2
418 * @return {!string} The point in "x y" form, suitable for SVG paths.
420 var point_from_end = function(x1, y1, x2, y2, t, u) {
424 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
428 var x = x2 + dx * t + dy * u;
429 var y = y2 + dy * t - dx * u;
433 var position_arrow = function(arrow) {
435 if (arrow.svg.parentElement) {
436 arrow.svg.parentElement.removeChild(arrow.svg);
440 if (current_display_line !== null && !current_display_line_is_history) {
444 var pos = $(".square-a8").position();
446 var zoom_factor = $("#board").width() / 400.0;
447 var line_width = arrow.line_width * zoom_factor;
448 var arrow_size = arrow.arrow_size * zoom_factor;
450 var square_width = $(".square-a8").width();
451 var from_y = (7 - arrow.from_row + 0.5)*square_width;
452 var to_y = (7 - arrow.to_row + 0.5)*square_width;
453 var from_x = (arrow.from_col + 0.5)*square_width;
454 var to_x = (arrow.to_col + 0.5)*square_width;
456 var SVG_NS = "http://www.w3.org/2000/svg";
457 var XHTML_NS = "http://www.w3.org/1999/xhtml";
458 var svg = document.createElementNS(SVG_NS, "svg");
459 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
460 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
461 svg.setAttribute("style", "position: absolute");
462 svg.setAttribute("position", "absolute");
463 svg.setAttribute("version", "1.1");
464 svg.setAttribute("class", "c1");
465 svg.setAttribute("xmlns", XHTML_NS);
473 var outline = document.createElementNS(SVG_NS, "path");
474 outline.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
475 outline.setAttribute("xmlns", XHTML_NS);
476 outline.setAttribute("stroke", "#666");
477 outline.setAttribute("stroke-width", line_width + 2);
478 outline.setAttribute("fill", "none");
479 svg.appendChild(outline);
481 var path = document.createElementNS(SVG_NS, "path");
482 path.setAttribute("d", "M " + point_from_start(x1, y1, x2, y2, arrow_size / 2, 0) + " L " + point_from_end(x1, y1, x2, y2, -arrow_size / 2, 0));
483 path.setAttribute("xmlns", XHTML_NS);
484 path.setAttribute("stroke", arrow.fg_color);
485 path.setAttribute("stroke-width", line_width);
486 path.setAttribute("fill", "none");
487 svg.appendChild(path);
489 // Then the arrow head.
490 var head = document.createElementNS(SVG_NS, "path");
491 head.setAttribute("d",
492 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
493 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
494 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
495 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
496 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
497 head.setAttribute("xmlns", XHTML_NS);
498 head.setAttribute("stroke", "#000");
499 head.setAttribute("stroke-width", "1");
500 head.setAttribute("fill", arrow.fg_color);
501 svg.appendChild(head);
503 $(svg).css({ top: pos.top, left: pos.left });
504 document.body.appendChild(svg);
509 * @param {!string} from_square
510 * @param {!string} to_square
511 * @param {!string} fg_color
512 * @param {number} line_width
513 * @param {number} arrow_size
515 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
516 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
517 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
518 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
519 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
527 line_width: line_width,
528 arrow_size: arrow_size,
532 position_arrow(arrow);
536 var compare_by_sort_key = function(refutation_lines, a, b) {
537 var ska = refutation_lines[a]['sort_key'];
538 var skb = refutation_lines[b]['sort_key'];
539 if (ska < skb) return -1;
540 if (ska > skb) return 1;
544 var compare_by_score = function(refutation_lines, a, b) {
545 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
546 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
551 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
552 * sorted by quality, descending.
554 * @param {!Object} data
555 * @param {number} margin The maximum number of centipawns worse than the
556 * best move can be and still be included.
557 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
558 * moves, in score order.
560 var find_nonstupid_moves = function(data, margin) {
561 // First of all, if there are any moves that are more than 0.5 ahead of
562 // the primary move, the refutation lines are probably bunk, so just
564 var best_score = undefined;
565 var pv_score = undefined;
566 for (var move in data['refutation_lines']) {
567 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
568 if (move == data['pv_uci'][0]) {
571 if (best_score === undefined || score > best_score) {
574 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
579 if (best_score - pv_score > 50) {
583 // Now find all moves that are within “margin” of the best score.
584 // The PV move will always be first.
586 for (var move in data['refutation_lines']) {
587 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
588 if (move != data['pv_uci'][0] && best_score - score <= margin) {
592 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
593 moves.unshift(data['pv_uci'][0]);
602 var thousands = function(x) {
603 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
607 * @param {!string} start_fen
608 * @param {Array.<string>} pretty_pv
609 * @param {number} move_num
610 * @param {!string} toplay
611 * @param {number} start_display_move_num
612 * @param {number=} opt_limit
613 * @param {boolean=} opt_showlast
615 var add_pv = function(start_fen, pretty_pv, move_num, toplay, start_display_move_num, opt_limit, opt_showlast) {
617 start_fen: start_fen,
618 pretty_pv: pretty_pv,
619 move_num: parseInt(move_num),
621 start_display_move_num: start_display_move_num,
623 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
627 * @param {number} line_num
628 * @param {number=} opt_limit
629 * @param {boolean=} opt_showlast
631 var print_pv = function(line_num, opt_limit, opt_showlast) {
632 var display_line = display_lines[line_num];
633 var pretty_pv = display_line.pretty_pv;
634 var move_num = display_line.move_num;
635 var toplay = display_line.toplay;
637 // Truncate PV at the start if needed.
638 var start_display_move_num = display_line.start_display_move_num;
639 if (start_display_move_num > 0) {
640 pretty_pv = pretty_pv.slice(start_display_move_num);
641 var to_add = start_display_move_num;
642 if (toplay === 'B') {
647 if (to_add % 2 == 1) {
651 move_num += to_add / 2;
656 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
657 // Truncate the PV at the beginning (instead of at the end).
658 // We assume here that toplay is 'W'. We also assume that if
659 // opt_showlast is set, then it is the history, and thus,
660 // the UI should be to expand the history.
661 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
662 i = pretty_pv.length - opt_limit;
667 } else if (toplay == 'B' && pretty_pv.length > 0) {
668 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
669 pv = move_num + '. … ' + move;
674 for ( ; i < pretty_pv.length; ++i) {
675 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
678 if (i > opt_limit && !opt_showlast) {
684 pv += move_num + '. ' + move;
695 /** Update the highlighted to/from squares on the board.
696 * Based on the global "highlight_from" and "highlight_to" variables.
698 var update_board_highlight = function() {
699 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
700 if ((current_display_line === null || current_display_line_is_history) &&
701 highlight_from !== undefined && highlight_to !== undefined) {
702 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
703 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
707 var update_history = function() {
708 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
709 $("#history").html("No history");
710 } else if (truncate_display_history) {
711 $("#history").html(print_pv(0, 8, true));
714 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
715 print_pv(0, 1, 'W'));
720 * @param {!boolean} truncate_history
722 var collapse_history = function(truncate_history) {
723 truncate_display_history = truncate_history;
726 window['collapse_history'] = collapse_history;
728 /** Update the HTML display of multi-PV from the global "refutation_lines".
730 * Also recreates the global "display_lines".
732 var update_refutation_lines = function() {
733 if (base_fen === null) {
736 if (display_lines.length > 2) {
737 // Truncate so that only the history and PV is left.
738 display_lines = [ display_lines[0], display_lines[1] ];
740 var tbl = $("#refutationlines");
743 // Find out where the lines start from.
745 var start_display_move_num = 0;
746 if (hash_refutation_lines) {
747 base_line = current_display_line.pretty_pv.slice(0, current_display_move + 1);
748 start_display_move_num = base_line.length;
752 for (var move in refutation_lines) {
755 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
756 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
757 for (var i = 0; i < moves.length; ++i) {
758 var line = refutation_lines[moves[i]];
760 var tr = document.createElement("tr");
762 var move_td = document.createElement("td");
763 tr.appendChild(move_td);
764 $(move_td).addClass("move");
766 if (line['pv_pretty'].length == 0) {
768 $(move_td).text(line['pretty_move']);
769 var score_td = document.createElement("td");
771 $(score_td).addClass("score");
772 $(score_td).text("—");
773 tr.appendChild(score_td);
775 var depth_td = document.createElement("td");
776 tr.appendChild(depth_td);
777 $(depth_td).addClass("depth");
778 $(depth_td).text("—");
784 if (line['pv_pretty'].length == 0) {
785 $(move_td).text(line['pretty_move']);
787 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
788 $(move_td).html(move);
791 var score_td = document.createElement("td");
792 tr.appendChild(score_td);
793 $(score_td).addClass("score");
794 $(score_td).text(line['pretty_score']);
796 var depth_td = document.createElement("td");
797 tr.appendChild(depth_td);
798 $(depth_td).addClass("depth");
799 $(depth_td).text("d" + line['depth']);
801 var pv_td = document.createElement("td");
802 tr.appendChild(pv_td);
803 $(pv_td).addClass("pv");
804 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv_pretty']), move_num, toplay, start_display_move_num, 10));
809 // Make one of the links clickable and the other nonclickable.
810 if (sort_refutation_lines_by_score) {
811 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
812 $("#sortbyscore1").html("<strong>Score</strong>");
814 $("#sortbyscore0").html("<strong>Move</strong>");
815 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
818 // Update the move highlight, as we've rewritten all the HTML.
819 update_move_highlight();
823 * Create a Chess.js board object, containing the given position plus the given moves,
824 * up to the given limit.
826 * @param {?string} fen
827 * @param {Array.<string>} moves
828 * @param {number} last_move
830 var chess_from = function(fen, moves, last_move) {
831 var hiddenboard = new Chess();
833 hiddenboard.load(fen);
835 for (var i = 0; i <= last_move; ++i) {
836 if (moves[i] === '0-0') {
837 hiddenboard.move('O-O');
838 } else if (moves[i] === '0-0-0') {
839 hiddenboard.move('O-O-O');
841 hiddenboard.move(moves[i]);
847 var update_game_list = function(games) {
848 $("#games").text("");
849 if (games === null) {
853 var games_div = document.getElementById('games');
854 for (var game_num = 0; game_num < games.length; ++game_num) {
855 var game = games[game_num];
856 var game_span = document.createElement("span");
857 game_span.setAttribute("class", "game");
859 var game_name = document.createTextNode(game['name']);
860 if (game['url'] === backend_url) {
861 game_span.appendChild(game_name);
863 var game_a = document.createElement("a");
864 game_a.setAttribute("href", "#" + game['id']);
865 game_a.appendChild(game_name);
866 game_span.appendChild(game_a);
868 games_div.appendChild(game_span);
873 * Try to find a running game that matches with the current hash,
874 * and switch to it if we're not already displaying it.
876 var possibly_switch_game_from_hash = function() {
877 if (current_games === null) {
881 var hash = window.location.hash.replace(/^#/,'');
882 for (var i = 0; i < current_games.length; ++i) {
883 if (current_games[i]['id'] === hash) {
884 if (backend_url !== current_games[i]['url']) {
885 switch_backend(current_games[i]['url']);
892 /** Update all the HTML on the page, based on current global state.
894 var update_board = function() {
895 var data = displayed_analysis_data || current_analysis_data;
896 var current_data = current_analysis_data; // Convenience alias.
900 // Print the history. This is pretty much the only thing that's
901 // unconditionally taken from current_data (we're not interested in
902 // historic history).
903 if (current_data['position']['pretty_history']) {
904 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 0, 8, true);
906 display_lines.push(null);
910 // Games currently in progress, if any.
911 if (current_data['games']) {
912 current_games = current_data['games'];
913 possibly_switch_game_from_hash();
914 update_game_list(current_data['games']);
916 current_games = null;
917 update_game_list(null);
920 // The headline. Names are always fetched from current_data;
921 // the rest can depend a bit.
924 current_data['position']['player_w'] && current_data['position']['player_b']) {
925 headline = current_data['position']['player_w'] + '–' +
926 current_data['position']['player_b'] + ', analysis';
928 headline = 'Analysis';
931 // Credits, where applicable. Note that we don't want the footer to change a lot
932 // when e.g. viewing history, so if any of these changed during the game,
933 // use the current one still.
934 if (current_data['using_lomonosov']) {
935 $("#lomonosov").show();
937 $("#lomonosov").hide();
940 // Credits: The engine name/version.
941 if (current_data['engine'] && current_data['engine']['name'] !== null) {
942 $("#engineid").text(current_data['engine']['name']);
945 // Credits: The engine URL.
946 if (current_data['engine'] && current_data['engine']['url']) {
947 $("#engineid").attr("href", current_data['engine']['url']);
949 $("#engineid").removeAttr("href");
952 // Credits: Engine details.
953 if (current_data['engine'] && current_data['engine']['details']) {
954 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
956 $("#enginedetails").text("");
959 // Credits: Move source, possibly with URL.
960 if (current_data['move_source'] && current_data['move_source_url']) {
961 $("#movesource").text("Moves provided by ");
962 var movesource_a = document.createElement("a");
963 movesource_a.setAttribute("href", current_data['move_source_url']);
964 var movesource_text = document.createTextNode(current_data['move_source']);
965 movesource_a.appendChild(movesource_text);
966 var movesource_period = document.createTextNode(".");
967 document.getElementById("movesource").appendChild(movesource_a);
968 document.getElementById("movesource").appendChild(movesource_period);
969 } else if (current_data['move_source']) {
970 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
972 $("#movesource").text("");
976 if (displayed_analysis_data) {
977 // Displaying some non-current position, pick out the last move
978 // from the history. This will work even if the fetch failed.
979 last_move = format_halfmove_with_number(
980 current_display_line.pretty_pv[current_display_move],
981 current_display_move + 1);
982 headline += ' after ' + last_move;
983 } else if (data['position']['last_move'] !== 'none') {
984 last_move = format_move_with_number(
985 data['position']['last_move'],
986 data['position']['move_num'],
987 data['position']['toplay'] == 'W');
988 headline += ' after ' + last_move;
992 $("#headline").text(headline);
994 // The <title> contains a very brief headline.
995 var title_elems = [];
996 if (data['short_score'] !== undefined && data['short_score'] !== null) {
997 title_elems.push(data['short_score'].replace(/^ /, ""));
999 if (last_move !== null) {
1000 title_elems.push(last_move);
1003 if (title_elems.length != 0) {
1004 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1006 document.title = 'analysis.sesse.net';
1009 // The last move (shown by highlighting the from and to squares).
1010 if (data['position'] && data['position']['last_move_uci']) {
1011 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1012 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1013 } else if (current_display_line_is_history && current_display_move >= 0) {
1014 // We don't have historic analysis for this position, but we
1015 // can reconstruct what the last move was by just replaying
1017 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1018 var moves = hiddenboard.history({ verbose: true });
1019 var last_move = moves.pop();
1020 highlight_from = last_move.from;
1021 highlight_to = last_move.to;
1023 highlight_from = highlight_to = undefined;
1025 update_board_highlight();
1027 if (data['failed']) {
1028 $("#score").text("No analysis for this move");
1029 $("#pvtitle").text("PV:");
1031 $("#searchstats").html(" ");
1032 $("#refutationlines").empty();
1033 $("#whiteclock").empty();
1034 $("#blackclock").empty();
1035 refutation_lines = [];
1036 update_refutation_lines();
1038 update_displayed_line();
1039 update_move_highlight();
1046 if (data['score'] !== null) {
1047 $("#score").text(data['score']);
1050 // The search stats.
1051 if (data['searchstats']) {
1052 $("#searchstats").html(data['searchstats']);
1053 } else if (data['tablebase'] == 1) {
1054 $("#searchstats").text("Tablebase result");
1055 } else if (data['nodes'] && data['nps'] && data['depth']) {
1056 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1057 if (data['seldepth']) {
1058 stats += ' (' + data['seldepth'] + ' selective)';
1060 if (data['tbhits'] && data['tbhits'] > 0) {
1061 if (data['tbhits'] == 1) {
1062 stats += ', one Syzygy hit';
1064 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1068 $("#searchstats").text(stats);
1070 $("#searchstats").text("");
1073 // Update the board itself.
1074 base_fen = data['position']['fen'];
1075 update_displayed_line();
1078 $("#pvtitle").text("PV:");
1079 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay'], 0));
1081 // Update the PV arrow.
1083 if (data['pv_uci'].length >= 1) {
1084 // draw a continuation arrow as long as it's the same piece
1085 for (var i = 0; i < data['pv_uci'].length; i += 2) {
1086 var from = data['pv_uci'][i].substr(0, 2);
1087 var to = data['pv_uci'][i].substr(2,4);
1088 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
1089 interfering_arrow(from, to)) {
1092 create_arrow(from, to, '#f66', 6, 20);
1095 var alt_moves = find_nonstupid_moves(data, 30);
1096 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1097 create_arrow(alt_moves[i].substr(0, 2),
1098 alt_moves[i].substr(2, 2), '#f66', 1, 10);
1102 // See if all semi-reasonable moves have only one possible response.
1103 if (data['pv_uci'].length >= 2) {
1104 var nonstupid_moves = find_nonstupid_moves(data, 300);
1105 var response = data['pv_uci'][1];
1106 for (var i = 0; i < nonstupid_moves.length; ++i) {
1107 if (nonstupid_moves[i] == data['pv_uci'][0]) {
1108 // ignore the PV move for refutation lines.
1111 if (!data['refutation_lines'] ||
1112 !data['refutation_lines'][nonstupid_moves[i]] ||
1113 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1114 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1115 // Incomplete PV, abort.
1116 response = undefined;
1119 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1120 if (response !== this_response) {
1121 // Different response depending on lines, abort.
1122 response = undefined;
1127 if (nonstupid_moves.length > 0 && response !== undefined) {
1128 create_arrow(response.substr(0, 2),
1129 response.substr(2, 2), '#66f', 6, 20);
1133 // Update the refutation lines.
1134 base_fen = data['position']['fen'];
1135 move_num = parseInt(data['position']['move_num']);
1136 toplay = data['position']['toplay'];
1137 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1138 update_refutation_lines();
1140 // Update the sparkline last, since its size depends on how everything else reflowed.
1141 update_sparkline(data);
1144 var update_sparkline = function(data) {
1145 if (data && data['score_history']) {
1146 var first_move_num = undefined;
1147 for (var halfmove_num in data['score_history']) {
1148 halfmove_num = parseInt(halfmove_num);
1149 if (first_move_num === undefined || halfmove_num < first_move_num) {
1150 first_move_num = halfmove_num;
1153 if (first_move_num !== undefined) {
1154 var last_move_num = data['position']['move_num'] * 2 - 3;
1155 if (data['position']['toplay'] === 'B') {
1159 // Possibly truncate some moves if we don't have enough width.
1160 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1161 // #scoresparkcontainer) on Chrome for mobile seems to start off
1162 // at something very small, and then suddenly snap back into place.
1164 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1165 if (last_move_num - first_move_num > max_moves) {
1166 first_move_num = last_move_num - max_moves;
1169 var min_score = -100;
1170 var max_score = 100;
1171 var last_score = null;
1173 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1174 if (data['score_history'][halfmove_num]) {
1175 var score = data['score_history'][halfmove_num][0];
1176 if (score < min_score) min_score = score;
1177 if (score > max_score) max_score = score;
1178 last_score = data['score_history'][halfmove_num][0];
1180 scores.push(last_score);
1182 if (data['plot_score']) {
1183 scores.push(data['plot_score']);
1185 // FIXME: at some widths, calling sparkline() seems to push
1186 // #scorecontainer under the board.
1187 $("#scorespark").sparkline(scores, {
1190 chartRangeMin: min_score,
1191 chartRangeMax: max_score,
1192 tooltipFormatter: function(sparkline, options, fields) {
1193 return format_tooltip(data, fields[0].offset + first_move_num);
1197 $("#scorespark").text("");
1200 $("#scorespark").text("");
1205 * @param {number} num_viewers
1207 var update_num_viewers = function(num_viewers) {
1208 if (num_viewers === null) {
1209 $("#numviewers").text("");
1210 } else if (num_viewers == 1) {
1211 $("#numviewers").text("You are the only current viewer");
1213 $("#numviewers").text(num_viewers + " current viewers");
1217 var update_clock = function() {
1218 clearTimeout(clock_timer);
1220 var data = displayed_analysis_data || current_analysis_data;
1221 if (data['position']) {
1222 var result = data['position']['result'];
1223 if (result === '1-0') {
1224 $("#whiteclock").text("1");
1225 $("#blackclock").text("0");
1226 $("#whiteclock").removeClass("running-clock");
1227 $("#blackclock").removeClass("running-clock");
1230 if (result === '1/2-1/2') {
1231 $("#whiteclock").text("1/2");
1232 $("#blackclock").text("1/2");
1233 $("#whiteclock").removeClass("running-clock");
1234 $("#blackclock").removeClass("running-clock");
1237 if (result === '0-1') {
1238 $("#whiteclock").text("0");
1239 $("#blackclock").text("1");
1240 $("#whiteclock").removeClass("running-clock");
1241 $("#blackclock").removeClass("running-clock");
1246 var white_clock_ms = null;
1247 var black_clock_ms = null;
1248 var show_seconds = false;
1251 if (data['position'] &&
1252 data['position']['white_clock'] &&
1253 data['position']['black_clock']) {
1254 white_clock_ms = data['position']['white_clock'] * 1000;
1255 black_clock_ms = data['position']['black_clock'] * 1000;
1258 // Dynamic clock (only one, obviously).
1260 if (data['position']['white_clock_target']) {
1262 $("#whiteclock").addClass("running-clock");
1263 $("#blackclock").removeClass("running-clock");
1264 } else if (data['position']['black_clock_target']) {
1266 $("#whiteclock").removeClass("running-clock");
1267 $("#blackclock").addClass("running-clock");
1269 $("#whiteclock").removeClass("running-clock");
1270 $("#blackclock").removeClass("running-clock");
1274 var now = new Date().getTime() + client_clock_offset_ms;
1275 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1276 if (color === "white") {
1277 white_clock_ms = remaining_ms;
1279 black_clock_ms = remaining_ms;
1283 if (white_clock_ms === null || black_clock_ms === null) {
1284 $("#whiteclock").empty();
1285 $("#blackclock").empty();
1289 // If either player has ten minutes or less left, add the second counters.
1290 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1293 // See when the clock will change next, and update right after that.
1296 next_update_ms = remaining_ms % 1000 + 100;
1298 next_update_ms = remaining_ms % 60000 + 100;
1300 clock_timer = setTimeout(update_clock, next_update_ms);
1303 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1304 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1308 * @param {Number} remaining_ms
1309 * @param {boolean} show_seconds
1311 var format_clock = function(remaining_ms, show_seconds) {
1312 if (remaining_ms <= 0) {
1320 var remaining = Math.floor(remaining_ms / 1000);
1321 var seconds = remaining % 60;
1322 remaining = (remaining - seconds) / 60;
1323 var minutes = remaining % 60;
1324 remaining = (remaining - minutes) / 60;
1325 var hours = remaining;
1327 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1329 return format_2d(hours) + ":" + format_2d(minutes);
1336 var format_2d = function(x) {
1345 * @param {string} move
1346 * @param {Number} move_num
1347 * @param {boolean} white_to_play
1349 var format_move_with_number = function(move, move_num, white_to_play) {
1351 if (white_to_play) {
1352 ret = (move_num - 1) + '… ';
1354 ret = move_num + '. ';
1361 * @param {string} move
1362 * @param {Number} halfmove_num
1364 var format_halfmove_with_number = function(move, halfmove_num) {
1365 return format_move_with_number(
1367 Math.floor(halfmove_num / 2) + 1,
1368 halfmove_num % 2 == 0);
1372 * @param {Object} data
1373 * @param {Number} halfmove_num
1375 var format_tooltip = function(data, halfmove_num) {
1376 if (data['score_history'][halfmove_num] ||
1377 halfmove_num === data['position']['pretty_history'].length) {
1380 if (halfmove_num === data['position']['pretty_history'].length) {
1381 move = data['position']['last_move'];
1382 short_score = data['short_score'];
1384 move = data['position']['pretty_history'][halfmove_num];
1385 short_score = data['score_history'][halfmove_num][1];
1387 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1389 return "After " + move_with_number + ": " + short_score;
1391 for (var i = halfmove_num; i --> 0; ) {
1392 if (data['score_history'][i]) {
1393 var move = data['position']['pretty_history'][i];
1394 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1401 * @param {boolean} sort_by_score
1403 var resort_refutation_lines = function(sort_by_score) {
1404 sort_refutation_lines_by_score = sort_by_score;
1405 if (supports_html5_storage()) {
1406 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1408 update_refutation_lines();
1410 window['resort_refutation_lines'] = resort_refutation_lines;
1413 * @param {boolean} truncate_history
1415 var set_truncate_history = function(truncate_history) {
1416 truncate_display_history = truncate_history;
1417 update_refutation_lines();
1419 window['set_truncate_history'] = set_truncate_history;
1422 * @param {number} line_num
1423 * @param {number} move_num
1425 var show_line = function(line_num, move_num) {
1426 if (line_num == -1) {
1427 current_display_line = null;
1428 current_display_move = null;
1429 hash_refutation_lines = null;
1430 if (displayed_analysis_data) {
1431 // TODO: Support exiting to history position if we are in an
1432 // analysis line of a history position.
1433 displayed_analysis_data = null;
1438 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1439 current_display_move = move_num + current_display_line.start_display_move_num;
1441 current_display_line_is_history = (line_num == 0);
1443 update_historic_analysis();
1444 update_displayed_line();
1445 update_board_highlight();
1446 update_move_highlight();
1449 window['show_line'] = show_line;
1451 var prev_move = function() {
1452 if (current_display_line &&
1453 current_display_move >= current_display_line.start_display_move_num) {
1454 --current_display_move;
1456 update_historic_analysis();
1457 update_displayed_line();
1458 update_move_highlight();
1460 window['prev_move'] = prev_move;
1462 var next_move = function() {
1463 if (current_display_line &&
1464 current_display_move < current_display_line.pretty_pv.length - 1) {
1465 ++current_display_move;
1467 update_historic_analysis();
1468 update_displayed_line();
1469 update_move_highlight();
1471 window['next_move'] = next_move;
1473 var update_historic_analysis = function() {
1474 if (!current_display_line_is_history) {
1477 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1478 displayed_analysis_data = null;
1482 // Fetch old analysis for this line if it exists.
1483 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1484 var filename = "/history/move" + (current_display_move + 1) + "-" +
1485 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1487 current_historic_xhr = $.ajax({
1489 }).done(function(data, textstatus, xhr) {
1490 displayed_analysis_data = data;
1492 }).fail(function(jqXHR, textStatus, errorThrown) {
1493 if (textStatus === "abort") {
1494 // Aborted because we are switching backends. Don't do anything;
1495 // we will already have been cleared.
1497 displayed_analysis_data = {'failed': true};
1504 * @param {string} fen
1506 var update_imbalance = function(fen) {
1507 var hiddenboard = new Chess(fen);
1508 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1509 for (var row = 0; row < 8; ++row) {
1510 for (var col = 0; col < 8; ++col) {
1511 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1512 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1513 var square = col_text + row_text;
1514 var contents = hiddenboard.get(square);
1515 if (contents !== null) {
1516 if (contents.color === 'w') {
1517 ++imbalance[contents.type];
1519 --imbalance[contents.type];
1524 var white_imbalance = '';
1525 var black_imbalance = '';
1526 for (var piece in imbalance) {
1527 for (var i = 0; i < imbalance[piece]; ++i) {
1528 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1530 for (var i = 0; i < -imbalance[piece]; ++i) {
1531 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1534 $('#whiteimbalance').html(white_imbalance);
1535 $('#blackimbalance').html(black_imbalance);
1538 /** Mark the currently selected move in red.
1539 * Also replaces the PV with the current displayed line if it's not shown
1540 * anywhere else on the screen.
1542 var update_move_highlight = function() {
1543 if (highlighted_move !== null) {
1544 highlighted_move.removeClass('highlight');
1546 if (current_display_line) {
1547 // See if the current displayed line is identical to any of the ones
1548 // we have on screen. (It might not be if e.g. the analysis reloaded
1549 // since we started looking.)
1550 var display_line_num = null;
1551 for (var i = 0; i < display_lines.length; ++i) {
1552 var line = display_lines[i];
1553 if (line.start_display_move_num > 0) continue;
1554 if (current_display_line.start_fen !== line.start_fen) continue;
1555 if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1557 for (var j = 0; j < line.pretty_pv.length; ++j) {
1558 if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1564 display_line_num = i;
1569 if (display_line_num === null) {
1570 // Replace the PV with the (complete) line.
1571 $("#pvtitle").text("Exploring:");
1572 current_display_line.start_display_move_num = 0;
1573 display_lines.push(current_display_line);
1574 $("#pv").html(print_pv(display_lines.length - 1));
1575 display_line_num = display_lines.length - 1;
1578 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1579 highlighted_move.addClass('highlight');
1583 var update_displayed_line = function() {
1584 if (current_display_line === null) {
1585 $("#linenav").hide();
1586 $("#linemsg").show();
1587 display_fen = base_fen;
1588 board.position(base_fen);
1589 update_imbalance(base_fen);
1593 $("#linenav").show();
1594 $("#linemsg").hide();
1596 if (current_display_move <= 0) {
1597 $("#prevmove").html("Previous");
1599 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1601 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1602 $("#nextmove").html("Next");
1604 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1607 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1608 display_fen = hiddenboard.fen();
1609 board_is_animating = true;
1610 var old_fen = board.fen();
1611 board.position(hiddenboard.fen());
1612 if (board.fen() === old_fen) {
1613 board_is_animating = false;
1615 // Fire off a hash request, since we're now off the main position
1616 // and it just changed.
1617 explore_hash(display_fen);
1619 update_imbalance(hiddenboard.fen());
1623 * @param {boolean} param_enable_sound
1625 var set_sound = function(param_enable_sound) {
1626 enable_sound = param_enable_sound;
1628 $("#soundon").html("<strong>On</strong>");
1629 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1631 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1632 // and also preload the file since the user has selected audio.
1633 var ding = document.getElementById('ding');
1634 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1635 ding.src = 'ding.opus';
1639 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1640 $("#soundoff").html("<strong>Off</strong>");
1642 if (supports_html5_storage()) {
1643 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1646 window['set_sound'] = set_sound;
1648 /** Send off a hash probe request to the backend.
1649 * @param {string} fen
1651 var explore_hash = function(fen) {
1652 // If we already have a backend response going, abort it.
1653 if (current_hash_xhr) {
1654 current_hash_xhr.abort();
1656 if (current_hash_display_timer) {
1657 clearTimeout(current_hash_display_timer);
1658 current_hash_display_timer = null;
1660 current_hash_xhr = $.ajax({
1661 url: backend_hash_url + "?fen=" + fen
1662 }).done(function(data, textstatus, xhr) {
1663 show_explore_hash_results(data, fen);
1667 /** Process the JSON response from a hash probe request.
1668 * @param {!Object} data
1669 * @param {string} fen
1671 var show_explore_hash_results = function(data, fen) {
1672 if (board_is_animating) {
1673 // Updating while the animation is still going causes
1674 // the animation to jerk. This is pretty crude, but it will do.
1675 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1678 current_hash_display_timer = null;
1679 hash_refutation_lines = data['lines'];
1684 * @param {string} new_backend_url
1686 var switch_backend = function(new_backend_url) {
1687 // Stop looking at historic data.
1688 current_display_line = null;
1689 current_display_move = null;
1690 displayed_analysis_data = null;
1691 if (current_historic_xhr) {
1692 current_historic_xhr.abort();
1695 // If we already have a backend response going, abort it.
1696 if (current_analysis_xhr) {
1697 current_analysis_xhr.abort();
1699 if (current_hash_xhr) {
1700 current_hash_xhr.abort();
1703 // Otherwise, we should have a timer going to start a new one.
1705 if (current_analysis_request_timer) {
1706 clearTimeout(current_analysis_request_timer);
1707 current_analysis_request_timer = null;
1709 if (current_hash_display_timer) {
1710 clearTimeout(current_hash_display_timer);
1711 current_hash_display_timer = null;
1714 // Request an immediate fetch with the new backend.
1715 backend_url = new_backend_url;
1716 current_analysis_data = null;
1720 window['switch_backend'] = switch_backend;
1722 var init = function() {
1723 unique = get_unique();
1725 // Load settings from HTML5 local storage if available.
1726 if (supports_html5_storage() && localStorage['enable_sound']) {
1727 set_sound(parseInt(localStorage['enable_sound']));
1731 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1732 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1734 sort_refutation_lines_by_score = true;
1738 board = new window.ChessBoard('board', {
1739 onMoveEnd: function() { board_is_animating = false; }
1743 $(window).resize(function() {
1745 update_sparkline(displayed_analysis_data || current_analysis_data);
1746 update_board_highlight();
1749 $(window).keyup(function(event) {
1750 if (event.which == 39) {
1752 } else if (event.which == 37) {
1756 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
1758 $(document).ready(init);