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 if (arrows[i].svg.parentElement) {
256 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
258 delete arrows[i].svg;
263 occupied_by_arrows = [];
264 for (var y = 0; y < 8; ++y) {
265 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
269 var redraw_arrows = function() {
270 for (var i = 0; i < arrows.length; ++i) {
271 position_arrow(arrows[i]);
275 /** @param {!number} x
278 var sign = function(x) {
288 /** See if drawing this arrow on the board would cause unduly amount of confusion.
289 * @param {!string} from The square the arrow is from (e.g. e4).
290 * @param {!string} to The square the arrow is to (e.g. e4).
293 var interfering_arrow = function(from, to) {
294 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
295 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
296 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
297 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
299 occupied_by_arrows[from_row][from_col] = true;
301 // Knight move: Just check that we haven't been at the destination before.
302 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
303 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
304 return occupied_by_arrows[to_row][to_col];
307 // Sliding piece: Check if anything except the from-square is seen before.
308 var dx = sign(to_col - from_col);
309 var dy = sign(to_row - from_row);
315 if (occupied_by_arrows[y][x]) {
318 occupied_by_arrows[y][x] = true;
319 } while (x != to_col || y != to_row);
324 /** Find a point along the coordinate system given by the given line,
325 * <t> units forward from the start of the line, <u> units to the right of it.
326 * @param {!number} x1
327 * @param {!number} x2
328 * @param {!number} y1
329 * @param {!number} y2
332 * @return {!string} The point in "x y" form, suitable for SVG paths.
334 var point_from_start = function(x1, y1, x2, y2, t, u) {
338 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
342 var x = x1 + dx * t + dy * u;
343 var y = y1 + dy * t - dx * u;
347 /** Find a point along the coordinate system given by the given line,
348 * <t> units forward from the end of the line, <u> units to the right of it.
349 * @param {!number} x1
350 * @param {!number} x2
351 * @param {!number} y1
352 * @param {!number} y2
355 * @return {!string} The point in "x y" form, suitable for SVG paths.
357 var point_from_end = function(x1, y1, x2, y2, t, u) {
361 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
365 var x = x2 + dx * t + dy * u;
366 var y = y2 + dy * t - dx * u;
370 var position_arrow = function(arrow) {
372 if (arrow.svg.parentElement) {
373 arrow.svg.parentElement.removeChild(arrow.svg);
377 if (current_display_line !== null && !current_display_line_is_history) {
381 var pos = $(".square-a8").position();
383 var zoom_factor = $("#board").width() / 400.0;
384 var line_width = arrow.line_width * zoom_factor;
385 var arrow_size = arrow.arrow_size * zoom_factor;
387 var square_width = $(".square-a8").width();
388 var from_y = (7 - arrow.from_row + 0.5)*square_width;
389 var to_y = (7 - arrow.to_row + 0.5)*square_width;
390 var from_x = (arrow.from_col + 0.5)*square_width;
391 var to_x = (arrow.to_col + 0.5)*square_width;
393 var SVG_NS = "http://www.w3.org/2000/svg";
394 var XHTML_NS = "http://www.w3.org/1999/xhtml";
395 var svg = document.createElementNS(SVG_NS, "svg");
396 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
397 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
398 svg.setAttribute("style", "position: absolute");
399 svg.setAttribute("position", "absolute");
400 svg.setAttribute("version", "1.1");
401 svg.setAttribute("class", "c1");
402 svg.setAttribute("xmlns", XHTML_NS);
410 var outline = document.createElementNS(SVG_NS, "path");
411 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));
412 outline.setAttribute("xmlns", XHTML_NS);
413 outline.setAttribute("stroke", "#666");
414 outline.setAttribute("stroke-width", line_width + 2);
415 outline.setAttribute("fill", "none");
416 svg.appendChild(outline);
418 var path = document.createElementNS(SVG_NS, "path");
419 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));
420 path.setAttribute("xmlns", XHTML_NS);
421 path.setAttribute("stroke", arrow.fg_color);
422 path.setAttribute("stroke-width", line_width);
423 path.setAttribute("fill", "none");
424 svg.appendChild(path);
426 // Then the arrow head.
427 var head = document.createElementNS(SVG_NS, "path");
428 head.setAttribute("d",
429 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
430 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
431 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
432 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
433 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
434 head.setAttribute("xmlns", XHTML_NS);
435 head.setAttribute("stroke", "#000");
436 head.setAttribute("stroke-width", "1");
437 head.setAttribute("fill", arrow.fg_color);
438 svg.appendChild(head);
440 $(svg).css({ top: pos.top, left: pos.left });
441 document.body.appendChild(svg);
446 * @param {!string} from_square
447 * @param {!string} to_square
448 * @param {!string} fg_color
449 * @param {number} line_width
450 * @param {number} arrow_size
452 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
453 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
454 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
455 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
456 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
464 line_width: line_width,
465 arrow_size: arrow_size,
469 position_arrow(arrow);
473 var compare_by_sort_key = function(refutation_lines, a, b) {
474 var ska = refutation_lines[a]['sort_key'];
475 var skb = refutation_lines[b]['sort_key'];
476 if (ska < skb) return -1;
477 if (ska > skb) return 1;
481 var compare_by_score = function(refutation_lines, a, b) {
482 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
483 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
488 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
489 * sorted by quality, descending.
491 * @param {!Object} data
492 * @param {number} margin The maximum number of centipawns worse than the
493 * best move can be and still be included.
494 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
495 * moves, in score order.
497 var find_nonstupid_moves = function(data, margin) {
498 // First of all, if there are any moves that are more than 0.5 ahead of
499 // the primary move, the refutation lines are probably bunk, so just
501 var best_score = undefined;
502 var pv_score = undefined;
503 for (var move in data['refutation_lines']) {
504 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
505 if (move == data['pv_uci'][0]) {
508 if (best_score === undefined || score > best_score) {
511 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
516 if (best_score - pv_score > 50) {
520 // Now find all moves that are within “margin” of the best score.
521 // The PV move will always be first.
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] && best_score - score <= margin) {
529 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
530 moves.unshift(data['pv_uci'][0]);
539 var thousands = function(x) {
540 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
544 * @param {!string} fen
545 * @param {Array.<string>} pretty_pv
546 * @param {number} move_num
547 * @param {!string} toplay
548 * @param {number=} opt_limit
549 * @param {boolean=} opt_showlast
551 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
554 pretty_pv: pretty_pv,
555 line_number: display_lines.length
557 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
561 * @param {number} line_num
562 * @param {Array.<string>} pretty_pv
563 * @param {number} move_num
564 * @param {!string} toplay
565 * @param {number=} opt_limit
566 * @param {boolean=} opt_showlast
568 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
571 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
572 // Truncate the PV at the beginning (instead of at the end).
573 // We assume here that toplay is 'W'. We also assume that if
574 // opt_showlast is set, then it is the history, and thus,
575 // the UI should be to expand the history.
576 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
577 i = pretty_pv.length - opt_limit;
582 } else if (toplay == 'B' && pretty_pv.length > 0) {
583 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
584 pv = move_num + '. … ' + move;
589 for ( ; i < pretty_pv.length; ++i) {
590 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
593 if (i > opt_limit && !opt_showlast) {
599 pv += move_num + '. ' + move;
610 var update_highlight = function() {
611 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
612 if ((current_display_line === null || current_display_line_is_history) &&
613 highlight_from !== undefined && highlight_to !== undefined) {
614 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
615 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
619 var update_history = function() {
620 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
621 $("#history").html("No history");
622 } else if (truncate_display_history) {
623 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
626 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
627 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
632 * @param {!boolean} truncate_history
634 var collapse_history = function(truncate_history) {
635 truncate_display_history = truncate_history;
638 window['collapse_history'] = collapse_history;
640 var update_refutation_lines = function() {
644 if (display_lines.length > 2) {
645 display_lines = [ display_lines[0], display_lines[1] ];
648 var tbl = $("#refutationlines");
652 for (var move in refutation_lines) {
655 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
656 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
657 for (var i = 0; i < moves.length; ++i) {
658 var line = refutation_lines[moves[i]];
660 var tr = document.createElement("tr");
662 var move_td = document.createElement("td");
663 tr.appendChild(move_td);
664 $(move_td).addClass("move");
665 if (line['pv_pretty'].length == 0) {
666 $(move_td).text(line['pretty_move']);
668 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
669 $(move_td).html(move);
672 var score_td = document.createElement("td");
673 tr.appendChild(score_td);
674 $(score_td).addClass("score");
675 $(score_td).text(line['pretty_score']);
677 var depth_td = document.createElement("td");
678 tr.appendChild(depth_td);
679 $(depth_td).addClass("depth");
680 $(depth_td).text("d" + line['depth']);
682 var pv_td = document.createElement("td");
683 tr.appendChild(pv_td);
684 $(pv_td).addClass("pv");
685 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
690 // Make one of the links clickable and the other nonclickable.
691 if (sort_refutation_lines_by_score) {
692 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
693 $("#sortbyscore1").html("<strong>Score</strong>");
695 $("#sortbyscore0").html("<strong>Move</strong>");
696 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
701 * @param {?string} fen
702 * @param {Array.<string>} moves
703 * @param {number} last_move
705 var chess_from = function(fen, moves, last_move) {
706 var hiddenboard = new Chess();
708 hiddenboard.load(fen);
710 for (var i = 0; i <= last_move; ++i) {
711 if (moves[i] === '0-0') {
712 hiddenboard.move('O-O');
713 } else if (moves[i] === '0-0-0') {
714 hiddenboard.move('O-O-O');
716 hiddenboard.move(moves[i]);
723 * @param {Object} data
724 * @param {?Object} display_data
726 var update_board = function(current_data, display_data) {
727 var data = display_data || current_data;
731 // Print the history. This is pretty much the only thing that's
732 // unconditionally taken from current_data (we're not interested in
733 // historic history).
734 if (current_data['position']['pretty_history']) {
735 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
737 display_lines.push(null);
741 // The headline. Names are always fetched from current_data;
742 // the rest can depend a bit.
745 current_data['position']['player_w'] && current_data['position']['player_b']) {
746 headline = current_data['position']['player_w'] + '–' +
747 current_data['position']['player_b'] + ', analysis';
749 headline = 'Analysis';
754 // Displaying some non-current position, pick out the last move
755 // from the history. This will work even if the fetch failed.
756 last_move = format_halfmove_with_number(
757 current_display_line.pretty_pv[current_display_move],
758 current_display_move + 1);
759 headline += ' after ' + last_move;
760 } else if (data['position']['last_move'] !== 'none') {
761 last_move = format_move_with_number(
762 data['position']['last_move'],
763 data['position']['move_num'],
764 data['position']['toplay'] == 'W');
765 headline += ' after ' + last_move;
769 $("#headline").text(headline);
771 // The <title> contains a very brief headline.
772 var title_elems = [];
773 if (data['short_score'] !== undefined && data['short_score'] !== null) {
774 title_elems.push(data['short_score'].replace(/^ /, ""));
776 if (last_move !== null) {
777 title_elems.push(last_move);
780 if (title_elems.length != 0) {
781 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
783 document.title = 'analysis.sesse.net';
786 // The last move (shown by highlighting the from and to squares).
787 if (data['position'] && data['position']['last_move_uci']) {
788 highlight_from = data['position']['last_move_uci'].substr(0, 2);
789 highlight_to = data['position']['last_move_uci'].substr(2, 2);
790 } else if (current_display_line_is_history && current_display_move >= 0) {
791 // We don't have historic analysis for this position, but we
792 // can reconstruct what the last move was by just replaying
794 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
795 var moves = hiddenboard.history({ verbose: true });
796 var last_move = moves.pop();
797 highlight_from = last_move.from;
798 highlight_to = last_move.to;
800 highlight_from = highlight_to = undefined;
804 if (data['failed']) {
805 $("#score").text("No analysis for this move");
807 $("#searchstats").html(" ");
808 $("#refutationlines").empty();
809 $("#whiteclock").empty();
810 $("#blackclock").empty();
811 refutation_lines = [];
812 update_refutation_lines();
814 update_displayed_line();
821 if (data['id'] && data['id']['name'] !== null) {
822 $("#engineid").text(data['id']['name']);
826 if (data['score'] !== null) {
827 $("#score").text(data['score']);
831 if (data['tablebase'] == 1) {
832 $("#searchstats").text("Tablebase result");
833 } else if (data['nodes'] && data['nps'] && data['depth']) {
834 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
835 if (data['seldepth']) {
836 stats += ' (' + data['seldepth'] + ' selective)';
838 if (data['tbhits'] && data['tbhits'] > 0) {
839 if (data['tbhits'] == 1) {
840 stats += ', one Syzygy hit';
842 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
846 $("#searchstats").text(stats);
848 $("#searchstats").text("");
851 // Update the board itself.
852 fen = data['position']['fen'];
853 update_displayed_line();
856 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
858 // Update the PV arrow.
860 if (data['pv_uci'].length >= 1) {
861 // draw a continuation arrow as long as it's the same piece
862 for (var i = 0; i < data['pv_uci'].length; i += 2) {
863 var from = data['pv_uci'][i].substr(0, 2);
864 var to = data['pv_uci'][i].substr(2,4);
865 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
866 interfering_arrow(from, to)) {
869 create_arrow(from, to, '#f66', 6, 20);
872 var alt_moves = find_nonstupid_moves(data, 30);
873 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
874 create_arrow(alt_moves[i].substr(0, 2),
875 alt_moves[i].substr(2, 2), '#f66', 1, 10);
879 // See if all semi-reasonable moves have only one possible response.
880 if (data['pv_uci'].length >= 2) {
881 var nonstupid_moves = find_nonstupid_moves(data, 300);
882 var response = data['pv_uci'][1];
883 for (var i = 0; i < nonstupid_moves.length; ++i) {
884 if (nonstupid_moves[i] == data['pv_uci'][0]) {
885 // ignore the PV move for refutation lines.
888 if (!data['refutation_lines'] ||
889 !data['refutation_lines'][nonstupid_moves[i]] ||
890 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
891 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
892 // Incomplete PV, abort.
893 response = undefined;
896 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
897 if (response !== this_response) {
898 // Different response depending on lines, abort.
899 response = undefined;
904 if (nonstupid_moves.length > 0 && response !== undefined) {
905 create_arrow(response.substr(0, 2),
906 response.substr(2, 2), '#66f', 6, 20);
910 // Update the refutation lines.
911 fen = data['position']['fen'];
912 move_num = data['position']['move_num'];
913 toplay = data['position']['toplay'];
914 refutation_lines = data['refutation_lines'];
915 update_refutation_lines();
917 // Update the sparkline last, since its size depends on how everything else reflowed.
918 update_sparkline(data);
921 var update_sparkline = function(data) {
922 if (data && data['score_history']) {
923 var first_move_num = undefined;
924 for (var halfmove_num in data['score_history']) {
925 halfmove_num = parseInt(halfmove_num);
926 if (first_move_num === undefined || halfmove_num < first_move_num) {
927 first_move_num = halfmove_num;
930 if (first_move_num !== undefined) {
931 var last_move_num = data['position']['move_num'] * 2 - 3;
932 if (data['position']['toplay'] === 'B') {
936 // Possibly truncate some moves if we don't have enough width.
937 // FIXME: Sometimes width() for #scorecontainer (and by extent,
938 // #scoresparkcontainer) on Chrome for mobile seems to start off
939 // at something very small, and then suddenly snap back into place.
941 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
942 if (last_move_num - first_move_num > max_moves) {
943 first_move_num = last_move_num - max_moves;
946 var min_score = -100;
948 var last_score = null;
950 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
951 if (data['score_history'][halfmove_num]) {
952 var score = data['score_history'][halfmove_num][0];
953 if (score < min_score) min_score = score;
954 if (score > max_score) max_score = score;
955 last_score = data['score_history'][halfmove_num][0];
957 scores.push(last_score);
959 if (data['plot_score']) {
960 scores.push(data['plot_score']);
962 // FIXME: at some widths, calling sparkline() seems to push
963 // #scorecontainer under the board.
964 $("#scorespark").sparkline(scores, {
967 chartRangeMin: min_score,
968 chartRangeMax: max_score,
969 tooltipFormatter: function(sparkline, options, fields) {
970 return format_tooltip(data, fields[0].offset + first_move_num);
974 $("#scorespark").text("");
977 $("#scorespark").text("");
982 * @param {number} num_viewers
984 var update_num_viewers = function(num_viewers) {
985 if (num_viewers === null) {
986 $("#numviewers").text("");
987 } else if (num_viewers == 1) {
988 $("#numviewers").text("You are the only current viewer");
990 $("#numviewers").text(num_viewers + " current viewers");
994 var update_clock = function() {
995 clearTimeout(clock_timer);
997 var data = displayed_analysis_data || current_analysis_data;
998 if (data['position']) {
999 var result = data['position']['result'];
1000 if (result === '1-0') {
1001 $("#whiteclock").text("1");
1002 $("#blackclock").text("0");
1003 $("#whiteclock").removeClass("running-clock");
1004 $("#blackclock").removeClass("running-clock");
1007 if (result === '1/2-1/2') {
1008 $("#whiteclock").text("1/2");
1009 $("#blackclock").text("1/2");
1010 $("#whiteclock").removeClass("running-clock");
1011 $("#blackclock").removeClass("running-clock");
1014 if (result === '0-1') {
1015 $("#whiteclock").text("0");
1016 $("#blackclock").text("1");
1017 $("#whiteclock").removeClass("running-clock");
1018 $("#blackclock").removeClass("running-clock");
1023 var white_clock_ms = null;
1024 var black_clock_ms = null;
1025 var show_seconds = false;
1028 if (data['position'] &&
1029 data['position']['white_clock'] &&
1030 data['position']['black_clock']) {
1031 white_clock_ms = data['position']['white_clock'] * 1000;
1032 black_clock_ms = data['position']['black_clock'] * 1000;
1035 // Dynamic clock (only one, obviously).
1037 if (data['position']['white_clock_target']) {
1039 $("#whiteclock").addClass("running-clock");
1040 $("#blackclock").removeClass("running-clock");
1041 } else if (data['position']['black_clock_target']) {
1043 $("#whiteclock").removeClass("running-clock");
1044 $("#blackclock").addClass("running-clock");
1046 $("#whiteclock").removeClass("running-clock");
1047 $("#blackclock").removeClass("running-clock");
1051 var now = new Date().getTime() + client_clock_offset_ms;
1052 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1053 if (color === "white") {
1054 white_clock_ms = remaining_ms;
1056 black_clock_ms = remaining_ms;
1060 if (white_clock_ms === null || black_clock_ms === null) {
1061 $("#whiteclock").empty();
1062 $("#blackclock").empty();
1066 // If either player has ten minutes or less left, add the second counters.
1067 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1070 // See when the clock will change next, and update right after that.
1073 next_update_ms = remaining_ms % 1000 + 100;
1075 next_update_ms = remaining_ms % 60000 + 100;
1077 clock_timer = setTimeout(update_clock, next_update_ms);
1080 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1081 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1085 * @param {Number} remaining_ms
1086 * @param {boolean} show_seconds
1088 var format_clock = function(remaining_ms, show_seconds) {
1089 if (remaining_ms <= 0) {
1097 var remaining = Math.floor(remaining_ms / 1000);
1098 var seconds = remaining % 60;
1099 remaining = (remaining - seconds) / 60;
1100 var minutes = remaining % 60;
1101 remaining = (remaining - minutes) / 60;
1102 var hours = remaining;
1104 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1106 return format_2d(hours) + ":" + format_2d(minutes);
1113 var format_2d = function(x) {
1122 * @param {string} move
1123 * @param {Number} move_num
1124 * @param {boolean} white_to_play
1126 var format_move_with_number = function(move, move_num, white_to_play) {
1128 if (white_to_play) {
1129 ret = (move_num - 1) + '… ';
1131 ret = move_num + '. ';
1138 * @param {string} move
1139 * @param {Number} halfmove_num
1141 var format_halfmove_with_number = function(move, halfmove_num) {
1142 return format_move_with_number(
1144 Math.floor(halfmove_num / 2) + 1,
1145 halfmove_num % 2 == 0);
1149 * @param {Object} data
1150 * @param {Number} halfmove_num
1152 var format_tooltip = function(data, halfmove_num) {
1153 if (data['score_history'][halfmove_num] ||
1154 halfmove_num === data['position']['pretty_history'].length) {
1157 if (halfmove_num === data['position']['pretty_history'].length) {
1158 move = data['position']['last_move'];
1159 short_score = data['short_score'];
1161 move = data['position']['pretty_history'][halfmove_num];
1162 short_score = data['score_history'][halfmove_num][1];
1164 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1166 return "After " + move_with_number + ": " + short_score;
1168 for (var i = halfmove_num; i --> 0; ) {
1169 if (data['score_history'][i]) {
1170 var move = data['position']['pretty_history'][i];
1171 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1178 * @param {boolean} sort_by_score
1180 var resort_refutation_lines = function(sort_by_score) {
1181 sort_refutation_lines_by_score = sort_by_score;
1182 if (supports_html5_storage()) {
1183 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1185 update_refutation_lines();
1187 window['resort_refutation_lines'] = resort_refutation_lines;
1190 * @param {boolean} truncate_history
1192 var set_truncate_history = function(truncate_history) {
1193 truncate_display_history = truncate_history;
1194 update_refutation_lines();
1196 window['set_truncate_history'] = set_truncate_history;
1199 * @param {number} line_num
1200 * @param {number} move_num
1202 var show_line = function(line_num, move_num) {
1203 if (line_num == -1) {
1204 current_display_line = null;
1205 current_display_move = null;
1206 if (displayed_analysis_data) {
1207 // TODO: Support exiting to history position if we are in an
1208 // analysis line of a history position.
1209 displayed_analysis_data = null;
1210 update_board(current_analysis_data, displayed_analysis_data);
1213 current_display_line = display_lines[line_num];
1214 current_display_move = move_num;
1216 current_display_line_is_history = (line_num == 0);
1218 update_historic_analysis();
1219 update_displayed_line();
1223 window['show_line'] = show_line;
1225 var prev_move = function() {
1226 if (current_display_move > -1) {
1227 --current_display_move;
1229 update_historic_analysis();
1230 update_displayed_line();
1232 window['prev_move'] = prev_move;
1234 var next_move = function() {
1235 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1236 ++current_display_move;
1238 update_historic_analysis();
1239 update_displayed_line();
1241 window['next_move'] = next_move;
1243 var update_historic_analysis = function() {
1244 if (!current_display_line_is_history) {
1247 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1248 displayed_analysis_data = null;
1249 update_board(current_analysis_data, displayed_analysis_data);
1252 // Fetch old analysis for this line if it exists.
1253 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1254 var filename = "/history/move" + (current_display_move + 1) + "-" +
1255 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1257 current_historic_xhr = $.ajax({
1259 }).done(function(data, textstatus, xhr) {
1260 displayed_analysis_data = data;
1261 update_board(current_analysis_data, displayed_analysis_data);
1262 }).fail(function(jqXHR, textStatus, errorThrown) {
1263 if (textStatus === "abort") {
1264 // Aborted because we are switching backends. Don't do anything;
1265 // we will already have been cleared.
1267 displayed_analysis_data = {'failed': true};
1268 update_board(current_analysis_data, displayed_analysis_data);
1274 * @param {string} fen
1276 var update_imbalance = function(fen) {
1277 var hiddenboard = new Chess(fen);
1278 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1279 for (var row = 0; row < 8; ++row) {
1280 for (var col = 0; col < 8; ++col) {
1281 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1282 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1283 var square = col_text + row_text;
1284 var contents = hiddenboard.get(square);
1285 if (contents !== null) {
1286 if (contents.color === 'w') {
1287 ++imbalance[contents.type];
1289 --imbalance[contents.type];
1294 var white_imbalance = '';
1295 var black_imbalance = '';
1296 for (var piece in imbalance) {
1297 for (var i = 0; i < imbalance[piece]; ++i) {
1298 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1300 for (var i = 0; i < -imbalance[piece]; ++i) {
1301 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1304 $('#whiteimbalance').html(white_imbalance);
1305 $('#blackimbalance').html(black_imbalance);
1308 var update_displayed_line = function() {
1309 if (highlighted_move !== null) {
1310 highlighted_move.removeClass('highlight');
1312 if (current_display_line === null) {
1313 $("#linenav").hide();
1314 $("#linemsg").show();
1315 board.position(fen);
1316 update_imbalance(fen);
1320 $("#linenav").show();
1321 $("#linemsg").hide();
1323 if (current_display_move <= 0) {
1324 $("#prevmove").html("Previous");
1326 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1328 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1329 $("#nextmove").html("Next");
1331 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1334 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1335 highlighted_move.addClass('highlight');
1337 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1338 board.position(hiddenboard.fen());
1339 update_imbalance(hiddenboard.fen());
1343 * @param {boolean} param_enable_sound
1345 var set_sound = function(param_enable_sound) {
1346 enable_sound = param_enable_sound;
1348 $("#soundon").html("<strong>On</strong>");
1349 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1351 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1352 // and also preload the file since the user has selected audio.
1353 var ding = document.getElementById('ding');
1354 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1355 ding.src = 'ding.opus';
1359 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1360 $("#soundoff").html("<strong>Off</strong>");
1362 if (supports_html5_storage()) {
1363 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1366 window['set_sound'] = set_sound;
1369 * @param {string} new_backend_url
1371 var switch_backend = function(new_backend_url) {
1372 // Stop looking at historic data.
1373 current_display_line = null;
1374 current_display_move = null;
1375 displayed_analysis_data = null;
1376 if (current_historic_xhr) {
1377 current_historic_xhr.abort();
1380 // If we already have a backend response going, abort it.
1381 if (current_analysis_xhr) {
1382 current_analysis_xhr.abort();
1385 // Otherwise, we should have a timer going to start a new one.
1387 if (current_analysis_request_timer) {
1388 clearTimeout(current_analysis_request_timer);
1389 current_analysis_request_timer = null;
1392 // Request an immediate fetch with the new backend.
1393 backend_url = new_backend_url;
1394 current_analysis_data = null;
1398 window['switch_backend'] = switch_backend;
1400 var init = function() {
1401 unique = get_unique();
1403 // Load settings from HTML5 local storage if available.
1404 if (supports_html5_storage() && localStorage['enable_sound']) {
1405 set_sound(parseInt(localStorage['enable_sound']));
1409 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1410 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1412 sort_refutation_lines_by_score = true;
1416 board = new window.ChessBoard('board', 'start');
1419 $(window).resize(function() {
1421 update_sparkline(displayed_analysis_data || current_analysis_data);
1425 $(window).keyup(function(event) {
1426 if (event.which == 39) {
1428 } else if (event.which == 37) {
1433 $(document).ready(init);