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 /** @type {?jQuery} @private */
92 var highlighted_move = null;
94 /** @type {?number} @private */
97 /** @type {boolean} @private */
98 var enable_sound = false;
101 * Our best estimate of how many milliseconds we need to add to
102 * new Date() to get the true UTC time. Calibrated against the
108 var client_clock_offset_ms = null;
110 var clock_timer = null;
112 /** The current position on the board, represented as a FEN string.
120 * uci_pv: Array.<string>,
121 * pretty_pv: Array.<string>,
126 /** @type {Array.<DisplayLine>}
129 var display_lines = [];
131 /** @type {?DisplayLine} @private */
132 var current_display_line = null;
134 /** @type {boolean} @private */
135 var current_display_line_is_history = false;
137 /** @type {?number} @private */
138 var current_display_move = null;
141 * The current backend request to get main analysis (not history), if any,
142 * so that we can abort it.
147 var current_analysis_xhr = null;
150 * The current timer to fire off a request to get main analysis (not history),
151 * if any, so that we can abort it.
156 var current_analysis_request_timer = null;
159 * The current backend request to get historic data, if any.
164 var current_historic_xhr = null;
166 var supports_html5_storage = function() {
168 return 'localStorage' in window && window['localStorage'] !== null;
174 // Make the unique token persistent so people refreshing the page won't count twice.
175 // Of course, you can never fully protect against people deliberately wanting to spam.
176 var get_unique = function() {
177 var use_local_storage = supports_html5_storage();
178 if (use_local_storage && localStorage['unique']) {
179 return localStorage['unique'];
181 var unique = Math.random();
182 if (use_local_storage) {
183 localStorage['unique'] = unique;
188 var request_update = function() {
189 current_analysis_request_timer = null;
191 current_analysis_xhr = $.ajax({
192 url: backend_url + "?ims=" + ims + "&unique=" + unique
193 }).done(function(data, textstatus, xhr) {
194 sync_server_clock(xhr.getResponseHeader('Date'));
195 ims = xhr.getResponseHeader('X-RGLM');
196 var num_viewers = xhr.getResponseHeader('X-RGNV');
198 if (Array.isArray(data)) {
199 new_data = JSON.parse(JSON.stringify(current_analysis_data));
200 JSON_delta.patch(new_data, data);
205 var minimum_version = xhr.getResponseHeader('X-RGMV');
206 if (minimum_version && minimum_version > SCRIPT_VERSION) {
207 // Upgrade to latest version with a force-reload.
208 location.reload(true);
211 possibly_play_sound(current_analysis_data, new_data);
212 current_analysis_data = new_data;
213 update_board(current_analysis_data, displayed_analysis_data);
214 update_num_viewers(num_viewers);
217 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
218 }).fail(function(jqXHR, textStatus, errorThrown) {
219 if (textStatus === "abort") {
220 // Aborted because we are switching backends. Abandon and don't retry,
221 // because another one is already started for us.
223 // Backend error or similar. Wait ten seconds, then try again.
224 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
229 var possibly_play_sound = function(old_data, new_data) {
233 if (old_data === null) {
236 var ding = document.getElementById('ding');
237 if (ding && ding.play) {
238 if (old_data['position'] && old_data['position']['fen'] &&
239 new_data['position'] && new_data['position']['fen'] &&
240 (old_data['position']['fen'] !== new_data['position']['fen'] ||
241 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
248 * @type {!string} server_date_string
250 var sync_server_clock = function(server_date_string) {
251 var server_time_ms = new Date(server_date_string).getTime();
252 var client_time_ms = new Date().getTime();
253 var estimated_offset_ms = server_time_ms - client_time_ms;
255 // In order not to let the noise move us too much back and forth
256 // (the server only has one-second resolution anyway), we only
257 // change an existing skew if we are at least five seconds off.
258 if (client_clock_offset_ms === null ||
259 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
260 client_clock_offset_ms = estimated_offset_ms;
264 var clear_arrows = function() {
265 for (var i = 0; i < arrows.length; ++i) {
267 if (arrows[i].svg.parentElement) {
268 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
270 delete arrows[i].svg;
275 occupied_by_arrows = [];
276 for (var y = 0; y < 8; ++y) {
277 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
281 var redraw_arrows = function() {
282 for (var i = 0; i < arrows.length; ++i) {
283 position_arrow(arrows[i]);
287 /** @param {!number} x
290 var sign = function(x) {
300 /** See if drawing this arrow on the board would cause unduly amount of confusion.
301 * @param {!string} from The square the arrow is from (e.g. e4).
302 * @param {!string} to The square the arrow is to (e.g. e4).
305 var interfering_arrow = function(from, to) {
306 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
307 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
308 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
309 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
311 occupied_by_arrows[from_row][from_col] = true;
313 // Knight move: Just check that we haven't been at the destination before.
314 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
315 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
316 return occupied_by_arrows[to_row][to_col];
319 // Sliding piece: Check if anything except the from-square is seen before.
320 var dx = sign(to_col - from_col);
321 var dy = sign(to_row - from_row);
327 if (occupied_by_arrows[y][x]) {
330 occupied_by_arrows[y][x] = true;
331 } while (x != to_col || y != to_row);
336 /** Find a point along the coordinate system given by the given line,
337 * <t> units forward from the start of the line, <u> units to the right of it.
338 * @param {!number} x1
339 * @param {!number} x2
340 * @param {!number} y1
341 * @param {!number} y2
344 * @return {!string} The point in "x y" form, suitable for SVG paths.
346 var point_from_start = function(x1, y1, x2, y2, t, u) {
350 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
354 var x = x1 + dx * t + dy * u;
355 var y = y1 + dy * t - dx * u;
359 /** Find a point along the coordinate system given by the given line,
360 * <t> units forward from the end of the line, <u> units to the right of it.
361 * @param {!number} x1
362 * @param {!number} x2
363 * @param {!number} y1
364 * @param {!number} y2
367 * @return {!string} The point in "x y" form, suitable for SVG paths.
369 var point_from_end = function(x1, y1, x2, y2, t, u) {
373 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
377 var x = x2 + dx * t + dy * u;
378 var y = y2 + dy * t - dx * u;
382 var position_arrow = function(arrow) {
384 if (arrow.svg.parentElement) {
385 arrow.svg.parentElement.removeChild(arrow.svg);
389 if (current_display_line !== null && !current_display_line_is_history) {
393 var pos = $(".square-a8").position();
395 var zoom_factor = $("#board").width() / 400.0;
396 var line_width = arrow.line_width * zoom_factor;
397 var arrow_size = arrow.arrow_size * zoom_factor;
399 var square_width = $(".square-a8").width();
400 var from_y = (7 - arrow.from_row + 0.5)*square_width;
401 var to_y = (7 - arrow.to_row + 0.5)*square_width;
402 var from_x = (arrow.from_col + 0.5)*square_width;
403 var to_x = (arrow.to_col + 0.5)*square_width;
405 var SVG_NS = "http://www.w3.org/2000/svg";
406 var XHTML_NS = "http://www.w3.org/1999/xhtml";
407 var svg = document.createElementNS(SVG_NS, "svg");
408 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
409 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
410 svg.setAttribute("style", "position: absolute");
411 svg.setAttribute("position", "absolute");
412 svg.setAttribute("version", "1.1");
413 svg.setAttribute("class", "c1");
414 svg.setAttribute("xmlns", XHTML_NS);
422 var outline = document.createElementNS(SVG_NS, "path");
423 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));
424 outline.setAttribute("xmlns", XHTML_NS);
425 outline.setAttribute("stroke", "#666");
426 outline.setAttribute("stroke-width", line_width + 2);
427 outline.setAttribute("fill", "none");
428 svg.appendChild(outline);
430 var path = document.createElementNS(SVG_NS, "path");
431 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));
432 path.setAttribute("xmlns", XHTML_NS);
433 path.setAttribute("stroke", arrow.fg_color);
434 path.setAttribute("stroke-width", line_width);
435 path.setAttribute("fill", "none");
436 svg.appendChild(path);
438 // Then the arrow head.
439 var head = document.createElementNS(SVG_NS, "path");
440 head.setAttribute("d",
441 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
442 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
443 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
444 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
445 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
446 head.setAttribute("xmlns", XHTML_NS);
447 head.setAttribute("stroke", "#000");
448 head.setAttribute("stroke-width", "1");
449 head.setAttribute("fill", arrow.fg_color);
450 svg.appendChild(head);
452 $(svg).css({ top: pos.top, left: pos.left });
453 document.body.appendChild(svg);
458 * @param {!string} from_square
459 * @param {!string} to_square
460 * @param {!string} fg_color
461 * @param {number} line_width
462 * @param {number} arrow_size
464 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
465 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
466 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
467 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
468 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
476 line_width: line_width,
477 arrow_size: arrow_size,
481 position_arrow(arrow);
485 var compare_by_sort_key = function(refutation_lines, a, b) {
486 var ska = refutation_lines[a]['sort_key'];
487 var skb = refutation_lines[b]['sort_key'];
488 if (ska < skb) return -1;
489 if (ska > skb) return 1;
493 var compare_by_score = function(refutation_lines, a, b) {
494 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
495 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
500 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
501 * sorted by quality, descending.
503 * @param {!Object} data
504 * @param {number} margin The maximum number of centipawns worse than the
505 * best move can be and still be included.
506 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
507 * moves, in score order.
509 var find_nonstupid_moves = function(data, margin) {
510 // First of all, if there are any moves that are more than 0.5 ahead of
511 // the primary move, the refutation lines are probably bunk, so just
513 var best_score = undefined;
514 var pv_score = undefined;
515 for (var move in data['refutation_lines']) {
516 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
517 if (move == data['pv_uci'][0]) {
520 if (best_score === undefined || score > best_score) {
523 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
528 if (best_score - pv_score > 50) {
532 // Now find all moves that are within “margin” of the best score.
533 // The PV move will always be first.
535 for (var move in data['refutation_lines']) {
536 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
537 if (move != data['pv_uci'][0] && best_score - score <= margin) {
541 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
542 moves.unshift(data['pv_uci'][0]);
551 var thousands = function(x) {
552 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
556 * @param {!string} fen
557 * @param {Array.<string>} pretty_pv
558 * @param {number} move_num
559 * @param {!string} toplay
560 * @param {number=} opt_limit
561 * @param {boolean=} opt_showlast
563 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
566 pretty_pv: pretty_pv,
567 line_number: display_lines.length
569 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
573 * @param {number} line_num
574 * @param {Array.<string>} pretty_pv
575 * @param {number} move_num
576 * @param {!string} toplay
577 * @param {number=} opt_limit
578 * @param {boolean=} opt_showlast
580 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
583 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
584 // Truncate the PV at the beginning (instead of at the end).
585 // We assume here that toplay is 'W'. We also assume that if
586 // opt_showlast is set, then it is the history, and thus,
587 // the UI should be to expand the history.
588 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
589 i = pretty_pv.length - opt_limit;
594 } else if (toplay == 'B' && pretty_pv.length > 0) {
595 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
596 pv = move_num + '. … ' + move;
601 for ( ; i < pretty_pv.length; ++i) {
602 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
605 if (i > opt_limit && !opt_showlast) {
611 pv += move_num + '. ' + move;
622 var update_highlight = function() {
623 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
624 if ((current_display_line === null || current_display_line_is_history) &&
625 highlight_from !== undefined && highlight_to !== undefined) {
626 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
627 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
631 var update_history = function() {
632 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
633 $("#history").html("No history");
634 } else if (truncate_display_history) {
635 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
638 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
639 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
644 * @param {!boolean} truncate_history
646 var collapse_history = function(truncate_history) {
647 truncate_display_history = truncate_history;
650 window['collapse_history'] = collapse_history;
652 var update_refutation_lines = function() {
656 if (display_lines.length > 2) {
657 display_lines = [ display_lines[0], display_lines[1] ];
660 var tbl = $("#refutationlines");
664 for (var move in refutation_lines) {
667 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
668 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
669 for (var i = 0; i < moves.length; ++i) {
670 var line = refutation_lines[moves[i]];
672 var tr = document.createElement("tr");
674 var move_td = document.createElement("td");
675 tr.appendChild(move_td);
676 $(move_td).addClass("move");
677 if (line['pv_pretty'].length == 0) {
678 $(move_td).text(line['pretty_move']);
680 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
681 $(move_td).html(move);
684 var score_td = document.createElement("td");
685 tr.appendChild(score_td);
686 $(score_td).addClass("score");
687 $(score_td).text(line['pretty_score']);
689 var depth_td = document.createElement("td");
690 tr.appendChild(depth_td);
691 $(depth_td).addClass("depth");
692 $(depth_td).text("d" + line['depth']);
694 var pv_td = document.createElement("td");
695 tr.appendChild(pv_td);
696 $(pv_td).addClass("pv");
697 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
702 // Make one of the links clickable and the other nonclickable.
703 if (sort_refutation_lines_by_score) {
704 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
705 $("#sortbyscore1").html("<strong>Score</strong>");
707 $("#sortbyscore0").html("<strong>Move</strong>");
708 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
713 * @param {?string} fen
714 * @param {Array.<string>} moves
715 * @param {number} last_move
717 var chess_from = function(fen, moves, last_move) {
718 var hiddenboard = new Chess();
720 hiddenboard.load(fen);
722 for (var i = 0; i <= last_move; ++i) {
723 if (moves[i] === '0-0') {
724 hiddenboard.move('O-O');
725 } else if (moves[i] === '0-0-0') {
726 hiddenboard.move('O-O-O');
728 hiddenboard.move(moves[i]);
734 var update_game_list = function(games) {
735 $("#games").text("");
736 if (games === null) {
740 var games_div = document.getElementById('games');
741 for (var game_num = 0; game_num < games.length; ++game_num) {
742 var game = games[game_num];
743 var game_span = document.createElement("span");
744 game_span.setAttribute("class", "game");
746 var game_name = document.createTextNode(game['name']);
747 if (game['url'] === backend_url) {
748 game_span.appendChild(game_name);
750 var game_a = document.createElement("a");
751 game_a.setAttribute("href", "#" + game['id']);
752 game_a.appendChild(game_name);
753 game_span.appendChild(game_a);
755 games_div.appendChild(game_span);
760 * Try to find a running game that matches with the current hash,
761 * and switch to it if we're not already displaying it.
763 var possibly_switch_game_from_hash = function() {
764 if (current_games === null) {
768 var hash = window.location.hash.replace(/^#/,'');
769 for (var i = 0; i < current_games.length; ++i) {
770 if (current_games[i]['id'] === hash) {
771 if (backend_url !== current_games[i]['url']) {
772 switch_backend(current_games[i]['url']);
780 * @param {Object} data
781 * @param {?Object} display_data
783 var update_board = function(current_data, display_data) {
784 var data = display_data || current_data;
788 // Print the history. This is pretty much the only thing that's
789 // unconditionally taken from current_data (we're not interested in
790 // historic history).
791 if (current_data['position']['pretty_history']) {
792 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
794 display_lines.push(null);
798 // Games currently in progress, if any.
799 if (current_data['games']) {
800 current_games = current_data['games'];
801 possibly_switch_game_from_hash();
802 update_game_list(current_data['games']);
804 current_games = null;
805 update_game_list(null);
808 // The headline. Names are always fetched from current_data;
809 // the rest can depend a bit.
812 current_data['position']['player_w'] && current_data['position']['player_b']) {
813 headline = current_data['position']['player_w'] + '–' +
814 current_data['position']['player_b'] + ', analysis';
816 headline = 'Analysis';
819 // Credits, where applicable. Note that we don't want the footer to change a lot
820 // when e.g. viewing history, so if any of these changed during the game,
821 // use the current one still.
822 if (current_data['using_lomonosov']) {
823 $("#lomonosov").show();
825 $("#lomonosov").hide();
828 // Credits: The engine name/version.
829 if (current_data['engine'] && current_data['engine']['name'] !== null) {
830 $("#engineid").text(current_data['engine']['name']);
833 // Credits: The engine URL.
834 if (current_data['engine'] && current_data['engine']['url']) {
835 $("#engineid").attr("href", current_data['engine']['url']);
837 $("#engineid").removeAttr("href");
840 // Credits: Engine details.
841 if (current_data['engine'] && current_data['engine']['details']) {
842 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
844 $("#enginedetails").text("");
847 // Credits: Move source, possibly with URL.
848 if (current_data['move_source'] && current_data['move_source_url']) {
849 $("#movesource").text("Moves provided by ");
850 var movesource_a = document.createElement("a");
851 movesource_a.setAttribute("href", current_data['move_source_url']);
852 var movesource_text = document.createTextNode(current_data['move_source']);
853 movesource_a.appendChild(movesource_text);
854 var movesource_period = document.createTextNode(".");
855 document.getElementById("movesource").appendChild(movesource_a);
856 document.getElementById("movesource").appendChild(movesource_period);
857 } else if (current_data['move_source']) {
858 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
860 $("#movesource").text("");
865 // Displaying some non-current position, pick out the last move
866 // from the history. This will work even if the fetch failed.
867 last_move = format_halfmove_with_number(
868 current_display_line.pretty_pv[current_display_move],
869 current_display_move + 1);
870 headline += ' after ' + last_move;
871 } else if (data['position']['last_move'] !== 'none') {
872 last_move = format_move_with_number(
873 data['position']['last_move'],
874 data['position']['move_num'],
875 data['position']['toplay'] == 'W');
876 headline += ' after ' + last_move;
880 $("#headline").text(headline);
882 // The <title> contains a very brief headline.
883 var title_elems = [];
884 if (data['short_score'] !== undefined && data['short_score'] !== null) {
885 title_elems.push(data['short_score'].replace(/^ /, ""));
887 if (last_move !== null) {
888 title_elems.push(last_move);
891 if (title_elems.length != 0) {
892 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
894 document.title = 'analysis.sesse.net';
897 // The last move (shown by highlighting the from and to squares).
898 if (data['position'] && data['position']['last_move_uci']) {
899 highlight_from = data['position']['last_move_uci'].substr(0, 2);
900 highlight_to = data['position']['last_move_uci'].substr(2, 2);
901 } else if (current_display_line_is_history && current_display_move >= 0) {
902 // We don't have historic analysis for this position, but we
903 // can reconstruct what the last move was by just replaying
905 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
906 var moves = hiddenboard.history({ verbose: true });
907 var last_move = moves.pop();
908 highlight_from = last_move.from;
909 highlight_to = last_move.to;
911 highlight_from = highlight_to = undefined;
915 if (data['failed']) {
916 $("#score").text("No analysis for this move");
918 $("#searchstats").html(" ");
919 $("#refutationlines").empty();
920 $("#whiteclock").empty();
921 $("#blackclock").empty();
922 refutation_lines = [];
923 update_refutation_lines();
925 update_displayed_line();
932 if (data['score'] !== null) {
933 $("#score").text(data['score']);
937 if (data['tablebase'] == 1) {
938 $("#searchstats").text("Tablebase result");
939 } else if (data['nodes'] && data['nps'] && data['depth']) {
940 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
941 if (data['seldepth']) {
942 stats += ' (' + data['seldepth'] + ' selective)';
944 if (data['tbhits'] && data['tbhits'] > 0) {
945 if (data['tbhits'] == 1) {
946 stats += ', one Syzygy hit';
948 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
952 $("#searchstats").text(stats);
954 $("#searchstats").text("");
957 // Update the board itself.
958 fen = data['position']['fen'];
959 update_displayed_line();
962 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
964 // Update the PV arrow.
966 if (data['pv_uci'].length >= 1) {
967 // draw a continuation arrow as long as it's the same piece
968 for (var i = 0; i < data['pv_uci'].length; i += 2) {
969 var from = data['pv_uci'][i].substr(0, 2);
970 var to = data['pv_uci'][i].substr(2,4);
971 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
972 interfering_arrow(from, to)) {
975 create_arrow(from, to, '#f66', 6, 20);
978 var alt_moves = find_nonstupid_moves(data, 30);
979 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
980 create_arrow(alt_moves[i].substr(0, 2),
981 alt_moves[i].substr(2, 2), '#f66', 1, 10);
985 // See if all semi-reasonable moves have only one possible response.
986 if (data['pv_uci'].length >= 2) {
987 var nonstupid_moves = find_nonstupid_moves(data, 300);
988 var response = data['pv_uci'][1];
989 for (var i = 0; i < nonstupid_moves.length; ++i) {
990 if (nonstupid_moves[i] == data['pv_uci'][0]) {
991 // ignore the PV move for refutation lines.
994 if (!data['refutation_lines'] ||
995 !data['refutation_lines'][nonstupid_moves[i]] ||
996 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
997 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
998 // Incomplete PV, abort.
999 response = undefined;
1002 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1003 if (response !== this_response) {
1004 // Different response depending on lines, abort.
1005 response = undefined;
1010 if (nonstupid_moves.length > 0 && response !== undefined) {
1011 create_arrow(response.substr(0, 2),
1012 response.substr(2, 2), '#66f', 6, 20);
1016 // Update the refutation lines.
1017 fen = data['position']['fen'];
1018 move_num = data['position']['move_num'];
1019 toplay = data['position']['toplay'];
1020 refutation_lines = data['refutation_lines'];
1021 update_refutation_lines();
1023 // Update the sparkline last, since its size depends on how everything else reflowed.
1024 update_sparkline(data);
1027 var update_sparkline = function(data) {
1028 if (data && data['score_history']) {
1029 var first_move_num = undefined;
1030 for (var halfmove_num in data['score_history']) {
1031 halfmove_num = parseInt(halfmove_num);
1032 if (first_move_num === undefined || halfmove_num < first_move_num) {
1033 first_move_num = halfmove_num;
1036 if (first_move_num !== undefined) {
1037 var last_move_num = data['position']['move_num'] * 2 - 3;
1038 if (data['position']['toplay'] === 'B') {
1042 // Possibly truncate some moves if we don't have enough width.
1043 // FIXME: Sometimes width() for #scorecontainer (and by extent,
1044 // #scoresparkcontainer) on Chrome for mobile seems to start off
1045 // at something very small, and then suddenly snap back into place.
1047 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1048 if (last_move_num - first_move_num > max_moves) {
1049 first_move_num = last_move_num - max_moves;
1052 var min_score = -100;
1053 var max_score = 100;
1054 var last_score = null;
1056 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1057 if (data['score_history'][halfmove_num]) {
1058 var score = data['score_history'][halfmove_num][0];
1059 if (score < min_score) min_score = score;
1060 if (score > max_score) max_score = score;
1061 last_score = data['score_history'][halfmove_num][0];
1063 scores.push(last_score);
1065 if (data['plot_score']) {
1066 scores.push(data['plot_score']);
1068 // FIXME: at some widths, calling sparkline() seems to push
1069 // #scorecontainer under the board.
1070 $("#scorespark").sparkline(scores, {
1073 chartRangeMin: min_score,
1074 chartRangeMax: max_score,
1075 tooltipFormatter: function(sparkline, options, fields) {
1076 return format_tooltip(data, fields[0].offset + first_move_num);
1080 $("#scorespark").text("");
1083 $("#scorespark").text("");
1088 * @param {number} num_viewers
1090 var update_num_viewers = function(num_viewers) {
1091 if (num_viewers === null) {
1092 $("#numviewers").text("");
1093 } else if (num_viewers == 1) {
1094 $("#numviewers").text("You are the only current viewer");
1096 $("#numviewers").text(num_viewers + " current viewers");
1100 var update_clock = function() {
1101 clearTimeout(clock_timer);
1103 var data = displayed_analysis_data || current_analysis_data;
1104 if (data['position']) {
1105 var result = data['position']['result'];
1106 if (result === '1-0') {
1107 $("#whiteclock").text("1");
1108 $("#blackclock").text("0");
1109 $("#whiteclock").removeClass("running-clock");
1110 $("#blackclock").removeClass("running-clock");
1113 if (result === '1/2-1/2') {
1114 $("#whiteclock").text("1/2");
1115 $("#blackclock").text("1/2");
1116 $("#whiteclock").removeClass("running-clock");
1117 $("#blackclock").removeClass("running-clock");
1120 if (result === '0-1') {
1121 $("#whiteclock").text("0");
1122 $("#blackclock").text("1");
1123 $("#whiteclock").removeClass("running-clock");
1124 $("#blackclock").removeClass("running-clock");
1129 var white_clock_ms = null;
1130 var black_clock_ms = null;
1131 var show_seconds = false;
1134 if (data['position'] &&
1135 data['position']['white_clock'] &&
1136 data['position']['black_clock']) {
1137 white_clock_ms = data['position']['white_clock'] * 1000;
1138 black_clock_ms = data['position']['black_clock'] * 1000;
1141 // Dynamic clock (only one, obviously).
1143 if (data['position']['white_clock_target']) {
1145 $("#whiteclock").addClass("running-clock");
1146 $("#blackclock").removeClass("running-clock");
1147 } else if (data['position']['black_clock_target']) {
1149 $("#whiteclock").removeClass("running-clock");
1150 $("#blackclock").addClass("running-clock");
1152 $("#whiteclock").removeClass("running-clock");
1153 $("#blackclock").removeClass("running-clock");
1157 var now = new Date().getTime() + client_clock_offset_ms;
1158 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1159 if (color === "white") {
1160 white_clock_ms = remaining_ms;
1162 black_clock_ms = remaining_ms;
1166 if (white_clock_ms === null || black_clock_ms === null) {
1167 $("#whiteclock").empty();
1168 $("#blackclock").empty();
1172 // If either player has ten minutes or less left, add the second counters.
1173 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1176 // See when the clock will change next, and update right after that.
1179 next_update_ms = remaining_ms % 1000 + 100;
1181 next_update_ms = remaining_ms % 60000 + 100;
1183 clock_timer = setTimeout(update_clock, next_update_ms);
1186 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1187 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1191 * @param {Number} remaining_ms
1192 * @param {boolean} show_seconds
1194 var format_clock = function(remaining_ms, show_seconds) {
1195 if (remaining_ms <= 0) {
1203 var remaining = Math.floor(remaining_ms / 1000);
1204 var seconds = remaining % 60;
1205 remaining = (remaining - seconds) / 60;
1206 var minutes = remaining % 60;
1207 remaining = (remaining - minutes) / 60;
1208 var hours = remaining;
1210 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1212 return format_2d(hours) + ":" + format_2d(minutes);
1219 var format_2d = function(x) {
1228 * @param {string} move
1229 * @param {Number} move_num
1230 * @param {boolean} white_to_play
1232 var format_move_with_number = function(move, move_num, white_to_play) {
1234 if (white_to_play) {
1235 ret = (move_num - 1) + '… ';
1237 ret = move_num + '. ';
1244 * @param {string} move
1245 * @param {Number} halfmove_num
1247 var format_halfmove_with_number = function(move, halfmove_num) {
1248 return format_move_with_number(
1250 Math.floor(halfmove_num / 2) + 1,
1251 halfmove_num % 2 == 0);
1255 * @param {Object} data
1256 * @param {Number} halfmove_num
1258 var format_tooltip = function(data, halfmove_num) {
1259 if (data['score_history'][halfmove_num] ||
1260 halfmove_num === data['position']['pretty_history'].length) {
1263 if (halfmove_num === data['position']['pretty_history'].length) {
1264 move = data['position']['last_move'];
1265 short_score = data['short_score'];
1267 move = data['position']['pretty_history'][halfmove_num];
1268 short_score = data['score_history'][halfmove_num][1];
1270 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1272 return "After " + move_with_number + ": " + short_score;
1274 for (var i = halfmove_num; i --> 0; ) {
1275 if (data['score_history'][i]) {
1276 var move = data['position']['pretty_history'][i];
1277 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1284 * @param {boolean} sort_by_score
1286 var resort_refutation_lines = function(sort_by_score) {
1287 sort_refutation_lines_by_score = sort_by_score;
1288 if (supports_html5_storage()) {
1289 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1291 update_refutation_lines();
1293 window['resort_refutation_lines'] = resort_refutation_lines;
1296 * @param {boolean} truncate_history
1298 var set_truncate_history = function(truncate_history) {
1299 truncate_display_history = truncate_history;
1300 update_refutation_lines();
1302 window['set_truncate_history'] = set_truncate_history;
1305 * @param {number} line_num
1306 * @param {number} move_num
1308 var show_line = function(line_num, move_num) {
1309 if (line_num == -1) {
1310 current_display_line = null;
1311 current_display_move = null;
1312 if (displayed_analysis_data) {
1313 // TODO: Support exiting to history position if we are in an
1314 // analysis line of a history position.
1315 displayed_analysis_data = null;
1316 update_board(current_analysis_data, displayed_analysis_data);
1319 current_display_line = display_lines[line_num];
1320 current_display_move = move_num;
1322 current_display_line_is_history = (line_num == 0);
1324 update_historic_analysis();
1325 update_displayed_line();
1329 window['show_line'] = show_line;
1331 var prev_move = function() {
1332 if (current_display_move > -1) {
1333 --current_display_move;
1335 update_historic_analysis();
1336 update_displayed_line();
1338 window['prev_move'] = prev_move;
1340 var next_move = function() {
1341 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1342 ++current_display_move;
1344 update_historic_analysis();
1345 update_displayed_line();
1347 window['next_move'] = next_move;
1349 var update_historic_analysis = function() {
1350 if (!current_display_line_is_history) {
1353 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1354 displayed_analysis_data = null;
1355 update_board(current_analysis_data, displayed_analysis_data);
1358 // Fetch old analysis for this line if it exists.
1359 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1360 var filename = "/history/move" + (current_display_move + 1) + "-" +
1361 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1363 current_historic_xhr = $.ajax({
1365 }).done(function(data, textstatus, xhr) {
1366 displayed_analysis_data = data;
1367 update_board(current_analysis_data, displayed_analysis_data);
1368 }).fail(function(jqXHR, textStatus, errorThrown) {
1369 if (textStatus === "abort") {
1370 // Aborted because we are switching backends. Don't do anything;
1371 // we will already have been cleared.
1373 displayed_analysis_data = {'failed': true};
1374 update_board(current_analysis_data, displayed_analysis_data);
1380 * @param {string} fen
1382 var update_imbalance = function(fen) {
1383 var hiddenboard = new Chess(fen);
1384 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1385 for (var row = 0; row < 8; ++row) {
1386 for (var col = 0; col < 8; ++col) {
1387 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1388 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1389 var square = col_text + row_text;
1390 var contents = hiddenboard.get(square);
1391 if (contents !== null) {
1392 if (contents.color === 'w') {
1393 ++imbalance[contents.type];
1395 --imbalance[contents.type];
1400 var white_imbalance = '';
1401 var black_imbalance = '';
1402 for (var piece in imbalance) {
1403 for (var i = 0; i < imbalance[piece]; ++i) {
1404 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1406 for (var i = 0; i < -imbalance[piece]; ++i) {
1407 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1410 $('#whiteimbalance').html(white_imbalance);
1411 $('#blackimbalance').html(black_imbalance);
1414 var update_displayed_line = function() {
1415 if (highlighted_move !== null) {
1416 highlighted_move.removeClass('highlight');
1418 if (current_display_line === null) {
1419 $("#linenav").hide();
1420 $("#linemsg").show();
1421 board.position(fen);
1422 update_imbalance(fen);
1426 $("#linenav").show();
1427 $("#linemsg").hide();
1429 if (current_display_move <= 0) {
1430 $("#prevmove").html("Previous");
1432 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1434 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1435 $("#nextmove").html("Next");
1437 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1440 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1441 highlighted_move.addClass('highlight');
1443 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1444 board.position(hiddenboard.fen());
1445 update_imbalance(hiddenboard.fen());
1449 * @param {boolean} param_enable_sound
1451 var set_sound = function(param_enable_sound) {
1452 enable_sound = param_enable_sound;
1454 $("#soundon").html("<strong>On</strong>");
1455 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1457 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1458 // and also preload the file since the user has selected audio.
1459 var ding = document.getElementById('ding');
1460 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1461 ding.src = 'ding.opus';
1465 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1466 $("#soundoff").html("<strong>Off</strong>");
1468 if (supports_html5_storage()) {
1469 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1472 window['set_sound'] = set_sound;
1475 * @param {string} new_backend_url
1477 var switch_backend = function(new_backend_url) {
1478 // Stop looking at historic data.
1479 current_display_line = null;
1480 current_display_move = null;
1481 displayed_analysis_data = null;
1482 if (current_historic_xhr) {
1483 current_historic_xhr.abort();
1486 // If we already have a backend response going, abort it.
1487 if (current_analysis_xhr) {
1488 current_analysis_xhr.abort();
1491 // Otherwise, we should have a timer going to start a new one.
1493 if (current_analysis_request_timer) {
1494 clearTimeout(current_analysis_request_timer);
1495 current_analysis_request_timer = null;
1498 // Request an immediate fetch with the new backend.
1499 backend_url = new_backend_url;
1500 current_analysis_data = null;
1504 window['switch_backend'] = switch_backend;
1506 var init = function() {
1507 unique = get_unique();
1509 // Load settings from HTML5 local storage if available.
1510 if (supports_html5_storage() && localStorage['enable_sound']) {
1511 set_sound(parseInt(localStorage['enable_sound']));
1515 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1516 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1518 sort_refutation_lines_by_score = true;
1522 board = new window.ChessBoard('board', 'start');
1525 $(window).resize(function() {
1527 update_sparkline(displayed_analysis_data || current_analysis_data);
1531 $(window).keyup(function(event) {
1532 if (event.which == 39) {
1534 } else if (event.which == 37) {
1538 window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
1540 $(document).ready(init);