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 /** Currently suggested/recommended move when dragging.
112 * @type {?{from: !string, to: !string}}
115 var recommended_move = null;
117 /** If reverse-dragging (dragging from the destination square to the
118 * source square), the destination square.
122 var reverse_dragging_from = null;
124 /** @type {?number} @private */
127 /** @type {boolean} @private */
128 var enable_sound = false;
131 * Our best estimate of how many milliseconds we need to add to
132 * new Date() to get the true UTC time. Calibrated against the
138 var client_clock_offset_ms = null;
140 var clock_timer = null;
142 /** The current position being analyzed, represented as a FEN string.
143 * Note that this is not necessarily the same as display_fen.
149 /** The current position on the board, represented as a FEN string.
150 * Note that board.fen() does not contain e.g. who is to play.
154 var display_fen = null;
158 * pretty_pv: Array.<string>,
162 * start_display_move_num: number
165 * "start_display_move_num" is the (half-)move number to start displaying the PV at.
166 * "score" is also evaluated at this point.
169 /** All PVs that we currently know of.
171 * Element 0 is history (or null if no history).
172 * Element 1 is current main PV, or explored line if nowhere else on the screen.
173 * All remaining elements are refutation lines (multi-PV).
175 * @type {Array.<DisplayLine>}
178 var display_lines = [];
180 /** @type {?DisplayLine} @private */
181 var current_display_line = null;
183 /** @type {boolean} @private */
184 var current_display_line_is_history = false;
186 /** @type {?number} @private */
187 var current_display_move = null;
190 * The current backend request to get main analysis (not history), if any,
191 * so that we can abort it.
196 var current_analysis_xhr = null;
199 * The current timer to fire off a request to get main analysis (not history),
200 * if any, so that we can abort it.
205 var current_analysis_request_timer = null;
208 * The current backend request to get historic data, if any.
213 var current_historic_xhr = null;
216 * The current backend request to get hash probes, if any, so that we can abort it.
221 var current_hash_xhr = null;
224 * The current timer to display hash probe information (it could be waiting on the
225 * board to stop animating), if any, so that we can abort it.
230 var current_hash_display_timer = null;
232 var supports_html5_storage = function() {
234 return 'localStorage' in window && window['localStorage'] !== null;
240 // Make the unique token persistent so people refreshing the page won't count twice.
241 // Of course, you can never fully protect against people deliberately wanting to spam.
242 var get_unique = function() {
243 var use_local_storage = supports_html5_storage();
244 if (use_local_storage && localStorage['unique']) {
245 return localStorage['unique'];
247 var unique = Math.random();
248 if (use_local_storage) {
249 localStorage['unique'] = unique;
254 var request_update = function() {
255 current_analysis_request_timer = null;
257 current_analysis_xhr = $.ajax({
258 url: backend_url + "?ims=" + ims + "&unique=" + unique
259 }).done(function(data, textstatus, xhr) {
260 sync_server_clock(xhr.getResponseHeader('Date'));
261 ims = xhr.getResponseHeader('X-RGLM');
262 var num_viewers = xhr.getResponseHeader('X-RGNV');
264 if (Array.isArray(data)) {
265 new_data = JSON.parse(JSON.stringify(current_analysis_data));
266 JSON_delta.patch(new_data, data);
271 var minimum_version = xhr.getResponseHeader('X-RGMV');
272 if (minimum_version && minimum_version > SCRIPT_VERSION) {
273 // Upgrade to latest version with a force-reload.
274 location.reload(true);
277 possibly_play_sound(current_analysis_data, new_data);
278 current_analysis_data = new_data;
280 update_num_viewers(num_viewers);
283 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
284 }).fail(function(jqXHR, textStatus, errorThrown) {
285 if (textStatus === "abort") {
286 // Aborted because we are switching backends. Abandon and don't retry,
287 // because another one is already started for us.
289 // Backend error or similar. Wait ten seconds, then try again.
290 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
295 var possibly_play_sound = function(old_data, new_data) {
299 if (old_data === null) {
302 var ding = document.getElementById('ding');
303 if (ding && ding.play) {
304 if (old_data['position'] && old_data['position']['fen'] &&
305 new_data['position'] && new_data['position']['fen'] &&
306 (old_data['position']['fen'] !== new_data['position']['fen'] ||
307 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
314 * @type {!string} server_date_string
316 var sync_server_clock = function(server_date_string) {
317 var server_time_ms = new Date(server_date_string).getTime();
318 var client_time_ms = new Date().getTime();
319 var estimated_offset_ms = server_time_ms - client_time_ms;
321 // In order not to let the noise move us too much back and forth
322 // (the server only has one-second resolution anyway), we only
323 // change an existing skew if we are at least five seconds off.
324 if (client_clock_offset_ms === null ||
325 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
326 client_clock_offset_ms = estimated_offset_ms;
330 var clear_arrows = function() {
331 for (var i = 0; i < arrows.length; ++i) {
333 if (arrows[i].svg.parentElement) {
334 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
336 delete arrows[i].svg;
341 occupied_by_arrows = [];
342 for (var y = 0; y < 8; ++y) {
343 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
347 var redraw_arrows = function() {
348 for (var i = 0; i < arrows.length; ++i) {
349 position_arrow(arrows[i]);
353 /** @param {!number} x
356 var sign = function(x) {
366 /** See if drawing this arrow on the board would cause unduly amount of confusion.
367 * @param {!string} from The square the arrow is from (e.g. e4).
368 * @param {!string} to The square the arrow is to (e.g. e4).
371 var interfering_arrow = function(from, to) {
372 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
373 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
374 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
375 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
377 occupied_by_arrows[from_row][from_col] = true;
379 // Knight move: Just check that we haven't been at the destination before.
380 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
381 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
382 return occupied_by_arrows[to_row][to_col];
385 // Sliding piece: Check if anything except the from-square is seen before.
386 var dx = sign(to_col - from_col);
387 var dy = sign(to_row - from_row);
393 if (occupied_by_arrows[y][x]) {
396 occupied_by_arrows[y][x] = true;
397 } while (x != to_col || y != to_row);
402 /** Find a point along the coordinate system given by the given line,
403 * <t> units forward from the start of the line, <u> units to the right of it.
404 * @param {!number} x1
405 * @param {!number} x2
406 * @param {!number} y1
407 * @param {!number} y2
410 * @return {!string} The point in "x y" form, suitable for SVG paths.
412 var point_from_start = function(x1, y1, x2, y2, t, u) {
416 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
420 var x = x1 + dx * t + dy * u;
421 var y = y1 + dy * t - dx * u;
425 /** Find a point along the coordinate system given by the given line,
426 * <t> units forward from the end of the line, <u> units to the right of it.
427 * @param {!number} x1
428 * @param {!number} x2
429 * @param {!number} y1
430 * @param {!number} y2
433 * @return {!string} The point in "x y" form, suitable for SVG paths.
435 var point_from_end = function(x1, y1, x2, y2, t, u) {
439 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
443 var x = x2 + dx * t + dy * u;
444 var y = y2 + dy * t - dx * u;
448 var position_arrow = function(arrow) {
450 if (arrow.svg.parentElement) {
451 arrow.svg.parentElement.removeChild(arrow.svg);
455 if (current_display_line !== null && !current_display_line_is_history) {
459 var pos = $(".square-a8").position();
461 var zoom_factor = $("#board").width() / 400.0;
462 var line_width = arrow.line_width * zoom_factor;
463 var arrow_size = arrow.arrow_size * zoom_factor;
465 var square_width = $(".square-a8").width();
466 var from_y = (7 - arrow.from_row + 0.5)*square_width;
467 var to_y = (7 - arrow.to_row + 0.5)*square_width;
468 var from_x = (arrow.from_col + 0.5)*square_width;
469 var to_x = (arrow.to_col + 0.5)*square_width;
471 var SVG_NS = "http://www.w3.org/2000/svg";
472 var XHTML_NS = "http://www.w3.org/1999/xhtml";
473 var svg = document.createElementNS(SVG_NS, "svg");
474 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
475 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
476 svg.setAttribute("style", "position: absolute");
477 svg.setAttribute("position", "absolute");
478 svg.setAttribute("version", "1.1");
479 svg.setAttribute("class", "c1");
480 svg.setAttribute("xmlns", XHTML_NS);
488 var outline = document.createElementNS(SVG_NS, "path");
489 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));
490 outline.setAttribute("xmlns", XHTML_NS);
491 outline.setAttribute("stroke", "#666");
492 outline.setAttribute("stroke-width", line_width + 2);
493 outline.setAttribute("fill", "none");
494 svg.appendChild(outline);
496 var path = document.createElementNS(SVG_NS, "path");
497 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));
498 path.setAttribute("xmlns", XHTML_NS);
499 path.setAttribute("stroke", arrow.fg_color);
500 path.setAttribute("stroke-width", line_width);
501 path.setAttribute("fill", "none");
502 svg.appendChild(path);
504 // Then the arrow head.
505 var head = document.createElementNS(SVG_NS, "path");
506 head.setAttribute("d",
507 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
508 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
509 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
510 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
511 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
512 head.setAttribute("xmlns", XHTML_NS);
513 head.setAttribute("stroke", "#000");
514 head.setAttribute("stroke-width", "1");
515 head.setAttribute("fill", arrow.fg_color);
516 svg.appendChild(head);
518 $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
519 document.body.appendChild(svg);
524 * @param {!string} from_square
525 * @param {!string} to_square
526 * @param {!string} fg_color
527 * @param {number} line_width
528 * @param {number} arrow_size
530 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
531 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
532 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
533 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
534 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
542 line_width: line_width,
543 arrow_size: arrow_size,
547 position_arrow(arrow);
551 // Note: invert is ignored.
552 var compare_by_sort_key = function(refutation_lines, invert, a, b) {
553 var ska = refutation_lines[a]['sort_key'];
554 var skb = refutation_lines[b]['sort_key'];
555 if (ska < skb) return -1;
556 if (ska > skb) return 1;
560 var compare_by_score = function(refutation_lines, invert, a, b) {
561 var sa = compute_score_sort_key(refutation_lines[b]['score'], invert);
562 var sb = compute_score_sort_key(refutation_lines[a]['score'], invert);
567 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
568 * sorted by quality, descending.
570 * @param {!Object} data
571 * @param {number} margin The maximum number of centipawns worse than the
572 * best move can be and still be included.
573 * @param {boolean} margin Whether black is to play.
574 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
575 * moves, in score order.
577 var find_nonstupid_moves = function(data, margin, invert) {
578 // First of all, if there are any moves that are more than 0.5 ahead of
579 // the primary move, the refutation lines are probably bunk, so just
581 var best_score = undefined;
582 var pv_score = undefined;
583 for (var move in data['refutation_lines']) {
584 var score = compute_score_sort_key(data['refutation_lines'][move]['score'], invert);
585 if (move == data['pv_uci'][0]) {
588 if (best_score === undefined || score > best_score) {
591 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
596 if (best_score - pv_score > 50) {
600 // Now find all moves that are within “margin” of the best score.
601 // The PV move will always be first.
603 for (var move in data['refutation_lines']) {
604 var score = compute_score_sort_key(data['refutation_lines'][move]['score'], invert);
605 if (move != data['pv_uci'][0] && best_score - score <= margin) {
609 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
610 moves.unshift(data['pv_uci'][0]);
619 var thousands = function(x) {
620 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
624 * @param {!string} start_fen
625 * @param {Array.<string>} pretty_pv
626 * @param {number} move_num
627 * @param {!string} toplay
628 * @param {!string} score
629 * @param {number} start_display_move_num
630 * @param {number=} opt_limit
631 * @param {boolean=} opt_showlast
633 var add_pv = function(start_fen, pretty_pv, move_num, toplay, score, start_display_move_num, opt_limit, opt_showlast) {
635 start_fen: start_fen,
636 pretty_pv: pretty_pv,
637 move_num: parseInt(move_num),
640 start_display_move_num: start_display_move_num
642 return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
646 * @param {number} line_num
647 * @param {number=} opt_limit
648 * @param {boolean=} opt_showlast
650 var print_pv = function(line_num, opt_limit, opt_showlast) {
651 var display_line = display_lines[line_num];
652 var pretty_pv = display_line.pretty_pv;
653 var move_num = display_line.move_num;
654 var toplay = display_line.toplay;
656 // Truncate PV at the start if needed.
657 var start_display_move_num = display_line.start_display_move_num;
658 if (start_display_move_num > 0) {
659 pretty_pv = pretty_pv.slice(start_display_move_num);
660 var to_add = start_display_move_num;
661 if (toplay === 'B') {
666 if (to_add % 2 == 1) {
670 move_num += to_add / 2;
675 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
676 // Truncate the PV at the beginning (instead of at the end).
677 // We assume here that toplay is 'W'. We also assume that if
678 // opt_showlast is set, then it is the history, and thus,
679 // the UI should be to expand the history.
680 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
681 i = pretty_pv.length - opt_limit;
686 } else if (toplay == 'B' && pretty_pv.length > 0) {
687 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
688 pv = move_num + '. … ' + move;
693 for ( ; i < pretty_pv.length; ++i) {
694 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
697 if (i > opt_limit && !opt_showlast) {
703 pv += move_num + '. ' + move;
714 /** Update the highlighted to/from squares on the board.
715 * Based on the global "highlight_from" and "highlight_to" variables.
717 var update_board_highlight = function() {
718 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
719 if ((current_display_line === null || current_display_line_is_history) &&
720 highlight_from !== undefined && highlight_to !== undefined) {
721 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
722 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
726 var update_history = function() {
727 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
728 $("#history").html("No history");
729 } else if (truncate_display_history) {
730 $("#history").html(print_pv(0, 8, true));
733 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
734 print_pv(0, 1, 'W'));
739 * @param {!boolean} truncate_history
741 var collapse_history = function(truncate_history) {
742 truncate_display_history = truncate_history;
745 window['collapse_history'] = collapse_history;
747 /** Update the HTML display of multi-PV from the global "refutation_lines".
749 * Also recreates the global "display_lines".
751 var update_refutation_lines = function() {
752 if (base_fen === null) {
755 if (display_lines.length > 2) {
756 // Truncate so that only the history and PV is left.
757 display_lines = [ display_lines[0], display_lines[1] ];
759 var tbl = $("#refutationlines");
762 // Find out where the lines start from.
764 var start_display_move_num = 0;
765 if (hash_refutation_lines) {
766 base_line = current_display_line.pretty_pv.slice(0, current_display_move + 1);
767 start_display_move_num = base_line.length;
771 for (var move in refutation_lines) {
775 var invert = (toplay === 'B');
776 if (current_display_line && current_display_move % 2 == 0) {
779 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
780 moves = moves.sort(function(a, b) { return compare(refutation_lines, invert, a, b) });
781 for (var i = 0; i < moves.length; ++i) {
782 var line = refutation_lines[moves[i]];
784 var tr = document.createElement("tr");
786 var move_td = document.createElement("td");
787 tr.appendChild(move_td);
788 $(move_td).addClass("move");
790 if (line['pv_pretty'].length == 0) {
791 // Not found, so just make a one-move PV.
792 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
793 $(move_td).html(move);
794 var score_td = document.createElement("td");
796 $(score_td).addClass("score");
797 $(score_td).text("—");
798 tr.appendChild(score_td);
800 var depth_td = document.createElement("td");
801 tr.appendChild(depth_td);
802 $(depth_td).addClass("depth");
803 $(depth_td).text("—");
805 var pv_td = document.createElement("td");
806 tr.appendChild(pv_td);
807 $(pv_td).addClass("pv");
808 $(pv_td).html(add_pv(base_fen, base_line.concat([ line['pretty_move'] ]), move_num, toplay, line['score'], start_display_move_num));
814 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
815 $(move_td).html(move);
817 var score_td = document.createElement("td");
818 tr.appendChild(score_td);
819 $(score_td).addClass("score");
820 $(score_td).text(format_short_score(line['score']));
822 var depth_td = document.createElement("td");
823 tr.appendChild(depth_td);
824 $(depth_td).addClass("depth");
825 if (line['depth'] && line['depth'] >= 0) {
826 $(depth_td).text("d" + line['depth']);
828 $(depth_td).text("—");
831 var pv_td = document.createElement("td");
832 tr.appendChild(pv_td);
833 $(pv_td).addClass("pv");
834 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv_pretty']), move_num, toplay, line['score'], start_display_move_num, 10));
839 // Make one of the links clickable and the other nonclickable.
840 if (sort_refutation_lines_by_score) {
841 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
842 $("#sortbyscore1").html("<strong>Score</strong>");
844 $("#sortbyscore0").html("<strong>Move</strong>");
845 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
848 // Update the move highlight, as we've rewritten all the HTML.
849 update_move_highlight();
853 * Create a Chess.js board object, containing the given position plus the given moves,
854 * up to the given limit.
856 * @param {?string} fen
857 * @param {Array.<string>} moves
858 * @param {number} last_move
860 var chess_from = function(fen, moves, last_move) {
861 var hiddenboard = new Chess();
863 hiddenboard.load(fen);
865 for (var i = 0; i <= last_move; ++i) {
866 if (moves[i] === '0-0') {
867 hiddenboard.move('O-O');
868 } else if (moves[i] === '0-0-0') {
869 hiddenboard.move('O-O-O');
871 hiddenboard.move(moves[i]);
877 var update_game_list = function(games) {
878 $("#games").text("");
879 if (games === null) {
883 var games_div = document.getElementById('games');
884 for (var game_num = 0; game_num < games.length; ++game_num) {
885 var game = games[game_num];
886 var game_span = document.createElement("span");
887 game_span.setAttribute("class", "game");
889 var game_name = document.createTextNode(game['name']);
890 if (game['url'] === backend_url) {
891 game_span.appendChild(game_name);
893 var game_a = document.createElement("a");
894 game_a.setAttribute("href", "#" + game['id']);
895 game_a.appendChild(game_name);
896 game_span.appendChild(game_a);
898 games_div.appendChild(game_span);
903 * Try to find a running game that matches with the current hash,
904 * and switch to it if we're not already displaying it.
906 var possibly_switch_game_from_hash = function() {
907 if (current_games === null) {
911 var hash = window.location.hash.replace(/^#/,'');
912 for (var i = 0; i < current_games.length; ++i) {
913 if (current_games[i]['id'] === hash) {
914 if (backend_url !== current_games[i]['url']) {
915 switch_backend(current_games[i]['url'], current_games[i]['hashurl']);
922 /** Update all the HTML on the page, based on current global state.
924 var update_board = function() {
925 var data = displayed_analysis_data || current_analysis_data;
926 var current_data = current_analysis_data; // Convenience alias.
930 // Print the history. This is pretty much the only thing that's
931 // unconditionally taken from current_data (we're not interested in
932 // historic history).
933 if (current_data['position']['pretty_history']) {
934 add_pv('start', current_data['position']['pretty_history'], 1, 'W', null, 0, 8, true);
936 display_lines.push(null);
940 // Games currently in progress, if any.
941 if (current_data['games']) {
942 current_games = current_data['games'];
943 possibly_switch_game_from_hash();
944 update_game_list(current_data['games']);
946 current_games = null;
947 update_game_list(null);
950 // The headline. Names are always fetched from current_data;
951 // the rest can depend a bit.
954 current_data['position']['player_w'] && current_data['position']['player_b']) {
955 headline = current_data['position']['player_w'] + '–' +
956 current_data['position']['player_b'] + ', analysis';
958 headline = 'Analysis';
961 // Credits, where applicable. Note that we don't want the footer to change a lot
962 // when e.g. viewing history, so if any of these changed during the game,
963 // use the current one still.
964 if (current_data['using_lomonosov']) {
965 $("#lomonosov").show();
967 $("#lomonosov").hide();
970 // Credits: The engine name/version.
971 if (current_data['engine'] && current_data['engine']['name'] !== null) {
972 $("#engineid").text(current_data['engine']['name']);
975 // Credits: The engine URL.
976 if (current_data['engine'] && current_data['engine']['url']) {
977 $("#engineid").attr("href", current_data['engine']['url']);
979 $("#engineid").removeAttr("href");
982 // Credits: Engine details.
983 if (current_data['engine'] && current_data['engine']['details']) {
984 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
986 $("#enginedetails").text("");
989 // Credits: Move source, possibly with URL.
990 if (current_data['move_source'] && current_data['move_source_url']) {
991 $("#movesource").text("Moves provided by ");
992 var movesource_a = document.createElement("a");
993 movesource_a.setAttribute("href", current_data['move_source_url']);
994 var movesource_text = document.createTextNode(current_data['move_source']);
995 movesource_a.appendChild(movesource_text);
996 var movesource_period = document.createTextNode(".");
997 document.getElementById("movesource").appendChild(movesource_a);
998 document.getElementById("movesource").appendChild(movesource_period);
999 } else if (current_data['move_source']) {
1000 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
1002 $("#movesource").text("");
1006 if (displayed_analysis_data) {
1007 // Displaying some non-current position, pick out the last move
1008 // from the history. This will work even if the fetch failed.
1009 last_move = format_halfmove_with_number(
1010 current_display_line.pretty_pv[current_display_move],
1011 current_display_move + 1);
1012 headline += ' after ' + last_move;
1013 } else if (data['position']['last_move'] !== 'none') {
1014 last_move = format_move_with_number(
1015 data['position']['last_move'],
1016 data['position']['move_num'],
1017 data['position']['toplay'] == 'W');
1018 headline += ' after ' + last_move;
1022 $("#headline").text(headline);
1024 // The <title> contains a very brief headline.
1025 var title_elems = [];
1026 if (data['score']) {
1027 title_elems.push(format_short_score(data['score']).replace(/^ /, ""));
1029 if (last_move !== null) {
1030 title_elems.push(last_move);
1033 if (title_elems.length != 0) {
1034 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1036 document.title = 'analysis.sesse.net';
1039 // The last move (shown by highlighting the from and to squares).
1040 if (data['position'] && data['position']['last_move_uci']) {
1041 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1042 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1043 } else if (current_display_line_is_history && current_display_move >= 0) {
1044 // We don't have historic analysis for this position, but we
1045 // can reconstruct what the last move was by just replaying
1047 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1048 var moves = hiddenboard.history({ verbose: true });
1049 var last_move = moves.pop();
1050 highlight_from = last_move.from;
1051 highlight_to = last_move.to;
1053 highlight_from = highlight_to = undefined;
1055 update_board_highlight();
1057 if (data['failed']) {
1058 $("#score").text("No analysis for this move");
1059 $("#pvtitle").text("PV:");
1061 $("#searchstats").html(" ");
1062 $("#refutationlines").empty();
1063 $("#whiteclock").empty();
1064 $("#blackclock").empty();
1065 refutation_lines = [];
1066 update_refutation_lines();
1068 update_displayed_line();
1069 update_move_highlight();
1076 if (current_display_line) {
1077 if (current_display_line.score) {
1078 $("#score").text(format_long_score(current_display_line.score));
1080 $("#score").text("No score for this move");
1082 } else if (data['score']) {
1083 $("#score").text(format_long_score(data['score']));
1086 // The search stats.
1087 if (data['searchstats']) {
1088 $("#searchstats").html(data['searchstats']);
1089 } else if (data['tablebase'] == 1) {
1090 $("#searchstats").text("Tablebase result");
1091 } else if (data['nodes'] && data['nps'] && data['depth']) {
1092 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1093 if (data['seldepth']) {
1094 stats += ' (' + data['seldepth'] + ' selective)';
1096 if (data['tbhits'] && data['tbhits'] > 0) {
1097 if (data['tbhits'] == 1) {
1098 stats += ', one Syzygy hit';
1100 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1104 $("#searchstats").text(stats);
1106 $("#searchstats").text("");
1109 // Update the board itself.
1110 base_fen = data['position']['fen'];
1111 update_displayed_line();
1114 $("#pvtitle").text("PV:");
1115 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay'], data['score'], 0));
1117 // Update the PV arrow.
1119 if (data['pv_uci'].length >= 1) {
1120 // draw a continuation arrow as long as it's the same piece
1121 for (var i = 0; i < data['pv_uci'].length; i += 2) {
1122 var from = data['pv_uci'][i].substr(0, 2);
1123 var to = data['pv_uci'][i].substr(2,4);
1124 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
1125 interfering_arrow(from, to)) {
1128 create_arrow(from, to, '#f66', 6, 20);
1131 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1132 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1133 create_arrow(alt_moves[i].substr(0, 2),
1134 alt_moves[i].substr(2, 2), '#f66', 1, 10);
1138 // See if all semi-reasonable moves have only one possible response.
1139 if (data['pv_uci'].length >= 2) {
1140 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1141 var response = data['pv_uci'][1];
1142 for (var i = 0; i < nonstupid_moves.length; ++i) {
1143 if (nonstupid_moves[i] == data['pv_uci'][0]) {
1144 // ignore the PV move for refutation lines.
1147 if (!data['refutation_lines'] ||
1148 !data['refutation_lines'][nonstupid_moves[i]] ||
1149 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1150 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1151 // Incomplete PV, abort.
1152 response = undefined;
1155 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1156 if (response !== this_response) {
1157 // Different response depending on lines, abort.
1158 response = undefined;
1163 if (nonstupid_moves.length > 0 && response !== undefined) {
1164 create_arrow(response.substr(0, 2),
1165 response.substr(2, 2), '#66f', 6, 20);
1169 // Update the refutation lines.
1170 base_fen = data['position']['fen'];
1171 move_num = parseInt(data['position']['move_num']);
1172 toplay = data['position']['toplay'];
1173 refutation_lines = hash_refutation_lines || data['refutation_lines'];
1174 update_refutation_lines();
1176 // Update the sparkline last, since its size depends on how everything else reflowed.
1177 update_sparkline(data);
1180 var update_sparkline = function(data) {
1181 if (data && data['score_history']) {
1182 var first_move_num = undefined;
1183 for (var halfmove_num in data['score_history']) {
1184 halfmove_num = parseInt(halfmove_num);
1185 if (first_move_num === undefined || halfmove_num < first_move_num) {
1186 first_move_num = halfmove_num;
1189 if (first_move_num !== undefined) {
1190 var last_move_num = data['position']['move_num'] * 2 - 3;
1191 if (data['position']['toplay'] === 'B') {
1195 // Possibly truncate some moves if we don't have enough width.
1196 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1197 // #scoresparkcontainer) on Chrome for mobile seems to start off
1198 // at something very small, and then suddenly snap back into place.
1200 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1201 if (last_move_num - first_move_num > max_moves) {
1202 first_move_num = last_move_num - max_moves;
1205 var min_score = -100;
1206 var max_score = 100;
1207 var last_score = null;
1209 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1210 if (data['score_history'][halfmove_num]) {
1211 var score = compute_plot_score(data['score_history'][halfmove_num]);
1213 if (score < min_score) min_score = score;
1214 if (score > max_score) max_score = score;
1216 scores.push(last_score);
1218 if (data['score']) {
1219 scores.push(compute_plot_score(data['score']));
1221 // FIXME: at some widths, calling sparkline() seems to push
1222 // #scorecontainer under the board.
1223 $("#scorespark").sparkline(scores, {
1226 chartRangeMin: min_score,
1227 chartRangeMax: max_score,
1228 tooltipFormatter: function(sparkline, options, fields) {
1229 return format_tooltip(data, fields[0].offset + first_move_num);
1233 $("#scorespark").text("");
1236 $("#scorespark").text("");
1241 * @param {number} num_viewers
1243 var update_num_viewers = function(num_viewers) {
1244 if (num_viewers === null) {
1245 $("#numviewers").text("");
1246 } else if (num_viewers == 1) {
1247 $("#numviewers").text("You are the only current viewer");
1249 $("#numviewers").text(num_viewers + " current viewers");
1253 var update_clock = function() {
1254 clearTimeout(clock_timer);
1256 var data = displayed_analysis_data || current_analysis_data;
1257 if (data['position']) {
1258 var result = data['position']['result'];
1259 if (result === '1-0') {
1260 $("#whiteclock").text("1");
1261 $("#blackclock").text("0");
1262 $("#whiteclock").removeClass("running-clock");
1263 $("#blackclock").removeClass("running-clock");
1266 if (result === '1/2-1/2') {
1267 $("#whiteclock").text("1/2");
1268 $("#blackclock").text("1/2");
1269 $("#whiteclock").removeClass("running-clock");
1270 $("#blackclock").removeClass("running-clock");
1273 if (result === '0-1') {
1274 $("#whiteclock").text("0");
1275 $("#blackclock").text("1");
1276 $("#whiteclock").removeClass("running-clock");
1277 $("#blackclock").removeClass("running-clock");
1282 var white_clock_ms = null;
1283 var black_clock_ms = null;
1284 var show_seconds = false;
1287 if (data['position'] &&
1288 data['position']['white_clock'] &&
1289 data['position']['black_clock']) {
1290 white_clock_ms = data['position']['white_clock'] * 1000;
1291 black_clock_ms = data['position']['black_clock'] * 1000;
1294 // Dynamic clock (only one, obviously).
1296 if (data['position']['white_clock_target']) {
1298 $("#whiteclock").addClass("running-clock");
1299 $("#blackclock").removeClass("running-clock");
1300 } else if (data['position']['black_clock_target']) {
1302 $("#whiteclock").removeClass("running-clock");
1303 $("#blackclock").addClass("running-clock");
1305 $("#whiteclock").removeClass("running-clock");
1306 $("#blackclock").removeClass("running-clock");
1310 var now = new Date().getTime() + client_clock_offset_ms;
1311 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1312 if (color === "white") {
1313 white_clock_ms = remaining_ms;
1315 black_clock_ms = remaining_ms;
1319 if (white_clock_ms === null || black_clock_ms === null) {
1320 $("#whiteclock").empty();
1321 $("#blackclock").empty();
1325 // If either player has ten minutes or less left, add the second counters.
1326 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1329 // See when the clock will change next, and update right after that.
1332 next_update_ms = remaining_ms % 1000 + 100;
1334 next_update_ms = remaining_ms % 60000 + 100;
1336 clock_timer = setTimeout(update_clock, next_update_ms);
1339 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1340 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1344 * @param {Number} remaining_ms
1345 * @param {boolean} show_seconds
1347 var format_clock = function(remaining_ms, show_seconds) {
1348 if (remaining_ms <= 0) {
1356 var remaining = Math.floor(remaining_ms / 1000);
1357 var seconds = remaining % 60;
1358 remaining = (remaining - seconds) / 60;
1359 var minutes = remaining % 60;
1360 remaining = (remaining - minutes) / 60;
1361 var hours = remaining;
1363 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1365 return format_2d(hours) + ":" + format_2d(minutes);
1372 var format_2d = function(x) {
1381 * @param {string} move
1382 * @param {Number} move_num
1383 * @param {boolean} white_to_play
1385 var format_move_with_number = function(move, move_num, white_to_play) {
1387 if (white_to_play) {
1388 ret = (move_num - 1) + '… ';
1390 ret = move_num + '. ';
1397 * @param {string} move
1398 * @param {Number} halfmove_num
1400 var format_halfmove_with_number = function(move, halfmove_num) {
1401 return format_move_with_number(
1403 Math.floor(halfmove_num / 2) + 1,
1404 halfmove_num % 2 == 0);
1408 * @param {Object} data
1409 * @param {Number} halfmove_num
1411 var format_tooltip = function(data, halfmove_num) {
1412 if (data['score_history'][halfmove_num] ||
1413 halfmove_num === data['position']['pretty_history'].length) {
1416 if (halfmove_num === data['position']['pretty_history'].length) {
1417 move = data['position']['last_move'];
1418 short_score = format_short_score(data['score']);
1420 move = data['position']['pretty_history'][halfmove_num];
1421 short_score = format_short_score(data['score_history'][halfmove_num]);
1423 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1425 return "After " + move_with_number + ": " + short_score;
1427 for (var i = halfmove_num; i --> 0; ) {
1428 if (data['score_history'][i]) {
1429 var move = data['position']['pretty_history'][i];
1430 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1437 * @param {boolean} sort_by_score
1439 var resort_refutation_lines = function(sort_by_score) {
1440 sort_refutation_lines_by_score = sort_by_score;
1441 if (supports_html5_storage()) {
1442 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1444 update_refutation_lines();
1446 window['resort_refutation_lines'] = resort_refutation_lines;
1449 * @param {boolean} truncate_history
1451 var set_truncate_history = function(truncate_history) {
1452 truncate_display_history = truncate_history;
1453 update_refutation_lines();
1455 window['set_truncate_history'] = set_truncate_history;
1458 * @param {number} line_num
1459 * @param {number} move_num
1461 var show_line = function(line_num, move_num) {
1462 if (line_num == -1) {
1463 current_display_line = null;
1464 current_display_move = null;
1465 hash_refutation_lines = null;
1466 if (displayed_analysis_data) {
1467 // TODO: Support exiting to history position if we are in an
1468 // analysis line of a history position.
1469 displayed_analysis_data = null;
1474 current_display_line = jQuery.extend({}, display_lines[line_num]); // Shallow clone.
1475 current_display_move = move_num + current_display_line.start_display_move_num;
1477 current_display_line_is_history = (line_num == 0);
1479 update_historic_analysis();
1480 update_displayed_line();
1481 update_board_highlight();
1482 update_move_highlight();
1485 window['show_line'] = show_line;
1487 var prev_move = function() {
1488 if (current_display_line &&
1489 current_display_move >= current_display_line.start_display_move_num) {
1490 --current_display_move;
1492 update_historic_analysis();
1493 update_displayed_line();
1494 update_move_highlight();
1496 window['prev_move'] = prev_move;
1498 var next_move = function() {
1499 if (current_display_line &&
1500 current_display_move < current_display_line.pretty_pv.length - 1) {
1501 ++current_display_move;
1503 update_historic_analysis();
1504 update_displayed_line();
1505 update_move_highlight();
1507 window['next_move'] = next_move;
1509 var update_historic_analysis = function() {
1510 if (!current_display_line_is_history) {
1513 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1514 displayed_analysis_data = null;
1518 // Fetch old analysis for this line if it exists.
1519 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1520 var filename = "/history/move" + (current_display_move + 1) + "-" +
1521 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1523 current_historic_xhr = $.ajax({
1525 }).done(function(data, textstatus, xhr) {
1526 displayed_analysis_data = data;
1528 }).fail(function(jqXHR, textStatus, errorThrown) {
1529 if (textStatus === "abort") {
1530 // Aborted because we are switching backends. Don't do anything;
1531 // we will already have been cleared.
1533 displayed_analysis_data = {'failed': true};
1540 * @param {string} fen
1542 var update_imbalance = function(fen) {
1543 var hiddenboard = new Chess(fen);
1544 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1545 for (var row = 0; row < 8; ++row) {
1546 for (var col = 0; col < 8; ++col) {
1547 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1548 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1549 var square = col_text + row_text;
1550 var contents = hiddenboard.get(square);
1551 if (contents !== null) {
1552 if (contents.color === 'w') {
1553 ++imbalance[contents.type];
1555 --imbalance[contents.type];
1560 var white_imbalance = '';
1561 var black_imbalance = '';
1562 for (var piece in imbalance) {
1563 for (var i = 0; i < imbalance[piece]; ++i) {
1564 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1566 for (var i = 0; i < -imbalance[piece]; ++i) {
1567 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1570 $('#whiteimbalance').html(white_imbalance);
1571 $('#blackimbalance').html(black_imbalance);
1574 /** Mark the currently selected move in red.
1575 * Also replaces the PV with the current displayed line if it's not shown
1576 * anywhere else on the screen.
1578 var update_move_highlight = function() {
1579 if (highlighted_move !== null) {
1580 highlighted_move.removeClass('highlight');
1582 if (current_display_line) {
1583 var display_line_num = find_display_line_matching_num();
1584 if (display_line_num === null) {
1585 // Replace the PV with the (complete) line.
1586 $("#pvtitle").text("Exploring:");
1587 current_display_line.start_display_move_num = 0;
1588 display_lines.push(current_display_line);
1589 $("#pv").html(print_pv(display_lines.length - 1));
1590 display_line_num = display_lines.length - 1;
1593 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1594 highlighted_move.addClass('highlight');
1599 * See if the current displayed line is identical to any of the ones
1600 * we have on screen. (It might not be if e.g. the analysis reloaded
1601 * since we started looking.)
1605 var find_display_line_matching_num = function() {
1606 for (var i = 0; i < display_lines.length; ++i) {
1607 var line = display_lines[i];
1608 if (line.start_display_move_num > 0) continue;
1609 if (current_display_line.start_fen !== line.start_fen) continue;
1610 if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1612 for (var j = 0; j < line.pretty_pv.length; ++j) {
1613 if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1625 var update_displayed_line = function() {
1626 if (current_display_line === null) {
1627 $("#linenav").hide();
1628 $("#linemsg").show();
1629 display_fen = base_fen;
1630 board.position(base_fen);
1631 update_imbalance(base_fen);
1635 $("#linenav").show();
1636 $("#linemsg").hide();
1638 if (current_display_move <= 0) {
1639 $("#prevmove").html("Previous");
1641 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1643 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1644 $("#nextmove").html("Next");
1646 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1649 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1650 display_fen = hiddenboard.fen();
1651 board_is_animating = true;
1652 var old_fen = board.fen();
1653 board.position(hiddenboard.fen());
1654 if (board.fen() === old_fen) {
1655 board_is_animating = false;
1656 } else if (!current_display_line_is_history) {
1657 // Fire off a hash request, since we're now off the main position
1658 // and it just changed.
1659 explore_hash(display_fen);
1661 update_imbalance(hiddenboard.fen());
1665 * @param {boolean} param_enable_sound
1667 var set_sound = function(param_enable_sound) {
1668 enable_sound = param_enable_sound;
1670 $("#soundon").html("<strong>On</strong>");
1671 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1673 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1674 // and also preload the file since the user has selected audio.
1675 var ding = document.getElementById('ding');
1676 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1677 ding.src = 'ding.opus';
1681 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1682 $("#soundoff").html("<strong>Off</strong>");
1684 if (supports_html5_storage()) {
1685 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1688 window['set_sound'] = set_sound;
1690 /** Send off a hash probe request to the backend.
1691 * @param {string} fen
1693 var explore_hash = function(fen) {
1694 // If we already have a backend response going, abort it.
1695 if (current_hash_xhr) {
1696 current_hash_xhr.abort();
1698 if (current_hash_display_timer) {
1699 clearTimeout(current_hash_display_timer);
1700 current_hash_display_timer = null;
1702 $("#refutationlines").empty();
1703 current_hash_xhr = $.ajax({
1704 url: backend_hash_url + "?fen=" + fen
1705 }).done(function(data, textstatus, xhr) {
1706 show_explore_hash_results(data, fen);
1710 /** Process the JSON response from a hash probe request.
1711 * @param {!Object} data
1712 * @param {string} fen
1714 var show_explore_hash_results = function(data, fen) {
1715 if (board_is_animating) {
1716 // Updating while the animation is still going causes
1717 // the animation to jerk. This is pretty crude, but it will do.
1718 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1721 current_hash_display_timer = null;
1722 hash_refutation_lines = data['lines'];
1726 // almost all of this stuff comes from the chessboard.js example page
1727 var onDragStart = function(source, piece, position, orientation) {
1728 var pseudogame = new Chess(display_fen);
1729 if (pseudogame.game_over() === true ||
1730 (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1731 (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1735 recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1736 if (recommended_move) {
1737 var squareEl = $('#board .square-' + recommended_move.to);
1738 squareEl.addClass('highlight1-32417');
1743 var mousedownSquare = function(e) {
1744 reverse_dragging_from = null;
1745 var square = $(this).attr('data-square');
1747 var pseudogame = new Chess(display_fen);
1748 if (pseudogame.game_over() === true) {
1752 // If the square is empty, or has a piece of the side not to move,
1753 // we handle it. If not, normal piece dragging will take it.
1754 var position = board.position();
1755 if (!position.hasOwnProperty(square) ||
1756 (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1757 (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1758 reverse_dragging_from = square;
1759 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1760 if (recommended_move) {
1761 var squareEl = $('#board .square-' + recommended_move.from);
1762 squareEl.addClass('highlight1-32417');
1763 squareEl = $('#board .square-' + recommended_move.to);
1764 squareEl.addClass('highlight1-32417');
1769 var mouseupSquare = function(e) {
1770 if (reverse_dragging_from === null) {
1773 var source = $(this).attr('data-square');
1774 var target = reverse_dragging_from;
1775 reverse_dragging_from = null;
1776 if (onDrop(source, target) !== 'snapback') {
1777 onSnapEnd(source, target);
1779 $("#board").find('.square-55d63').removeClass('highlight1-32417');
1782 var get_best_move = function(game, source, target, invert) {
1783 var moves = game.moves({ verbose: true });
1784 if (source !== null) {
1785 moves = moves.filter(function(move) { return move.from == source; });
1787 if (target !== null) {
1788 moves = moves.filter(function(move) { return move.to == target; });
1790 if (moves.length == 0) {
1793 if (moves.length == 1) {
1797 // More than one move. Use the display lines (if we have them)
1798 // to disambiguate; otherwise, we have no information.
1800 for (var i = 0; i < moves.length; ++i) {
1801 move_hash[moves[i].san] = moves[i];
1804 // History and PV take priority over the display lines.
1805 for (var i = 0; i < 2; ++i) {
1806 var line = display_lines[i];
1807 var first_move = line.pretty_pv[line.start_display_move_num];
1808 if (move_hash[first_move]) {
1809 return move_hash[first_move];
1813 var best_move = null;
1814 var best_move_score = null;
1816 for (var move in refutation_lines) {
1817 var line = refutation_lines[move];
1818 if (!line['score']) {
1821 var first_move = line['pv_pretty'][0];
1822 if (move_hash[first_move]) {
1823 var score = compute_score_sort_key(line['score'], invert);
1824 if (best_move_score === null || score > best_move_score) {
1825 best_move = move_hash[first_move];
1826 best_move_score = score;
1833 var onDrop = function(source, target) {
1834 if (source === target) {
1835 if (recommended_move === null) {
1838 // Accept the move. It will be changed in onSnapEnd.
1842 // Suggestion not asked for.
1843 recommended_move = null;
1846 // see if the move is legal
1847 var pseudogame = new Chess(display_fen);
1848 var move = pseudogame.move({
1851 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1855 if (move === null) return 'snapback';
1858 var onSnapEnd = function(source, target) {
1859 if (source === target && recommended_move !== null) {
1860 source = recommended_move.from;
1861 target = recommended_move.to;
1863 recommended_move = null;
1864 var pseudogame = new Chess(display_fen);
1865 var move = pseudogame.move({
1868 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1871 if (current_display_line &&
1872 current_display_move < current_display_line.pretty_pv.length - 1 &&
1873 current_display_line.pretty_pv[current_display_move + 1] === move.san) {
1878 // Walk down the displayed lines until we find one that starts with
1879 // this move, then select that. Note that this gives us a good priority
1880 // order (history first, then PV, then multi-PV lines).
1881 for (var i = 0; i < display_lines.length; ++i) {
1882 var line = display_lines[i];
1883 if (line.pretty_pv[line.start_display_move_num] === move.san) {
1889 // Shouldn't really be here if we have hash probes, but there's really
1890 // nothing we can do.
1892 // End of dragging-related code.
1894 var pad = function(val, num_digits) {
1895 var s = val.toString();
1896 while (s.length < num_digits) {
1902 var fmt_cp = function(v) {
1906 return "+" + (v / 100).toFixed(2);
1909 return "-" + (v / 100).toFixed(2);
1913 var format_short_score = function(score) {
1917 if (score[0] === 'm') {
1918 if (score[2]) { // Is a bound.
1919 return score[2] + "\u00a0M" + pad(score[1], 3);
1921 return "M" + pad(score[1], 3);
1923 } else if (score[0] === 'd') {
1925 } else if (score[0] === 'cp') {
1926 if (score[2]) { // Is a bound.
1927 return score[2] + "\u00a0" + fmt_cp(score[1]);
1929 return pad(fmt_cp(score[1]), 5);
1935 var format_long_score = function(score) {
1936 if (score[0] === 'm') {
1938 return "White mates in " + score[1];
1940 return "Black mates in " + (-score[1]);
1942 } else if (score[0] === 'd') {
1943 return "Theoretical draw";
1944 } else if (score[0] === 'cp') {
1945 return "Score: " + format_short_score(score);
1950 var compute_plot_score = function(score) {
1951 if (score[0] === 'm') {
1957 } else if (score[0] === 'd') {
1959 } else if (score[0] === 'cp') {
1960 if (score[1] > 500) {
1962 } else if (score[1] < -500) {
1972 * @param score The score digest tuple.
1973 * @param {boolean} invert Whether black is to play.
1976 var compute_score_sort_key = function(score, invert) {
1981 if (score[0] === 'm') {
1984 s = 99999 - score[1];
1986 // Black mates (note the double negative for score[1]).
1987 s = -99999 - score[1];
1991 } else if (score[0] === 'd') {
1993 } else if (score[0] === 'cp') {
1994 return invert ? -score[1] : score[1];
2000 * @param {string} new_backend_url
2002 var switch_backend = function(new_backend_url, new_backend_hash_url) {
2003 // Stop looking at historic data.
2004 current_display_line = null;
2005 current_display_move = null;
2006 displayed_analysis_data = null;
2007 if (current_historic_xhr) {
2008 current_historic_xhr.abort();
2011 // If we already have a backend response going, abort it.
2012 if (current_analysis_xhr) {
2013 current_analysis_xhr.abort();
2015 if (current_hash_xhr) {
2016 current_hash_xhr.abort();
2019 // Otherwise, we should have a timer going to start a new one.
2021 if (current_analysis_request_timer) {
2022 clearTimeout(current_analysis_request_timer);
2023 current_analysis_request_timer = null;
2025 if (current_hash_display_timer) {
2026 clearTimeout(current_hash_display_timer);
2027 current_hash_display_timer = null;
2030 // Request an immediate fetch with the new backend.
2031 backend_url = new_backend_url;
2032 backend_hash_url = new_backend_hash_url;
2033 current_analysis_data = null;
2037 window['switch_backend'] = switch_backend;
2039 var init = function() {
2040 unique = get_unique();
2042 // Load settings from HTML5 local storage if available.
2043 if (supports_html5_storage() && localStorage['enable_sound']) {
2044 set_sound(parseInt(localStorage['enable_sound']));
2048 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2049 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2051 sort_refutation_lines_by_score = true;
2055 board = new window.ChessBoard('board', {
2056 onMoveEnd: function() { board_is_animating = false; },
2059 onDragStart: onDragStart,
2061 onSnapEnd: onSnapEnd
2063 $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2064 $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2067 $(window).resize(function() {
2069 update_sparkline(displayed_analysis_data || current_analysis_data);
2070 update_board_highlight();
2073 $(window).keyup(function(event) {
2074 if (event.which == 39) {
2076 } else if (event.which == 37) {
2080 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2082 $(document).ready(init);