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;
53 /** @type {Array.<Array.<boolean>>} */
54 var occupied_by_arrows = [];
56 var refutation_lines = [];
58 /** @type {!number} @private */
61 /** @type {!string} @private */
64 /** @type {number} @private */
67 /** @type {boolean} @private */
68 var sort_refutation_lines_by_score = true;
70 /** @type {boolean} @private */
71 var truncate_display_history = true;
73 /** @type {!string|undefined} @private */
74 var highlight_from = undefined;
76 /** @type {!string|undefined} @private */
77 var highlight_to = undefined;
79 /** @type {?jQuery} @private */
80 var highlighted_move = null;
82 /** @type {?number} @private */
85 /** @type {boolean} @private */
86 var enable_sound = false;
89 * Our best estimate of how many milliseconds we need to add to
90 * new Date() to get the true UTC time. Calibrated against the
96 var client_clock_offset_ms = null;
98 var clock_timer = null;
100 /** The current position on the board, represented as a FEN string.
108 * uci_pv: Array.<string>,
109 * pretty_pv: Array.<string>,
114 /** @type {Array.<DisplayLine>}
117 var display_lines = [];
119 /** @type {?DisplayLine} @private */
120 var current_display_line = null;
122 /** @type {boolean} @private */
123 var current_display_line_is_history = false;
125 /** @type {?number} @private */
126 var current_display_move = null;
129 * The current backend request to get main analysis (not history), if any,
130 * so that we can abort it.
135 var current_analysis_xhr = null;
138 * The current timer to fire off a request to get main analysis (not history),
139 * if any, so that we can abort it.
144 var current_analysis_request_timer = null;
147 * The current backend request to get historic data, if any.
152 var current_historic_xhr = null;
154 var supports_html5_storage = function() {
156 return 'localStorage' in window && window['localStorage'] !== null;
162 // Make the unique token persistent so people refreshing the page won't count twice.
163 // Of course, you can never fully protect against people deliberately wanting to spam.
164 var get_unique = function() {
165 var use_local_storage = supports_html5_storage();
166 if (use_local_storage && localStorage['unique']) {
167 return localStorage['unique'];
169 var unique = Math.random();
170 if (use_local_storage) {
171 localStorage['unique'] = unique;
176 var request_update = function() {
177 current_analysis_request_timer = null;
179 current_analysis_xhr = $.ajax({
180 url: backend_url + "?ims=" + ims + "&unique=" + unique
181 }).done(function(data, textstatus, xhr) {
182 sync_server_clock(xhr.getResponseHeader('Date'));
183 ims = xhr.getResponseHeader('X-RGLM');
184 var num_viewers = xhr.getResponseHeader('X-RGNV');
186 if (Array.isArray(data)) {
187 new_data = JSON.parse(JSON.stringify(current_analysis_data));
188 JSON_delta.patch(new_data, data);
193 var minimum_version = xhr.getResponseHeader('X-RGMV');
194 if (minimum_version && minimum_version > SCRIPT_VERSION) {
195 // Upgrade to latest version with a force-reload.
196 location.reload(true);
199 possibly_play_sound(current_analysis_data, new_data);
200 current_analysis_data = new_data;
201 update_board(current_analysis_data, displayed_analysis_data);
202 update_num_viewers(num_viewers);
205 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
206 }).fail(function(jqXHR, textStatus, errorThrown) {
207 if (textStatus === "abort") {
208 // Aborted because we are switching backends. Abandon and don't retry,
209 // because another one is already started for us.
211 // Backend error or similar. Wait ten seconds, then try again.
212 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
217 var possibly_play_sound = function(old_data, new_data) {
221 if (old_data === null) {
224 var ding = document.getElementById('ding');
225 if (ding && ding.play) {
226 if (old_data['position'] && old_data['position']['fen'] &&
227 new_data['position'] && new_data['position']['fen'] &&
228 (old_data['position']['fen'] !== new_data['position']['fen'] ||
229 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
236 * @type {!string} server_date_string
238 var sync_server_clock = function(server_date_string) {
239 var server_time_ms = new Date(server_date_string).getTime();
240 var client_time_ms = new Date().getTime();
241 var estimated_offset_ms = server_time_ms - client_time_ms;
243 // In order not to let the noise move us too much back and forth
244 // (the server only has one-second resolution anyway), we only
245 // change an existing skew if we are at least five seconds off.
246 if (client_clock_offset_ms === null ||
247 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
248 client_clock_offset_ms = estimated_offset_ms;
252 var clear_arrows = function() {
253 for (var i = 0; i < arrows.length; ++i) {
255 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
256 delete arrows[i].svg;
261 occupied_by_arrows = [];
262 for (var y = 0; y < 8; ++y) {
263 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
267 var redraw_arrows = function() {
268 for (var i = 0; i < arrows.length; ++i) {
269 position_arrow(arrows[i]);
273 /** @param {!number} x
276 var sign = function(x) {
286 /** See if drawing this arrow on the board would cause unduly amount of confusion.
287 * @param {!string} from The square the arrow is from (e.g. e4).
288 * @param {!string} to The square the arrow is to (e.g. e4).
291 var interfering_arrow = function(from, to) {
292 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
293 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
294 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
295 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
297 occupied_by_arrows[from_row][from_col] = true;
299 // Knight move: Just check that we haven't been at the destination before.
300 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
301 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
302 return occupied_by_arrows[to_row][to_col];
305 // Sliding piece: Check if anything except the from-square is seen before.
306 var dx = sign(to_col - from_col);
307 var dy = sign(to_row - from_row);
313 if (occupied_by_arrows[y][x]) {
316 occupied_by_arrows[y][x] = true;
317 } while (x != to_col || y != to_row);
322 /** Find a point along the coordinate system given by the given line,
323 * <t> units forward from the start of the line, <u> units to the right of it.
324 * @param {!number} x1
325 * @param {!number} x2
326 * @param {!number} y1
327 * @param {!number} y2
330 * @return {!string} The point in "x y" form, suitable for SVG paths.
332 var point_from_start = function(x1, y1, x2, y2, t, u) {
336 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
340 var x = x1 + dx * t + dy * u;
341 var y = y1 + dy * t - dx * u;
345 /** Find a point along the coordinate system given by the given line,
346 * <t> units forward from the end of the line, <u> units to the right of it.
347 * @param {!number} x1
348 * @param {!number} x2
349 * @param {!number} y1
350 * @param {!number} y2
353 * @return {!string} The point in "x y" form, suitable for SVG paths.
355 var point_from_end = function(x1, y1, x2, y2, t, u) {
359 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
363 var x = x2 + dx * t + dy * u;
364 var y = y2 + dy * t - dx * u;
368 var position_arrow = function(arrow) {
370 arrow.svg.parentElement.removeChild(arrow.svg);
373 if (current_display_line !== null && !current_display_line_is_history) {
377 var pos = $(".square-a8").position();
379 var zoom_factor = $("#board").width() / 400.0;
380 var line_width = arrow.line_width * zoom_factor;
381 var arrow_size = arrow.arrow_size * zoom_factor;
383 var square_width = $(".square-a8").width();
384 var from_y = (7 - arrow.from_row + 0.5)*square_width;
385 var to_y = (7 - arrow.to_row + 0.5)*square_width;
386 var from_x = (arrow.from_col + 0.5)*square_width;
387 var to_x = (arrow.to_col + 0.5)*square_width;
389 var SVG_NS = "http://www.w3.org/2000/svg";
390 var XHTML_NS = "http://www.w3.org/1999/xhtml";
391 var svg = document.createElementNS(SVG_NS, "svg");
392 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
393 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
394 svg.setAttribute("style", "position: absolute");
395 svg.setAttribute("position", "absolute");
396 svg.setAttribute("version", "1.1");
397 svg.setAttribute("class", "c1");
398 svg.setAttribute("xmlns", XHTML_NS);
406 var outline = document.createElementNS(SVG_NS, "path");
407 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));
408 outline.setAttribute("xmlns", XHTML_NS);
409 outline.setAttribute("stroke", "#666");
410 outline.setAttribute("stroke-width", line_width + 2);
411 outline.setAttribute("fill", "none");
412 svg.appendChild(outline);
414 var path = document.createElementNS(SVG_NS, "path");
415 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));
416 path.setAttribute("xmlns", XHTML_NS);
417 path.setAttribute("stroke", arrow.fg_color);
418 path.setAttribute("stroke-width", line_width);
419 path.setAttribute("fill", "none");
420 svg.appendChild(path);
422 // Then the arrow head.
423 var head = document.createElementNS(SVG_NS, "path");
424 head.setAttribute("d",
425 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
426 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
427 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
428 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
429 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
430 head.setAttribute("xmlns", XHTML_NS);
431 head.setAttribute("stroke", "#000");
432 head.setAttribute("stroke-width", "1");
433 head.setAttribute("fill", arrow.fg_color);
434 svg.appendChild(head);
436 $(svg).css({ top: pos.top, left: pos.left });
437 document.body.appendChild(svg);
442 * @param {!string} from_square
443 * @param {!string} to_square
444 * @param {!string} fg_color
445 * @param {number} line_width
446 * @param {number} arrow_size
448 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
449 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
450 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
451 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
452 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
460 line_width: line_width,
461 arrow_size: arrow_size,
465 position_arrow(arrow);
469 var compare_by_sort_key = function(refutation_lines, a, b) {
470 var ska = refutation_lines[a]['sort_key'];
471 var skb = refutation_lines[b]['sort_key'];
472 if (ska < skb) return -1;
473 if (ska > skb) return 1;
477 var compare_by_score = function(refutation_lines, a, b) {
478 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
479 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
484 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
485 * sorted by quality, descending.
487 * @param {!Object} data
488 * @param {number} margin The maximum number of centipawns worse than the
489 * best move can be and still be included.
490 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
491 * moves, in score order.
493 var find_nonstupid_moves = function(data, margin) {
494 // First of all, if there are any moves that are more than 0.5 ahead of
495 // the primary move, the refutation lines are probably bunk, so just
497 var best_score = undefined;
498 var pv_score = undefined;
499 for (var move in data['refutation_lines']) {
500 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
501 if (move == data['pv_uci'][0]) {
504 if (best_score === undefined || score > best_score) {
507 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
512 if (best_score - pv_score > 50) {
516 // Now find all moves that are within “margin” of the best score.
517 // The PV move will always be first.
519 for (var move in data['refutation_lines']) {
520 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
521 if (move != data['pv_uci'][0] && best_score - score <= margin) {
525 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
526 moves.unshift(data['pv_uci'][0]);
535 var thousands = function(x) {
536 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
540 * @param {!string} fen
541 * @param {Array.<string>} pretty_pv
542 * @param {number} move_num
543 * @param {!string} toplay
544 * @param {number=} opt_limit
545 * @param {boolean=} opt_showlast
547 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
550 pretty_pv: pretty_pv,
551 line_number: display_lines.length
553 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
557 * @param {number} line_num
558 * @param {Array.<string>} pretty_pv
559 * @param {number} move_num
560 * @param {!string} toplay
561 * @param {number=} opt_limit
562 * @param {boolean=} opt_showlast
564 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
567 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
568 // Truncate the PV at the beginning (instead of at the end).
569 // We assume here that toplay is 'W'. We also assume that if
570 // opt_showlast is set, then it is the history, and thus,
571 // the UI should be to expand the history.
572 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
573 i = pretty_pv.length - opt_limit;
578 } else if (toplay == 'B' && pretty_pv.length > 0) {
579 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
580 pv = move_num + '. … ' + move;
585 for ( ; i < pretty_pv.length; ++i) {
586 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
589 if (i > opt_limit && !opt_showlast) {
595 pv += move_num + '. ' + move;
606 var update_highlight = function() {
607 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
608 if ((current_display_line === null || current_display_line_is_history) &&
609 highlight_from !== undefined && highlight_to !== undefined) {
610 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
611 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
615 var update_history = function() {
616 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
617 $("#history").html("No history");
618 } else if (truncate_display_history) {
619 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
622 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
623 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
628 * @param {!boolean} truncate_history
630 var collapse_history = function(truncate_history) {
631 truncate_display_history = truncate_history;
634 window['collapse_history'] = collapse_history;
636 var update_refutation_lines = function() {
640 if (display_lines.length > 2) {
641 display_lines = [ display_lines[0], display_lines[1] ];
644 var tbl = $("#refutationlines");
648 for (var move in refutation_lines) {
651 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
652 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
653 for (var i = 0; i < moves.length; ++i) {
654 var line = refutation_lines[moves[i]];
656 var tr = document.createElement("tr");
658 var move_td = document.createElement("td");
659 tr.appendChild(move_td);
660 $(move_td).addClass("move");
661 if (line['pv_pretty'].length == 0) {
662 $(move_td).text(line['pretty_move']);
664 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
665 $(move_td).html(move);
668 var score_td = document.createElement("td");
669 tr.appendChild(score_td);
670 $(score_td).addClass("score");
671 $(score_td).text(line['pretty_score']);
673 var depth_td = document.createElement("td");
674 tr.appendChild(depth_td);
675 $(depth_td).addClass("depth");
676 $(depth_td).text("d" + line['depth']);
678 var pv_td = document.createElement("td");
679 tr.appendChild(pv_td);
680 $(pv_td).addClass("pv");
681 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
686 // Make one of the links clickable and the other nonclickable.
687 if (sort_refutation_lines_by_score) {
688 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
689 $("#sortbyscore1").html("<strong>Score</strong>");
691 $("#sortbyscore0").html("<strong>Move</strong>");
692 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
697 * @param {?string} fen
698 * @param {Array.<string>} moves
699 * @param {number} last_move
701 var chess_from = function(fen, moves, last_move) {
702 var hiddenboard = new Chess();
704 hiddenboard.load(fen);
706 for (var i = 0; i <= last_move; ++i) {
707 if (moves[i] === '0-0') {
708 hiddenboard.move('O-O');
709 } else if (moves[i] === '0-0-0') {
710 hiddenboard.move('O-O-O');
712 hiddenboard.move(moves[i]);
719 * @param {Object} data
720 * @param {?Object} display_data
722 var update_board = function(current_data, display_data) {
723 var data = display_data || current_data;
727 // Print the history. This is pretty much the only thing that's
728 // unconditionally taken from current_data (we're not interested in
729 // historic history).
730 if (current_data['position']['pretty_history']) {
731 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
733 display_lines.push(null);
737 // The headline. Names are always fetched from current_data;
738 // the rest can depend a bit.
741 current_data['position']['player_w'] && current_data['position']['player_b']) {
742 headline = current_data['position']['player_w'] + '–' +
743 current_data['position']['player_b'] + ', analysis';
745 headline = 'Analysis';
750 // Displaying some non-current position, pick out the last move
751 // from the history. This will work even if the fetch failed.
752 last_move = format_halfmove_with_number(
753 current_display_line.pretty_pv[current_display_move],
754 current_display_move + 1);
755 headline += ' after ' + last_move;
756 } else if (data['position']['last_move'] !== 'none') {
757 last_move = format_move_with_number(
758 data['position']['last_move'],
759 data['position']['move_num'],
760 data['position']['toplay'] == 'W');
761 headline += ' after ' + last_move;
765 $("#headline").text(headline);
767 // The <title> contains a very brief headline.
768 var title_elems = [];
769 if (data['short_score'] !== undefined && data['short_score'] !== null) {
770 title_elems.push(data['short_score'].replace(/^ /, ""));
772 if (last_move !== null) {
773 title_elems.push(last_move);
776 if (title_elems.length != 0) {
777 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
779 document.title = 'analysis.sesse.net';
782 // The last move (shown by highlighting the from and to squares).
783 if (data['position'] && data['position']['last_move_uci']) {
784 highlight_from = data['position']['last_move_uci'].substr(0, 2);
785 highlight_to = data['position']['last_move_uci'].substr(2, 2);
786 } else if (current_display_line_is_history && current_display_move >= 0) {
787 // We don't have historic analysis for this position, but we
788 // can reconstruct what the last move was by just replaying
790 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
791 var moves = hiddenboard.history({ verbose: true });
792 var last_move = moves.pop();
793 highlight_from = last_move.from;
794 highlight_to = last_move.to;
796 highlight_from = highlight_to = undefined;
800 if (data['failed']) {
801 $("#score").text("No analysis for this move");
803 $("#searchstats").html(" ");
804 $("#refutationlines").empty();
805 $("#whiteclock").empty();
806 $("#blackclock").empty();
807 refutation_lines = [];
808 update_refutation_lines();
810 update_displayed_line();
817 if (data['id'] && data['id']['name'] !== null) {
818 $("#engineid").text(data['id']['name']);
822 if (data['score'] !== null) {
823 $("#score").text(data['score']);
827 if (data['tablebase'] == 1) {
828 $("#searchstats").text("Tablebase result");
829 } else if (data['nodes'] && data['nps'] && data['depth']) {
830 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
831 if (data['seldepth']) {
832 stats += ' (' + data['seldepth'] + ' selective)';
834 if (data['tbhits'] && data['tbhits'] > 0) {
835 if (data['tbhits'] == 1) {
836 stats += ', one Syzygy hit';
838 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
842 $("#searchstats").text(stats);
844 $("#searchstats").text("");
847 // Update the board itself.
848 fen = data['position']['fen'];
849 update_displayed_line();
852 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
854 // Update the PV arrow.
856 if (data['pv_uci'].length >= 1) {
857 // draw a continuation arrow as long as it's the same piece
858 for (var i = 0; i < data['pv_uci'].length; i += 2) {
859 var from = data['pv_uci'][i].substr(0, 2);
860 var to = data['pv_uci'][i].substr(2,4);
861 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
862 interfering_arrow(from, to)) {
865 create_arrow(from, to, '#f66', 6, 20);
868 var alt_moves = find_nonstupid_moves(data, 30);
869 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
870 create_arrow(alt_moves[i].substr(0, 2),
871 alt_moves[i].substr(2, 2), '#f66', 1, 10);
875 // See if all semi-reasonable moves have only one possible response.
876 if (data['pv_uci'].length >= 2) {
877 var nonstupid_moves = find_nonstupid_moves(data, 300);
878 var response = data['pv_uci'][1];
879 for (var i = 0; i < nonstupid_moves.length; ++i) {
880 if (nonstupid_moves[i] == data['pv_uci'][0]) {
881 // ignore the PV move for refutation lines.
884 if (!data['refutation_lines'] ||
885 !data['refutation_lines'][nonstupid_moves[i]] ||
886 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
887 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
888 // Incomplete PV, abort.
889 response = undefined;
892 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
893 if (response !== this_response) {
894 // Different response depending on lines, abort.
895 response = undefined;
900 if (nonstupid_moves.length > 0 && response !== undefined) {
901 create_arrow(response.substr(0, 2),
902 response.substr(2, 2), '#66f', 6, 20);
906 // Update the refutation lines.
907 fen = data['position']['fen'];
908 move_num = data['position']['move_num'];
909 toplay = data['position']['toplay'];
910 refutation_lines = data['refutation_lines'];
911 update_refutation_lines();
913 // Update the sparkline last, since its size depends on how everything else reflowed.
914 update_sparkline(data);
917 var update_sparkline = function(data) {
918 if (data && data['score_history']) {
919 var first_move_num = undefined;
920 for (var halfmove_num in data['score_history']) {
921 halfmove_num = parseInt(halfmove_num);
922 if (first_move_num === undefined || halfmove_num < first_move_num) {
923 first_move_num = halfmove_num;
926 if (first_move_num !== undefined) {
927 var last_move_num = data['position']['move_num'] * 2 - 3;
928 if (data['position']['toplay'] === 'B') {
932 // Possibly truncate some moves if we don't have enough width.
933 // FIXME: Sometimes width() for #scorecontainer (and by extent,
934 // #scoresparkcontainer) on Chrome for mobile seems to start off
935 // at something very small, and then suddenly snap back into place.
937 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
938 if (last_move_num - first_move_num > max_moves) {
939 first_move_num = last_move_num - max_moves;
942 var min_score = -100;
944 var last_score = null;
946 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
947 if (data['score_history'][halfmove_num]) {
948 var score = data['score_history'][halfmove_num][0];
949 if (score < min_score) min_score = score;
950 if (score > max_score) max_score = score;
951 last_score = data['score_history'][halfmove_num][0];
953 scores.push(last_score);
955 if (data['plot_score']) {
956 scores.push(data['plot_score']);
958 // FIXME: at some widths, calling sparkline() seems to push
959 // #scorecontainer under the board.
960 $("#scorespark").sparkline(scores, {
963 chartRangeMin: min_score,
964 chartRangeMax: max_score,
965 tooltipFormatter: function(sparkline, options, fields) {
966 return format_tooltip(data, fields[0].offset + first_move_num);
970 $("#scorespark").text("");
973 $("#scorespark").text("");
978 * @param {number} num_viewers
980 var update_num_viewers = function(num_viewers) {
981 if (num_viewers === null) {
982 $("#numviewers").text("");
983 } else if (num_viewers == 1) {
984 $("#numviewers").text("You are the only current viewer");
986 $("#numviewers").text(num_viewers + " current viewers");
990 var update_clock = function() {
991 clearTimeout(clock_timer);
993 var data = displayed_analysis_data || current_analysis_data;
994 if (data['position']) {
995 var result = data['position']['result'];
996 if (result === '1-0') {
997 $("#whiteclock").text("1");
998 $("#blackclock").text("0");
999 $("#whiteclock").removeClass("running-clock");
1000 $("#blackclock").removeClass("running-clock");
1003 if (result === '1/2-1/2') {
1004 $("#whiteclock").text("1/2");
1005 $("#blackclock").text("1/2");
1006 $("#whiteclock").removeClass("running-clock");
1007 $("#blackclock").removeClass("running-clock");
1010 if (result === '0-1') {
1011 $("#whiteclock").text("0");
1012 $("#blackclock").text("1");
1013 $("#whiteclock").removeClass("running-clock");
1014 $("#blackclock").removeClass("running-clock");
1019 var white_clock_ms = null;
1020 var black_clock_ms = null;
1021 var show_seconds = false;
1024 if (data['position'] &&
1025 data['position']['white_clock'] &&
1026 data['position']['black_clock']) {
1027 white_clock_ms = data['position']['white_clock'] * 1000;
1028 black_clock_ms = data['position']['black_clock'] * 1000;
1031 // Dynamic clock (only one, obviously).
1033 if (data['position']['white_clock_target']) {
1035 $("#whiteclock").addClass("running-clock");
1036 $("#blackclock").removeClass("running-clock");
1037 } else if (data['position']['black_clock_target']) {
1039 $("#whiteclock").removeClass("running-clock");
1040 $("#blackclock").addClass("running-clock");
1042 $("#whiteclock").removeClass("running-clock");
1043 $("#blackclock").removeClass("running-clock");
1047 var now = new Date().getTime() + client_clock_offset_ms;
1048 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1049 if (color === "white") {
1050 white_clock_ms = remaining_ms;
1052 black_clock_ms = remaining_ms;
1056 if (white_clock_ms === null || black_clock_ms === null) {
1057 $("#whiteclock").empty();
1058 $("#blackclock").empty();
1062 // If either player has ten minutes or less left, add the second counters.
1063 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1066 // See when the clock will change next, and update right after that.
1069 next_update_ms = remaining_ms % 1000 + 100;
1071 next_update_ms = remaining_ms % 60000 + 100;
1073 clock_timer = setTimeout(update_clock, next_update_ms);
1076 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1077 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1081 * @param {Number} remaining_ms
1082 * @param {boolean} show_seconds
1084 var format_clock = function(remaining_ms, show_seconds) {
1085 if (remaining_ms <= 0) {
1093 var remaining = Math.floor(remaining_ms / 1000);
1094 var seconds = remaining % 60;
1095 remaining = (remaining - seconds) / 60;
1096 var minutes = remaining % 60;
1097 remaining = (remaining - minutes) / 60;
1098 var hours = remaining;
1100 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1102 return format_2d(hours) + ":" + format_2d(minutes);
1109 var format_2d = function(x) {
1118 * @param {string} move
1119 * @param {Number} move_num
1120 * @param {boolean} white_to_play
1122 var format_move_with_number = function(move, move_num, white_to_play) {
1124 if (white_to_play) {
1125 ret = (move_num - 1) + '… ';
1127 ret = move_num + '. ';
1134 * @param {string} move
1135 * @param {Number} halfmove_num
1137 var format_halfmove_with_number = function(move, halfmove_num) {
1138 return format_move_with_number(
1140 Math.floor(halfmove_num / 2) + 1,
1141 halfmove_num % 2 == 0);
1145 * @param {Object} data
1146 * @param {Number} halfmove_num
1148 var format_tooltip = function(data, halfmove_num) {
1149 if (data['score_history'][halfmove_num] ||
1150 halfmove_num === data['position']['pretty_history'].length) {
1153 if (halfmove_num === data['position']['pretty_history'].length) {
1154 move = data['position']['last_move'];
1155 short_score = data['short_score'];
1157 move = data['position']['pretty_history'][halfmove_num];
1158 short_score = data['score_history'][halfmove_num][1];
1160 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1162 return "After " + move_with_number + ": " + short_score;
1164 for (var i = halfmove_num; i --> 0; ) {
1165 if (data['score_history'][i]) {
1166 var move = data['position']['pretty_history'][i];
1167 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1174 * @param {boolean} sort_by_score
1176 var resort_refutation_lines = function(sort_by_score) {
1177 sort_refutation_lines_by_score = sort_by_score;
1178 if (supports_html5_storage()) {
1179 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1181 update_refutation_lines();
1183 window['resort_refutation_lines'] = resort_refutation_lines;
1186 * @param {boolean} truncate_history
1188 var set_truncate_history = function(truncate_history) {
1189 truncate_display_history = truncate_history;
1190 update_refutation_lines();
1192 window['set_truncate_history'] = set_truncate_history;
1195 * @param {number} line_num
1196 * @param {number} move_num
1198 var show_line = function(line_num, move_num) {
1199 if (line_num == -1) {
1200 current_display_line = null;
1201 current_display_move = null;
1202 if (displayed_analysis_data) {
1203 // TODO: Support exiting to history position if we are in an
1204 // analysis line of a history position.
1205 displayed_analysis_data = null;
1206 update_board(current_analysis_data, displayed_analysis_data);
1209 current_display_line = display_lines[line_num];
1210 current_display_move = move_num;
1212 current_display_line_is_history = (line_num == 0);
1214 update_historic_analysis();
1215 update_displayed_line();
1219 window['show_line'] = show_line;
1221 var prev_move = function() {
1222 if (current_display_move > -1) {
1223 --current_display_move;
1225 update_historic_analysis();
1226 update_displayed_line();
1228 window['prev_move'] = prev_move;
1230 var next_move = function() {
1231 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1232 ++current_display_move;
1234 update_historic_analysis();
1235 update_displayed_line();
1237 window['next_move'] = next_move;
1239 var update_historic_analysis = function() {
1240 if (!current_display_line_is_history) {
1243 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1244 displayed_analysis_data = null;
1245 update_board(current_analysis_data, displayed_analysis_data);
1248 // Fetch old analysis for this line if it exists.
1249 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1250 var filename = "/history/move" + (current_display_move + 1) + "-" +
1251 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1253 current_historic_xhr = $.ajax({
1255 }).done(function(data, textstatus, xhr) {
1256 displayed_analysis_data = data;
1257 update_board(current_analysis_data, displayed_analysis_data);
1258 }).fail(function(jqXHR, textStatus, errorThrown) {
1259 if (textStatus === "abort") {
1260 // Aborted because we are switching backends. Don't do anything;
1261 // we will already have been cleared.
1263 displayed_analysis_data = {'failed': true};
1264 update_board(current_analysis_data, displayed_analysis_data);
1270 * @param {string} fen
1272 var update_imbalance = function(fen) {
1273 var hiddenboard = new Chess(fen);
1274 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1275 for (var row = 0; row < 8; ++row) {
1276 for (var col = 0; col < 8; ++col) {
1277 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1278 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1279 var square = col_text + row_text;
1280 var contents = hiddenboard.get(square);
1281 if (contents !== null) {
1282 if (contents.color === 'w') {
1283 ++imbalance[contents.type];
1285 --imbalance[contents.type];
1290 var white_imbalance = '';
1291 var black_imbalance = '';
1292 for (var piece in imbalance) {
1293 for (var i = 0; i < imbalance[piece]; ++i) {
1294 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1296 for (var i = 0; i < -imbalance[piece]; ++i) {
1297 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1300 $('#whiteimbalance').html(white_imbalance);
1301 $('#blackimbalance').html(black_imbalance);
1304 var update_displayed_line = function() {
1305 if (highlighted_move !== null) {
1306 highlighted_move.removeClass('highlight');
1308 if (current_display_line === null) {
1309 $("#linenav").hide();
1310 $("#linemsg").show();
1311 board.position(fen);
1312 update_imbalance(fen);
1316 $("#linenav").show();
1317 $("#linemsg").hide();
1319 if (current_display_move <= 0) {
1320 $("#prevmove").html("Previous");
1322 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1324 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1325 $("#nextmove").html("Next");
1327 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1330 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1331 highlighted_move.addClass('highlight');
1333 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1334 board.position(hiddenboard.fen());
1335 update_imbalance(hiddenboard.fen());
1339 * @param {boolean} param_enable_sound
1341 var set_sound = function(param_enable_sound) {
1342 enable_sound = param_enable_sound;
1344 $("#soundon").html("<strong>On</strong>");
1345 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1347 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1348 // and also preload the file since the user has selected audio.
1349 var ding = document.getElementById('ding');
1350 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1351 ding.src = 'ding.opus';
1355 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1356 $("#soundoff").html("<strong>Off</strong>");
1358 if (supports_html5_storage()) {
1359 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1362 window['set_sound'] = set_sound;
1365 * @param {string} new_backend_url
1367 var switch_backend = function(new_backend_url) {
1368 // Stop looking at historic data.
1369 current_display_line = null;
1370 current_display_move = null;
1371 displayed_analysis_data = null;
1372 if (current_historic_xhr) {
1373 current_historic_xhr.abort();
1376 // If we already have a backend response going, abort it.
1377 if (current_analysis_xhr) {
1378 current_analysis_xhr.abort();
1381 // Otherwise, we should have a timer going to start a new one.
1383 if (current_analysis_request_timer) {
1384 clearTimeout(current_analysis_request_timer);
1385 current_analysis_request_timer = null;
1388 // Request an immediate fetch with the new backend.
1389 backend_url = new_backend_url;
1393 window['switch_backend'] = switch_backend;
1395 var init = function() {
1396 unique = get_unique();
1398 // Load settings from HTML5 local storage if available.
1399 if (supports_html5_storage() && localStorage['enable_sound']) {
1400 set_sound(parseInt(localStorage['enable_sound']));
1404 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1405 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1407 sort_refutation_lines_by_score = true;
1411 board = new window.ChessBoard('board', 'start');
1414 $(window).resize(function() {
1416 update_sparkline(displayed_analysis_data || current_analysis_data);
1420 $(window).keyup(function(event) {
1421 if (event.which == 39) {
1423 } else if (event.which == 37) {
1428 $(document).ready(init);