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 = 2015062104;
13 * The current backend URL.
18 var backend_url = "/analysis.pl";
20 /** @type {window.ChessBoard} @private */
24 * The most recent analysis data we have from the server
25 * (about the most recent position).
29 var current_analysis_data = null;
32 * If we are displaying previous analysis, this is non-null,
33 * and will override most of current_analysis_data.
38 var displayed_analysis_data = null;
41 * Games currently in progress, if any.
50 var current_games = null;
65 /** @type {Array.<Array.<boolean>>} */
66 var occupied_by_arrows = [];
68 var refutation_lines = [];
70 /** @type {!number} @private */
73 /** @type {!string} @private */
76 /** @type {number} @private */
79 /** @type {boolean} @private */
80 var sort_refutation_lines_by_score = true;
82 /** @type {boolean} @private */
83 var truncate_display_history = true;
85 /** @type {!string|undefined} @private */
86 var highlight_from = undefined;
88 /** @type {!string|undefined} @private */
89 var highlight_to = undefined;
91 /** The HTML object of the move currently being highlighted (in red).
94 var highlighted_move = null;
96 /** @type {?number} @private */
99 /** @type {boolean} @private */
100 var enable_sound = false;
103 * Our best estimate of how many milliseconds we need to add to
104 * new Date() to get the true UTC time. Calibrated against the
110 var client_clock_offset_ms = null;
112 var clock_timer = null;
114 /** The current position on the board, represented as a FEN string.
122 * uci_pv: Array.<string>,
123 * pretty_pv: Array.<string>,
128 /** All PVs that we currently know of.
130 * Element 0 is history (or null if no history).
131 * Element 1 is current main PV.
132 * All remaining elements are refutation lines (multi-PV).
134 * @type {Array.<DisplayLine>}
137 var display_lines = [];
139 /** @type {?DisplayLine} @private */
140 var current_display_line = null;
142 /** @type {boolean} @private */
143 var current_display_line_is_history = false;
145 /** @type {?number} @private */
146 var current_display_move = null;
149 * The current backend request to get main analysis (not history), if any,
150 * so that we can abort it.
155 var current_analysis_xhr = null;
158 * The current timer to fire off a request to get main analysis (not history),
159 * if any, so that we can abort it.
164 var current_analysis_request_timer = null;
167 * The current backend request to get historic data, if any.
172 var current_historic_xhr = null;
174 var supports_html5_storage = function() {
176 return 'localStorage' in window && window['localStorage'] !== null;
182 // Make the unique token persistent so people refreshing the page won't count twice.
183 // Of course, you can never fully protect against people deliberately wanting to spam.
184 var get_unique = function() {
185 var use_local_storage = supports_html5_storage();
186 if (use_local_storage && localStorage['unique']) {
187 return localStorage['unique'];
189 var unique = Math.random();
190 if (use_local_storage) {
191 localStorage['unique'] = unique;
196 var request_update = function() {
197 current_analysis_request_timer = null;
199 current_analysis_xhr = $.ajax({
200 url: backend_url + "?ims=" + ims + "&unique=" + unique
201 }).done(function(data, textstatus, xhr) {
202 sync_server_clock(xhr.getResponseHeader('Date'));
203 ims = xhr.getResponseHeader('X-RGLM');
204 var num_viewers = xhr.getResponseHeader('X-RGNV');
206 if (Array.isArray(data)) {
207 new_data = JSON.parse(JSON.stringify(current_analysis_data));
208 JSON_delta.patch(new_data, data);
213 var minimum_version = xhr.getResponseHeader('X-RGMV');
214 if (minimum_version && minimum_version > SCRIPT_VERSION) {
215 // Upgrade to latest version with a force-reload.
216 location.reload(true);
219 possibly_play_sound(current_analysis_data, new_data);
220 current_analysis_data = new_data;
221 update_board(current_analysis_data, displayed_analysis_data);
222 update_num_viewers(num_viewers);
225 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
226 }).fail(function(jqXHR, textStatus, errorThrown) {
227 if (textStatus === "abort") {
228 // Aborted because we are switching backends. Abandon and don't retry,
229 // because another one is already started for us.
231 // Backend error or similar. Wait ten seconds, then try again.
232 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
237 var possibly_play_sound = function(old_data, new_data) {
241 if (old_data === null) {
244 var ding = document.getElementById('ding');
245 if (ding && ding.play) {
246 if (old_data['position'] && old_data['position']['fen'] &&
247 new_data['position'] && new_data['position']['fen'] &&
248 (old_data['position']['fen'] !== new_data['position']['fen'] ||
249 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
256 * @type {!string} server_date_string
258 var sync_server_clock = function(server_date_string) {
259 var server_time_ms = new Date(server_date_string).getTime();
260 var client_time_ms = new Date().getTime();
261 var estimated_offset_ms = server_time_ms - client_time_ms;
263 // In order not to let the noise move us too much back and forth
264 // (the server only has one-second resolution anyway), we only
265 // change an existing skew if we are at least five seconds off.
266 if (client_clock_offset_ms === null ||
267 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
268 client_clock_offset_ms = estimated_offset_ms;
272 var clear_arrows = function() {
273 for (var i = 0; i < arrows.length; ++i) {
275 if (arrows[i].svg.parentElement) {
276 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
278 delete arrows[i].svg;
283 occupied_by_arrows = [];
284 for (var y = 0; y < 8; ++y) {
285 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
289 var redraw_arrows = function() {
290 for (var i = 0; i < arrows.length; ++i) {
291 position_arrow(arrows[i]);
295 /** @param {!number} x
298 var sign = function(x) {
308 /** See if drawing this arrow on the board would cause unduly amount of confusion.
309 * @param {!string} from The square the arrow is from (e.g. e4).
310 * @param {!string} to The square the arrow is to (e.g. e4).
313 var interfering_arrow = function(from, to) {
314 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
315 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
316 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
317 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
319 occupied_by_arrows[from_row][from_col] = true;
321 // Knight move: Just check that we haven't been at the destination before.
322 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
323 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
324 return occupied_by_arrows[to_row][to_col];
327 // Sliding piece: Check if anything except the from-square is seen before.
328 var dx = sign(to_col - from_col);
329 var dy = sign(to_row - from_row);
335 if (occupied_by_arrows[y][x]) {
338 occupied_by_arrows[y][x] = true;
339 } while (x != to_col || y != to_row);
344 /** Find a point along the coordinate system given by the given line,
345 * <t> units forward from the start of the line, <u> units to the right of it.
346 * @param {!number} x1
347 * @param {!number} x2
348 * @param {!number} y1
349 * @param {!number} y2
352 * @return {!string} The point in "x y" form, suitable for SVG paths.
354 var point_from_start = function(x1, y1, x2, y2, t, u) {
358 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
362 var x = x1 + dx * t + dy * u;
363 var y = y1 + dy * t - dx * u;
367 /** Find a point along the coordinate system given by the given line,
368 * <t> units forward from the end of the line, <u> units to the right of it.
369 * @param {!number} x1
370 * @param {!number} x2
371 * @param {!number} y1
372 * @param {!number} y2
375 * @return {!string} The point in "x y" form, suitable for SVG paths.
377 var point_from_end = function(x1, y1, x2, y2, t, u) {
381 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
385 var x = x2 + dx * t + dy * u;
386 var y = y2 + dy * t - dx * u;
390 var position_arrow = function(arrow) {
392 if (arrow.svg.parentElement) {
393 arrow.svg.parentElement.removeChild(arrow.svg);
397 if (current_display_line !== null && !current_display_line_is_history) {
401 var pos = $(".square-a8").position();
403 var zoom_factor = $("#board").width() / 400.0;
404 var line_width = arrow.line_width * zoom_factor;
405 var arrow_size = arrow.arrow_size * zoom_factor;
407 var square_width = $(".square-a8").width();
408 var from_y = (7 - arrow.from_row + 0.5)*square_width;
409 var to_y = (7 - arrow.to_row + 0.5)*square_width;
410 var from_x = (arrow.from_col + 0.5)*square_width;
411 var to_x = (arrow.to_col + 0.5)*square_width;
413 var SVG_NS = "http://www.w3.org/2000/svg";
414 var XHTML_NS = "http://www.w3.org/1999/xhtml";
415 var svg = document.createElementNS(SVG_NS, "svg");
416 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
417 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
418 svg.setAttribute("style", "position: absolute");
419 svg.setAttribute("position", "absolute");
420 svg.setAttribute("version", "1.1");
421 svg.setAttribute("class", "c1");
422 svg.setAttribute("xmlns", XHTML_NS);
430 var outline = document.createElementNS(SVG_NS, "path");
431 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));
432 outline.setAttribute("xmlns", XHTML_NS);
433 outline.setAttribute("stroke", "#666");
434 outline.setAttribute("stroke-width", line_width + 2);
435 outline.setAttribute("fill", "none");
436 svg.appendChild(outline);
438 var path = document.createElementNS(SVG_NS, "path");
439 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));
440 path.setAttribute("xmlns", XHTML_NS);
441 path.setAttribute("stroke", arrow.fg_color);
442 path.setAttribute("stroke-width", line_width);
443 path.setAttribute("fill", "none");
444 svg.appendChild(path);
446 // Then the arrow head.
447 var head = document.createElementNS(SVG_NS, "path");
448 head.setAttribute("d",
449 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
450 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
451 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
452 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
453 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
454 head.setAttribute("xmlns", XHTML_NS);
455 head.setAttribute("stroke", "#000");
456 head.setAttribute("stroke-width", "1");
457 head.setAttribute("fill", arrow.fg_color);
458 svg.appendChild(head);
460 $(svg).css({ top: pos.top, left: pos.left });
461 document.body.appendChild(svg);
466 * @param {!string} from_square
467 * @param {!string} to_square
468 * @param {!string} fg_color
469 * @param {number} line_width
470 * @param {number} arrow_size
472 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
473 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
474 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
475 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
476 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
484 line_width: line_width,
485 arrow_size: arrow_size,
489 position_arrow(arrow);
493 var compare_by_sort_key = function(refutation_lines, a, b) {
494 var ska = refutation_lines[a]['sort_key'];
495 var skb = refutation_lines[b]['sort_key'];
496 if (ska < skb) return -1;
497 if (ska > skb) return 1;
501 var compare_by_score = function(refutation_lines, a, b) {
502 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
503 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
508 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
509 * sorted by quality, descending.
511 * @param {!Object} data
512 * @param {number} margin The maximum number of centipawns worse than the
513 * best move can be and still be included.
514 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
515 * moves, in score order.
517 var find_nonstupid_moves = function(data, margin) {
518 // First of all, if there are any moves that are more than 0.5 ahead of
519 // the primary move, the refutation lines are probably bunk, so just
521 var best_score = undefined;
522 var pv_score = undefined;
523 for (var move in data['refutation_lines']) {
524 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
525 if (move == data['pv_uci'][0]) {
528 if (best_score === undefined || score > best_score) {
531 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
536 if (best_score - pv_score > 50) {
540 // Now find all moves that are within “margin” of the best score.
541 // The PV move will always be first.
543 for (var move in data['refutation_lines']) {
544 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
545 if (move != data['pv_uci'][0] && best_score - score <= margin) {
549 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
550 moves.unshift(data['pv_uci'][0]);
559 var thousands = function(x) {
560 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
564 * @param {!string} fen
565 * @param {Array.<string>} pretty_pv
566 * @param {number} move_num
567 * @param {!string} toplay
568 * @param {number=} opt_limit
569 * @param {boolean=} opt_showlast
571 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
574 pretty_pv: pretty_pv,
575 line_number: display_lines.length
577 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
581 * @param {number} line_num
582 * @param {Array.<string>} pretty_pv
583 * @param {number} move_num
584 * @param {!string} toplay
585 * @param {number=} opt_limit
586 * @param {boolean=} opt_showlast
588 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
591 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
592 // Truncate the PV at the beginning (instead of at the end).
593 // We assume here that toplay is 'W'. We also assume that if
594 // opt_showlast is set, then it is the history, and thus,
595 // the UI should be to expand the history.
596 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
597 i = pretty_pv.length - opt_limit;
602 } else if (toplay == 'B' && pretty_pv.length > 0) {
603 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
604 pv = move_num + '. … ' + move;
609 for ( ; i < pretty_pv.length; ++i) {
610 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
613 if (i > opt_limit && !opt_showlast) {
619 pv += move_num + '. ' + move;
630 /** Update the highlighted to/from squares on the board.
631 * Based on the global "highlight_from" and "highlight_to" variables.
633 var update_board_highlight = function() {
634 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
635 if ((current_display_line === null || current_display_line_is_history) &&
636 highlight_from !== undefined && highlight_to !== undefined) {
637 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
638 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
642 var update_history = function() {
643 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
644 $("#history").html("No history");
645 } else if (truncate_display_history) {
646 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
649 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
650 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
655 * @param {!boolean} truncate_history
657 var collapse_history = function(truncate_history) {
658 truncate_display_history = truncate_history;
661 window['collapse_history'] = collapse_history;
663 /** Update the HTML display of multi-PV from the global "refutation_lines".
665 * Also recreates the global "display_lines".
667 var update_refutation_lines = function() {
671 if (display_lines.length > 2) {
672 // Truncate so that only the history and PV is left.
673 display_lines = [ display_lines[0], display_lines[1] ];
676 var tbl = $("#refutationlines");
680 for (var move in refutation_lines) {
683 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
684 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
685 for (var i = 0; i < moves.length; ++i) {
686 var line = refutation_lines[moves[i]];
688 var tr = document.createElement("tr");
690 var move_td = document.createElement("td");
691 tr.appendChild(move_td);
692 $(move_td).addClass("move");
693 if (line['pv_pretty'].length == 0) {
694 $(move_td).text(line['pretty_move']);
696 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
697 $(move_td).html(move);
700 var score_td = document.createElement("td");
701 tr.appendChild(score_td);
702 $(score_td).addClass("score");
703 $(score_td).text(line['pretty_score']);
705 var depth_td = document.createElement("td");
706 tr.appendChild(depth_td);
707 $(depth_td).addClass("depth");
708 $(depth_td).text("d" + line['depth']);
710 var pv_td = document.createElement("td");
711 tr.appendChild(pv_td);
712 $(pv_td).addClass("pv");
713 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
718 // Make one of the links clickable and the other nonclickable.
719 if (sort_refutation_lines_by_score) {
720 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
721 $("#sortbyscore1").html("<strong>Score</strong>");
723 $("#sortbyscore0").html("<strong>Move</strong>");
724 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
729 * Create a Chess.js board object, containing the given position plus the given moves,
730 * up to the given limit.
732 * @param {?string} fen
733 * @param {Array.<string>} moves
734 * @param {number} last_move
736 var chess_from = function(fen, moves, last_move) {
737 var hiddenboard = new Chess();
739 hiddenboard.load(fen);
741 for (var i = 0; i <= last_move; ++i) {
742 if (moves[i] === '0-0') {
743 hiddenboard.move('O-O');
744 } else if (moves[i] === '0-0-0') {
745 hiddenboard.move('O-O-O');
747 hiddenboard.move(moves[i]);
753 var update_game_list = function(games) {
754 $("#games").text("");
755 if (games === null) {
759 var games_div = document.getElementById('games');
760 for (var game_num = 0; game_num < games.length; ++game_num) {
761 var game = games[game_num];
762 var game_span = document.createElement("span");
763 game_span.setAttribute("class", "game");
765 var game_name = document.createTextNode(game['name']);
766 if (game['url'] === backend_url) {
767 game_span.appendChild(game_name);
769 var game_a = document.createElement("a");
770 game_a.setAttribute("href", "#" + game['id']);
771 game_a.appendChild(game_name);
772 game_span.appendChild(game_a);
774 games_div.appendChild(game_span);
779 * Try to find a running game that matches with the current hash,
780 * and switch to it if we're not already displaying it.
782 var possibly_switch_game_from_hash = function() {
783 if (current_games === null) {
787 var hash = window.location.hash.replace(/^#/,'');
788 for (var i = 0; i < current_games.length; ++i) {
789 if (current_games[i]['id'] === hash) {
790 if (backend_url !== current_games[i]['url']) {
791 switch_backend(current_games[i]['url']);
799 * @param {Object} data
800 * @param {?Object} display_data
802 var update_board = function(current_data, display_data) {
803 var data = display_data || current_data;
807 // Print the history. This is pretty much the only thing that's
808 // unconditionally taken from current_data (we're not interested in
809 // historic history).
810 if (current_data['position']['pretty_history']) {
811 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
813 display_lines.push(null);
817 // Games currently in progress, if any.
818 if (current_data['games']) {
819 current_games = current_data['games'];
820 possibly_switch_game_from_hash();
821 update_game_list(current_data['games']);
823 current_games = null;
824 update_game_list(null);
827 // The headline. Names are always fetched from current_data;
828 // the rest can depend a bit.
831 current_data['position']['player_w'] && current_data['position']['player_b']) {
832 headline = current_data['position']['player_w'] + '–' +
833 current_data['position']['player_b'] + ', analysis';
835 headline = 'Analysis';
838 // Credits, where applicable. Note that we don't want the footer to change a lot
839 // when e.g. viewing history, so if any of these changed during the game,
840 // use the current one still.
841 if (current_data['using_lomonosov']) {
842 $("#lomonosov").show();
844 $("#lomonosov").hide();
847 // Credits: The engine name/version.
848 if (current_data['engine'] && current_data['engine']['name'] !== null) {
849 $("#engineid").text(current_data['engine']['name']);
852 // Credits: The engine URL.
853 if (current_data['engine'] && current_data['engine']['url']) {
854 $("#engineid").attr("href", current_data['engine']['url']);
856 $("#engineid").removeAttr("href");
859 // Credits: Engine details.
860 if (current_data['engine'] && current_data['engine']['details']) {
861 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
863 $("#enginedetails").text("");
866 // Credits: Move source, possibly with URL.
867 if (current_data['move_source'] && current_data['move_source_url']) {
868 $("#movesource").text("Moves provided by ");
869 var movesource_a = document.createElement("a");
870 movesource_a.setAttribute("href", current_data['move_source_url']);
871 var movesource_text = document.createTextNode(current_data['move_source']);
872 movesource_a.appendChild(movesource_text);
873 var movesource_period = document.createTextNode(".");
874 document.getElementById("movesource").appendChild(movesource_a);
875 document.getElementById("movesource").appendChild(movesource_period);
876 } else if (current_data['move_source']) {
877 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
879 $("#movesource").text("");
884 // Displaying some non-current position, pick out the last move
885 // from the history. This will work even if the fetch failed.
886 last_move = format_halfmove_with_number(
887 current_display_line.pretty_pv[current_display_move],
888 current_display_move + 1);
889 headline += ' after ' + last_move;
890 } else if (data['position']['last_move'] !== 'none') {
891 last_move = format_move_with_number(
892 data['position']['last_move'],
893 data['position']['move_num'],
894 data['position']['toplay'] == 'W');
895 headline += ' after ' + last_move;
899 $("#headline").text(headline);
901 // The <title> contains a very brief headline.
902 var title_elems = [];
903 if (data['short_score'] !== undefined && data['short_score'] !== null) {
904 title_elems.push(data['short_score'].replace(/^ /, ""));
906 if (last_move !== null) {
907 title_elems.push(last_move);
910 if (title_elems.length != 0) {
911 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
913 document.title = 'analysis.sesse.net';
916 // The last move (shown by highlighting the from and to squares).
917 if (data['position'] && data['position']['last_move_uci']) {
918 highlight_from = data['position']['last_move_uci'].substr(0, 2);
919 highlight_to = data['position']['last_move_uci'].substr(2, 2);
920 } else if (current_display_line_is_history && current_display_move >= 0) {
921 // We don't have historic analysis for this position, but we
922 // can reconstruct what the last move was by just replaying
924 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
925 var moves = hiddenboard.history({ verbose: true });
926 var last_move = moves.pop();
927 highlight_from = last_move.from;
928 highlight_to = last_move.to;
930 highlight_from = highlight_to = undefined;
932 update_board_highlight();
934 if (data['failed']) {
935 $("#score").text("No analysis for this move");
937 $("#searchstats").html(" ");
938 $("#refutationlines").empty();
939 $("#whiteclock").empty();
940 $("#blackclock").empty();
941 refutation_lines = [];
942 update_refutation_lines();
944 update_displayed_line();
951 if (data['score'] !== null) {
952 $("#score").text(data['score']);
956 if (data['tablebase'] == 1) {
957 $("#searchstats").text("Tablebase result");
958 } else if (data['nodes'] && data['nps'] && data['depth']) {
959 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
960 if (data['seldepth']) {
961 stats += ' (' + data['seldepth'] + ' selective)';
963 if (data['tbhits'] && data['tbhits'] > 0) {
964 if (data['tbhits'] == 1) {
965 stats += ', one Syzygy hit';
967 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
971 $("#searchstats").text(stats);
973 $("#searchstats").text("");
976 // Update the board itself.
977 fen = data['position']['fen'];
978 update_displayed_line();
981 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
983 // Update the PV arrow.
985 if (data['pv_uci'].length >= 1) {
986 // draw a continuation arrow as long as it's the same piece
987 for (var i = 0; i < data['pv_uci'].length; i += 2) {
988 var from = data['pv_uci'][i].substr(0, 2);
989 var to = data['pv_uci'][i].substr(2,4);
990 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
991 interfering_arrow(from, to)) {
994 create_arrow(from, to, '#f66', 6, 20);
997 var alt_moves = find_nonstupid_moves(data, 30);
998 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
999 create_arrow(alt_moves[i].substr(0, 2),
1000 alt_moves[i].substr(2, 2), '#f66', 1, 10);
1004 // See if all semi-reasonable moves have only one possible response.
1005 if (data['pv_uci'].length >= 2) {
1006 var nonstupid_moves = find_nonstupid_moves(data, 300);
1007 var response = data['pv_uci'][1];
1008 for (var i = 0; i < nonstupid_moves.length; ++i) {
1009 if (nonstupid_moves[i] == data['pv_uci'][0]) {
1010 // ignore the PV move for refutation lines.
1013 if (!data['refutation_lines'] ||
1014 !data['refutation_lines'][nonstupid_moves[i]] ||
1015 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1016 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1017 // Incomplete PV, abort.
1018 response = undefined;
1021 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1022 if (response !== this_response) {
1023 // Different response depending on lines, abort.
1024 response = undefined;
1029 if (nonstupid_moves.length > 0 && response !== undefined) {
1030 create_arrow(response.substr(0, 2),
1031 response.substr(2, 2), '#66f', 6, 20);
1035 // Update the refutation lines.
1036 fen = data['position']['fen'];
1037 move_num = data['position']['move_num'];
1038 toplay = data['position']['toplay'];
1039 refutation_lines = data['refutation_lines'];
1040 update_refutation_lines();
1042 // Update the sparkline last, since its size depends on how everything else reflowed.
1043 update_sparkline(data);
1046 var update_sparkline = function(data) {
1047 if (data && data['score_history']) {
1048 var first_move_num = undefined;
1049 for (var halfmove_num in data['score_history']) {
1050 halfmove_num = parseInt(halfmove_num);
1051 if (first_move_num === undefined || halfmove_num < first_move_num) {
1052 first_move_num = halfmove_num;
1055 if (first_move_num !== undefined) {
1056 var last_move_num = data['position']['move_num'] * 2 - 3;
1057 if (data['position']['toplay'] === 'B') {
1061 // Possibly truncate some moves if we don't have enough width.
1062 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1063 // #scoresparkcontainer) on Chrome for mobile seems to start off
1064 // at something very small, and then suddenly snap back into place.
1066 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1067 if (last_move_num - first_move_num > max_moves) {
1068 first_move_num = last_move_num - max_moves;
1071 var min_score = -100;
1072 var max_score = 100;
1073 var last_score = null;
1075 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1076 if (data['score_history'][halfmove_num]) {
1077 var score = data['score_history'][halfmove_num][0];
1078 if (score < min_score) min_score = score;
1079 if (score > max_score) max_score = score;
1080 last_score = data['score_history'][halfmove_num][0];
1082 scores.push(last_score);
1084 if (data['plot_score']) {
1085 scores.push(data['plot_score']);
1087 // FIXME: at some widths, calling sparkline() seems to push
1088 // #scorecontainer under the board.
1089 $("#scorespark").sparkline(scores, {
1092 chartRangeMin: min_score,
1093 chartRangeMax: max_score,
1094 tooltipFormatter: function(sparkline, options, fields) {
1095 return format_tooltip(data, fields[0].offset + first_move_num);
1099 $("#scorespark").text("");
1102 $("#scorespark").text("");
1107 * @param {number} num_viewers
1109 var update_num_viewers = function(num_viewers) {
1110 if (num_viewers === null) {
1111 $("#numviewers").text("");
1112 } else if (num_viewers == 1) {
1113 $("#numviewers").text("You are the only current viewer");
1115 $("#numviewers").text(num_viewers + " current viewers");
1119 var update_clock = function() {
1120 clearTimeout(clock_timer);
1122 var data = displayed_analysis_data || current_analysis_data;
1123 if (data['position']) {
1124 var result = data['position']['result'];
1125 if (result === '1-0') {
1126 $("#whiteclock").text("1");
1127 $("#blackclock").text("0");
1128 $("#whiteclock").removeClass("running-clock");
1129 $("#blackclock").removeClass("running-clock");
1132 if (result === '1/2-1/2') {
1133 $("#whiteclock").text("1/2");
1134 $("#blackclock").text("1/2");
1135 $("#whiteclock").removeClass("running-clock");
1136 $("#blackclock").removeClass("running-clock");
1139 if (result === '0-1') {
1140 $("#whiteclock").text("0");
1141 $("#blackclock").text("1");
1142 $("#whiteclock").removeClass("running-clock");
1143 $("#blackclock").removeClass("running-clock");
1148 var white_clock_ms = null;
1149 var black_clock_ms = null;
1150 var show_seconds = false;
1153 if (data['position'] &&
1154 data['position']['white_clock'] &&
1155 data['position']['black_clock']) {
1156 white_clock_ms = data['position']['white_clock'] * 1000;
1157 black_clock_ms = data['position']['black_clock'] * 1000;
1160 // Dynamic clock (only one, obviously).
1162 if (data['position']['white_clock_target']) {
1164 $("#whiteclock").addClass("running-clock");
1165 $("#blackclock").removeClass("running-clock");
1166 } else if (data['position']['black_clock_target']) {
1168 $("#whiteclock").removeClass("running-clock");
1169 $("#blackclock").addClass("running-clock");
1171 $("#whiteclock").removeClass("running-clock");
1172 $("#blackclock").removeClass("running-clock");
1176 var now = new Date().getTime() + client_clock_offset_ms;
1177 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1178 if (color === "white") {
1179 white_clock_ms = remaining_ms;
1181 black_clock_ms = remaining_ms;
1185 if (white_clock_ms === null || black_clock_ms === null) {
1186 $("#whiteclock").empty();
1187 $("#blackclock").empty();
1191 // If either player has ten minutes or less left, add the second counters.
1192 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1195 // See when the clock will change next, and update right after that.
1198 next_update_ms = remaining_ms % 1000 + 100;
1200 next_update_ms = remaining_ms % 60000 + 100;
1202 clock_timer = setTimeout(update_clock, next_update_ms);
1205 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1206 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1210 * @param {Number} remaining_ms
1211 * @param {boolean} show_seconds
1213 var format_clock = function(remaining_ms, show_seconds) {
1214 if (remaining_ms <= 0) {
1222 var remaining = Math.floor(remaining_ms / 1000);
1223 var seconds = remaining % 60;
1224 remaining = (remaining - seconds) / 60;
1225 var minutes = remaining % 60;
1226 remaining = (remaining - minutes) / 60;
1227 var hours = remaining;
1229 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1231 return format_2d(hours) + ":" + format_2d(minutes);
1238 var format_2d = function(x) {
1247 * @param {string} move
1248 * @param {Number} move_num
1249 * @param {boolean} white_to_play
1251 var format_move_with_number = function(move, move_num, white_to_play) {
1253 if (white_to_play) {
1254 ret = (move_num - 1) + '… ';
1256 ret = move_num + '. ';
1263 * @param {string} move
1264 * @param {Number} halfmove_num
1266 var format_halfmove_with_number = function(move, halfmove_num) {
1267 return format_move_with_number(
1269 Math.floor(halfmove_num / 2) + 1,
1270 halfmove_num % 2 == 0);
1274 * @param {Object} data
1275 * @param {Number} halfmove_num
1277 var format_tooltip = function(data, halfmove_num) {
1278 if (data['score_history'][halfmove_num] ||
1279 halfmove_num === data['position']['pretty_history'].length) {
1282 if (halfmove_num === data['position']['pretty_history'].length) {
1283 move = data['position']['last_move'];
1284 short_score = data['short_score'];
1286 move = data['position']['pretty_history'][halfmove_num];
1287 short_score = data['score_history'][halfmove_num][1];
1289 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1291 return "After " + move_with_number + ": " + short_score;
1293 for (var i = halfmove_num; i --> 0; ) {
1294 if (data['score_history'][i]) {
1295 var move = data['position']['pretty_history'][i];
1296 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1303 * @param {boolean} sort_by_score
1305 var resort_refutation_lines = function(sort_by_score) {
1306 sort_refutation_lines_by_score = sort_by_score;
1307 if (supports_html5_storage()) {
1308 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1310 update_refutation_lines();
1312 window['resort_refutation_lines'] = resort_refutation_lines;
1315 * @param {boolean} truncate_history
1317 var set_truncate_history = function(truncate_history) {
1318 truncate_display_history = truncate_history;
1319 update_refutation_lines();
1321 window['set_truncate_history'] = set_truncate_history;
1324 * @param {number} line_num
1325 * @param {number} move_num
1327 var show_line = function(line_num, move_num) {
1328 if (line_num == -1) {
1329 current_display_line = null;
1330 current_display_move = null;
1331 if (displayed_analysis_data) {
1332 // TODO: Support exiting to history position if we are in an
1333 // analysis line of a history position.
1334 displayed_analysis_data = null;
1335 update_board(current_analysis_data, displayed_analysis_data);
1338 current_display_line = display_lines[line_num];
1339 current_display_move = move_num;
1341 current_display_line_is_history = (line_num == 0);
1343 update_historic_analysis();
1344 update_displayed_line();
1345 update_board_highlight();
1348 window['show_line'] = show_line;
1350 var prev_move = function() {
1351 if (current_display_move > -1) {
1352 --current_display_move;
1354 update_historic_analysis();
1355 update_displayed_line();
1357 window['prev_move'] = prev_move;
1359 var next_move = function() {
1360 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1361 ++current_display_move;
1363 update_historic_analysis();
1364 update_displayed_line();
1366 window['next_move'] = next_move;
1368 var update_historic_analysis = function() {
1369 if (!current_display_line_is_history) {
1372 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1373 displayed_analysis_data = null;
1374 update_board(current_analysis_data, displayed_analysis_data);
1377 // Fetch old analysis for this line if it exists.
1378 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1379 var filename = "/history/move" + (current_display_move + 1) + "-" +
1380 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1382 current_historic_xhr = $.ajax({
1384 }).done(function(data, textstatus, xhr) {
1385 displayed_analysis_data = data;
1386 update_board(current_analysis_data, displayed_analysis_data);
1387 }).fail(function(jqXHR, textStatus, errorThrown) {
1388 if (textStatus === "abort") {
1389 // Aborted because we are switching backends. Don't do anything;
1390 // we will already have been cleared.
1392 displayed_analysis_data = {'failed': true};
1393 update_board(current_analysis_data, displayed_analysis_data);
1399 * @param {string} fen
1401 var update_imbalance = function(fen) {
1402 var hiddenboard = new Chess(fen);
1403 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1404 for (var row = 0; row < 8; ++row) {
1405 for (var col = 0; col < 8; ++col) {
1406 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1407 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1408 var square = col_text + row_text;
1409 var contents = hiddenboard.get(square);
1410 if (contents !== null) {
1411 if (contents.color === 'w') {
1412 ++imbalance[contents.type];
1414 --imbalance[contents.type];
1419 var white_imbalance = '';
1420 var black_imbalance = '';
1421 for (var piece in imbalance) {
1422 for (var i = 0; i < imbalance[piece]; ++i) {
1423 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1425 for (var i = 0; i < -imbalance[piece]; ++i) {
1426 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1429 $('#whiteimbalance').html(white_imbalance);
1430 $('#blackimbalance').html(black_imbalance);
1433 var update_displayed_line = function() {
1434 if (highlighted_move !== null) {
1435 highlighted_move.removeClass('highlight');
1437 if (current_display_line === null) {
1438 $("#linenav").hide();
1439 $("#linemsg").show();
1440 board.position(fen);
1441 update_imbalance(fen);
1445 $("#linenav").show();
1446 $("#linemsg").hide();
1448 if (current_display_move <= 0) {
1449 $("#prevmove").html("Previous");
1451 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1453 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1454 $("#nextmove").html("Next");
1456 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1459 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1460 highlighted_move.addClass('highlight');
1462 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1463 board.position(hiddenboard.fen());
1464 update_imbalance(hiddenboard.fen());
1468 * @param {boolean} param_enable_sound
1470 var set_sound = function(param_enable_sound) {
1471 enable_sound = param_enable_sound;
1473 $("#soundon").html("<strong>On</strong>");
1474 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1476 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1477 // and also preload the file since the user has selected audio.
1478 var ding = document.getElementById('ding');
1479 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1480 ding.src = 'ding.opus';
1484 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1485 $("#soundoff").html("<strong>Off</strong>");
1487 if (supports_html5_storage()) {
1488 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1491 window['set_sound'] = set_sound;
1494 * @param {string} new_backend_url
1496 var switch_backend = function(new_backend_url) {
1497 // Stop looking at historic data.
1498 current_display_line = null;
1499 current_display_move = null;
1500 displayed_analysis_data = null;
1501 if (current_historic_xhr) {
1502 current_historic_xhr.abort();
1505 // If we already have a backend response going, abort it.
1506 if (current_analysis_xhr) {
1507 current_analysis_xhr.abort();
1510 // Otherwise, we should have a timer going to start a new one.
1512 if (current_analysis_request_timer) {
1513 clearTimeout(current_analysis_request_timer);
1514 current_analysis_request_timer = null;
1517 // Request an immediate fetch with the new backend.
1518 backend_url = new_backend_url;
1519 current_analysis_data = null;
1523 window['switch_backend'] = switch_backend;
1525 var init = function() {
1526 unique = get_unique();
1528 // Load settings from HTML5 local storage if available.
1529 if (supports_html5_storage() && localStorage['enable_sound']) {
1530 set_sound(parseInt(localStorage['enable_sound']));
1534 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1535 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1537 sort_refutation_lines_by_score = true;
1541 board = new window.ChessBoard('board', 'start');
1544 $(window).resize(function() {
1546 update_sparkline(displayed_analysis_data || current_analysis_data);
1547 update_board_highlight();
1550 $(window).keyup(function(event) {
1551 if (event.which == 39) {
1553 } else if (event.which == 37) {
1557 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
1559 $(document).ready(init);