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 = 2015062103;
12 /** @type {window.ChessBoard} @private */
16 * The most recent analysis data we have from the server
17 * (about the most recent position).
21 var current_analysis_data = null;
24 * If we are displaying previous analysis, this is non-null,
25 * and will override most of current_analysis_data.
30 var displayed_analysis_data = null;
45 /** @type {Array.<Array.<boolean>>} */
46 var occupied_by_arrows = [];
48 var refutation_lines = [];
50 /** @type {!number} @private */
53 /** @type {!string} @private */
56 /** @type {number} @private */
59 /** @type {boolean} @private */
60 var sort_refutation_lines_by_score = true;
62 /** @type {boolean} @private */
63 var truncate_display_history = true;
65 /** @type {!string|undefined} @private */
66 var highlight_from = undefined;
68 /** @type {!string|undefined} @private */
69 var highlight_to = undefined;
71 /** @type {?jQuery} @private */
72 var highlighted_move = null;
74 /** @type {?number} @private */
77 /** @type {boolean} @private */
78 var enable_sound = false;
81 * Our best estimate of how many milliseconds we need to add to
82 * new Date() to get the true UTC time. Calibrated against the
88 var client_clock_offset_ms = null;
90 var clock_timer = null;
92 /** The current position on the board, represented as a FEN string.
100 * uci_pv: Array.<string>,
101 * pretty_pv: Array.<string>,
106 /** @type {Array.<DisplayLine>}
109 var display_lines = [];
111 /** @type {?DisplayLine} @private */
112 var current_display_line = null;
114 /** @type {boolean} @private */
115 var current_display_line_is_history = false;
117 /** @type {?number} @private */
118 var current_display_move = null;
120 var supports_html5_storage = function() {
122 return 'localStorage' in window && window['localStorage'] !== null;
128 // Make the unique token persistent so people refreshing the page won't count twice.
129 // Of course, you can never fully protect against people deliberately wanting to spam.
130 var get_unique = function() {
131 var use_local_storage = supports_html5_storage();
132 if (use_local_storage && localStorage['unique']) {
133 return localStorage['unique'];
135 var unique = Math.random();
136 if (use_local_storage) {
137 localStorage['unique'] = unique;
142 var request_update = function() {
144 url: "/analysis.pl?ims=" + ims + "&unique=" + unique
145 }).done(function(data, textstatus, xhr) {
146 sync_server_clock(xhr.getResponseHeader('Date'));
147 ims = xhr.getResponseHeader('X-RGLM');
148 var num_viewers = xhr.getResponseHeader('X-RGNV');
150 if (Array.isArray(data)) {
151 new_data = JSON.parse(JSON.stringify(current_analysis_data));
152 JSON_delta.patch(new_data, data);
157 var minimum_version = xhr.getResponseHeader('X-RGMV');
158 if (minimum_version && minimum_version > SCRIPT_VERSION) {
159 // Upgrade to latest version with a force-reload.
160 location.reload(true);
163 possibly_play_sound(current_analysis_data, new_data);
164 current_analysis_data = new_data;
165 update_board(current_analysis_data, displayed_analysis_data);
166 update_num_viewers(num_viewers);
169 setTimeout(function() { request_update(); }, 100);
171 // Wait ten seconds, then try again.
172 setTimeout(function() { request_update(); }, 10000);
176 var possibly_play_sound = function(old_data, new_data) {
180 if (old_data === null) {
183 var ding = document.getElementById('ding');
184 if (ding && ding.play) {
185 if (old_data['position'] && old_data['position']['fen'] &&
186 new_data['position'] && new_data['position']['fen'] &&
187 (old_data['position']['fen'] !== new_data['position']['fen'] ||
188 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
195 * @type {!string} server_date_string
197 var sync_server_clock = function(server_date_string) {
198 var server_time_ms = new Date(server_date_string).getTime();
199 var client_time_ms = new Date().getTime();
200 var estimated_offset_ms = server_time_ms - client_time_ms;
202 // In order not to let the noise move us too much back and forth
203 // (the server only has one-second resolution anyway), we only
204 // change an existing skew if we are at least five seconds off.
205 if (client_clock_offset_ms === null ||
206 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
207 client_clock_offset_ms = estimated_offset_ms;
211 var clear_arrows = function() {
212 for (var i = 0; i < arrows.length; ++i) {
214 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
215 delete arrows[i].svg;
220 occupied_by_arrows = [];
221 for (var y = 0; y < 8; ++y) {
222 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
226 var redraw_arrows = function() {
227 for (var i = 0; i < arrows.length; ++i) {
228 position_arrow(arrows[i]);
232 /** @param {!number} x
235 var sign = function(x) {
245 /** See if drawing this arrow on the board would cause unduly amount of confusion.
246 * @param {!string} from The square the arrow is from (e.g. e4).
247 * @param {!string} to The square the arrow is to (e.g. e4).
250 var interfering_arrow = function(from, to) {
251 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
252 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
253 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
254 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
256 occupied_by_arrows[from_row][from_col] = true;
258 // Knight move: Just check that we haven't been at the destination before.
259 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
260 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
261 return occupied_by_arrows[to_row][to_col];
264 // Sliding piece: Check if anything except the from-square is seen before.
265 var dx = sign(to_col - from_col);
266 var dy = sign(to_row - from_row);
272 if (occupied_by_arrows[y][x]) {
275 occupied_by_arrows[y][x] = true;
276 } while (x != to_col || y != to_row);
281 /** Find a point along the coordinate system given by the given line,
282 * <t> units forward from the start of the line, <u> units to the right of it.
283 * @param {!number} x1
284 * @param {!number} x2
285 * @param {!number} y1
286 * @param {!number} y2
289 * @return {!string} The point in "x y" form, suitable for SVG paths.
291 var point_from_start = function(x1, y1, x2, y2, t, u) {
295 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
299 var x = x1 + dx * t + dy * u;
300 var y = y1 + dy * t - dx * u;
304 /** Find a point along the coordinate system given by the given line,
305 * <t> units forward from the end of the line, <u> units to the right of it.
306 * @param {!number} x1
307 * @param {!number} x2
308 * @param {!number} y1
309 * @param {!number} y2
312 * @return {!string} The point in "x y" form, suitable for SVG paths.
314 var point_from_end = function(x1, y1, x2, y2, t, u) {
318 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
322 var x = x2 + dx * t + dy * u;
323 var y = y2 + dy * t - dx * u;
327 var position_arrow = function(arrow) {
329 arrow.svg.parentElement.removeChild(arrow.svg);
332 if (current_display_line !== null && !current_display_line_is_history) {
336 var pos = $(".square-a8").position();
338 var zoom_factor = $("#board").width() / 400.0;
339 var line_width = arrow.line_width * zoom_factor;
340 var arrow_size = arrow.arrow_size * zoom_factor;
342 var square_width = $(".square-a8").width();
343 var from_y = (7 - arrow.from_row + 0.5)*square_width;
344 var to_y = (7 - arrow.to_row + 0.5)*square_width;
345 var from_x = (arrow.from_col + 0.5)*square_width;
346 var to_x = (arrow.to_col + 0.5)*square_width;
348 var SVG_NS = "http://www.w3.org/2000/svg";
349 var XHTML_NS = "http://www.w3.org/1999/xhtml";
350 var svg = document.createElementNS(SVG_NS, "svg");
351 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
352 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
353 svg.setAttribute("style", "position: absolute");
354 svg.setAttribute("position", "absolute");
355 svg.setAttribute("version", "1.1");
356 svg.setAttribute("class", "c1");
357 svg.setAttribute("xmlns", XHTML_NS);
365 var outline = document.createElementNS(SVG_NS, "path");
366 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));
367 outline.setAttribute("xmlns", XHTML_NS);
368 outline.setAttribute("stroke", "#666");
369 outline.setAttribute("stroke-width", line_width + 2);
370 outline.setAttribute("fill", "none");
371 svg.appendChild(outline);
373 var path = document.createElementNS(SVG_NS, "path");
374 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));
375 path.setAttribute("xmlns", XHTML_NS);
376 path.setAttribute("stroke", arrow.fg_color);
377 path.setAttribute("stroke-width", line_width);
378 path.setAttribute("fill", "none");
379 svg.appendChild(path);
381 // Then the arrow head.
382 var head = document.createElementNS(SVG_NS, "path");
383 head.setAttribute("d",
384 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
385 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
386 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
387 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
388 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
389 head.setAttribute("xmlns", XHTML_NS);
390 head.setAttribute("stroke", "#000");
391 head.setAttribute("stroke-width", "1");
392 head.setAttribute("fill", arrow.fg_color);
393 svg.appendChild(head);
395 $(svg).css({ top: pos.top, left: pos.left });
396 document.body.appendChild(svg);
401 * @param {!string} from_square
402 * @param {!string} to_square
403 * @param {!string} fg_color
404 * @param {number} line_width
405 * @param {number} arrow_size
407 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
408 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
409 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
410 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
411 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
419 line_width: line_width,
420 arrow_size: arrow_size,
424 position_arrow(arrow);
428 var compare_by_sort_key = function(refutation_lines, a, b) {
429 var ska = refutation_lines[a]['sort_key'];
430 var skb = refutation_lines[b]['sort_key'];
431 if (ska < skb) return -1;
432 if (ska > skb) return 1;
436 var compare_by_score = function(refutation_lines, a, b) {
437 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
438 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
443 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
444 * sorted by quality, descending.
446 * @param {!Object} data
447 * @param {number} margin The maximum number of centipawns worse than the
448 * best move can be and still be included.
449 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
450 * moves, in score order.
452 var find_nonstupid_moves = function(data, margin) {
453 // First of all, if there are any moves that are more than 0.5 ahead of
454 // the primary move, the refutation lines are probably bunk, so just
456 var best_score = undefined;
457 var pv_score = undefined;
458 for (var move in data['refutation_lines']) {
459 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
460 if (move == data['pv_uci'][0]) {
463 if (best_score === undefined || score > best_score) {
466 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
471 if (best_score - pv_score > 50) {
475 // Now find all moves that are within “margin” of the best score.
476 // The PV move will always be first.
478 for (var move in data['refutation_lines']) {
479 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
480 if (move != data['pv_uci'][0] && best_score - score <= margin) {
484 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
485 moves.unshift(data['pv_uci'][0]);
494 var thousands = function(x) {
495 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
499 * @param {!string} fen
500 * @param {Array.<string>} pretty_pv
501 * @param {number} move_num
502 * @param {!string} toplay
503 * @param {number=} opt_limit
504 * @param {boolean=} opt_showlast
506 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
509 pretty_pv: pretty_pv,
510 line_number: display_lines.length
512 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
516 * @param {number} line_num
517 * @param {Array.<string>} pretty_pv
518 * @param {number} move_num
519 * @param {!string} toplay
520 * @param {number=} opt_limit
521 * @param {boolean=} opt_showlast
523 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
526 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
527 // Truncate the PV at the beginning (instead of at the end).
528 // We assume here that toplay is 'W'. We also assume that if
529 // opt_showlast is set, then it is the history, and thus,
530 // the UI should be to expand the history.
531 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
532 i = pretty_pv.length - opt_limit;
537 } else if (toplay == 'B' && pretty_pv.length > 0) {
538 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
539 pv = move_num + '. … ' + move;
544 for ( ; i < pretty_pv.length; ++i) {
545 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
548 if (i > opt_limit && !opt_showlast) {
554 pv += move_num + '. ' + move;
565 var update_highlight = function() {
566 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
567 if ((current_display_line === null || current_display_line_is_history) &&
568 highlight_from !== undefined && highlight_to !== undefined) {
569 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
570 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
574 var update_history = function() {
575 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
576 $("#history").html("No history");
577 } else if (truncate_display_history) {
578 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
581 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
582 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
587 * @param {!boolean} truncate_history
589 var collapse_history = function(truncate_history) {
590 truncate_display_history = truncate_history;
593 window['collapse_history'] = collapse_history;
595 var update_refutation_lines = function() {
599 if (display_lines.length > 2) {
600 display_lines = [ display_lines[0], display_lines[1] ];
603 var tbl = $("#refutationlines");
607 for (var move in refutation_lines) {
610 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
611 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
612 for (var i = 0; i < moves.length; ++i) {
613 var line = refutation_lines[moves[i]];
615 var tr = document.createElement("tr");
617 var move_td = document.createElement("td");
618 tr.appendChild(move_td);
619 $(move_td).addClass("move");
620 if (line['pv_pretty'].length == 0) {
621 $(move_td).text(line['pretty_move']);
623 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
624 $(move_td).html(move);
627 var score_td = document.createElement("td");
628 tr.appendChild(score_td);
629 $(score_td).addClass("score");
630 $(score_td).text(line['pretty_score']);
632 var depth_td = document.createElement("td");
633 tr.appendChild(depth_td);
634 $(depth_td).addClass("depth");
635 $(depth_td).text("d" + line['depth']);
637 var pv_td = document.createElement("td");
638 tr.appendChild(pv_td);
639 $(pv_td).addClass("pv");
640 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
645 // Make one of the links clickable and the other nonclickable.
646 if (sort_refutation_lines_by_score) {
647 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
648 $("#sortbyscore1").html("<strong>Score</strong>");
650 $("#sortbyscore0").html("<strong>Move</strong>");
651 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
656 * @param {?string} fen
657 * @param {Array.<string>} moves
658 * @param {number} last_move
660 var chess_from = function(fen, moves, last_move) {
661 var hiddenboard = new Chess();
663 hiddenboard.load(fen);
665 for (var i = 0; i <= last_move; ++i) {
666 if (moves[i] === '0-0') {
667 hiddenboard.move('O-O');
668 } else if (moves[i] === '0-0-0') {
669 hiddenboard.move('O-O-O');
671 hiddenboard.move(moves[i]);
678 * @param {Object} data
679 * @param {?Object} display_data
681 var update_board = function(current_data, display_data) {
682 var data = display_data || current_data;
686 // Print the history. This is pretty much the only thing that's
687 // unconditionally taken from current_data (we're not interested in
688 // historic history).
689 if (current_data['position']['pretty_history']) {
690 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
692 display_lines.push(null);
696 // The headline. Names are always fetched from current_data;
697 // the rest can depend a bit.
700 current_data['position']['player_w'] && current_data['position']['player_b']) {
701 headline = current_data['position']['player_w'] + '–' +
702 current_data['position']['player_b'] + ', analysis';
704 headline = 'Analysis';
709 // Displaying some non-current position, pick out the last move
710 // from the history. This will work even if the fetch failed.
711 last_move = format_halfmove_with_number(
712 current_display_line.pretty_pv[current_display_move],
713 current_display_move + 1);
714 headline += ' after ' + last_move;
715 } else if (data['position']['last_move'] !== 'none') {
716 last_move = format_move_with_number(
717 data['position']['last_move'],
718 data['position']['move_num'],
719 data['position']['toplay'] == 'W');
720 headline += ' after ' + last_move;
724 $("#headline").text(headline);
726 // The <title> contains a very brief headline.
727 var title_elems = [];
728 if (data['short_score'] !== undefined && data['short_score'] !== null) {
729 title_elems.push(data['short_score'].replace(/^ /, ""));
731 if (last_move !== null) {
732 title_elems.push(last_move);
735 if (title_elems.length != 0) {
736 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
738 document.title = 'analysis.sesse.net';
741 // The last move (shown by highlighting the from and to squares).
742 if (data['position'] && data['position']['last_move_uci']) {
743 highlight_from = data['position']['last_move_uci'].substr(0, 2);
744 highlight_to = data['position']['last_move_uci'].substr(2, 2);
745 } else if (current_display_line_is_history && current_display_move >= 0) {
746 // We don't have historic analysis for this position, but we
747 // can reconstruct what the last move was by just replaying
749 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
750 var moves = hiddenboard.history({ verbose: true });
751 var last_move = moves.pop();
752 highlight_from = last_move.from;
753 highlight_to = last_move.to;
755 highlight_from = highlight_to = undefined;
759 if (data['failed']) {
760 $("#score").text("No analysis for this move");
762 $("#searchstats").html(" ");
763 $("#refutationlines").empty();
764 $("#whiteclock").empty();
765 $("#blackclock").empty();
766 refutation_lines = [];
767 update_refutation_lines();
769 update_displayed_line();
776 if (data['id'] && data['id']['name'] !== null) {
777 $("#engineid").text(data['id']['name']);
781 if (data['score'] !== null) {
782 $("#score").text(data['score']);
786 if (data['tablebase'] == 1) {
787 $("#searchstats").text("Tablebase result");
788 } else if (data['nodes'] && data['nps'] && data['depth']) {
789 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
790 if (data['seldepth']) {
791 stats += ' (' + data['seldepth'] + ' selective)';
793 if (data['tbhits'] && data['tbhits'] > 0) {
794 if (data['tbhits'] == 1) {
795 stats += ', one Syzygy hit';
797 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
801 $("#searchstats").text(stats);
803 $("#searchstats").text("");
806 // Update the board itself.
807 fen = data['position']['fen'];
808 update_displayed_line();
811 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
813 // Update the PV arrow.
815 if (data['pv_uci'].length >= 1) {
816 // draw a continuation arrow as long as it's the same piece
817 for (var i = 0; i < data['pv_uci'].length; i += 2) {
818 var from = data['pv_uci'][i].substr(0, 2);
819 var to = data['pv_uci'][i].substr(2,4);
820 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
821 interfering_arrow(from, to)) {
824 create_arrow(from, to, '#f66', 6, 20);
827 var alt_moves = find_nonstupid_moves(data, 30);
828 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
829 create_arrow(alt_moves[i].substr(0, 2),
830 alt_moves[i].substr(2, 2), '#f66', 1, 10);
834 // See if all semi-reasonable moves have only one possible response.
835 if (data['pv_uci'].length >= 2) {
836 var nonstupid_moves = find_nonstupid_moves(data, 300);
837 var response = data['pv_uci'][1];
838 for (var i = 0; i < nonstupid_moves.length; ++i) {
839 if (nonstupid_moves[i] == data['pv_uci'][0]) {
840 // ignore the PV move for refutation lines.
843 if (!data['refutation_lines'] ||
844 !data['refutation_lines'][nonstupid_moves[i]] ||
845 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
846 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
847 // Incomplete PV, abort.
848 response = undefined;
851 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
852 if (response !== this_response) {
853 // Different response depending on lines, abort.
854 response = undefined;
859 if (nonstupid_moves.length > 0 && response !== undefined) {
860 create_arrow(response.substr(0, 2),
861 response.substr(2, 2), '#66f', 6, 20);
865 // Update the refutation lines.
866 fen = data['position']['fen'];
867 move_num = data['position']['move_num'];
868 toplay = data['position']['toplay'];
869 refutation_lines = data['refutation_lines'];
870 update_refutation_lines();
872 // Update the sparkline last, since its size depends on how everything else reflowed.
873 update_sparkline(data);
876 var update_sparkline = function(data) {
877 if (data && data['score_history']) {
878 var first_move_num = undefined;
879 for (var halfmove_num in data['score_history']) {
880 halfmove_num = parseInt(halfmove_num);
881 if (first_move_num === undefined || halfmove_num < first_move_num) {
882 first_move_num = halfmove_num;
885 if (first_move_num !== undefined) {
886 var last_move_num = data['position']['move_num'] * 2 - 3;
887 if (data['position']['toplay'] === 'B') {
891 // Possibly truncate some moves if we don't have enough width.
892 // FIXME: Sometimes width() for #scorecontainer (and by extent,
893 // #scoresparkcontainer) on Chrome for mobile seems to start off
894 // at something very small, and then suddenly snap back into place.
896 var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
897 if (last_move_num - first_move_num > max_moves) {
898 first_move_num = last_move_num - max_moves;
901 var min_score = -100;
903 var last_score = null;
905 for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
906 if (data['score_history'][halfmove_num]) {
907 var score = data['score_history'][halfmove_num][0];
908 if (score < min_score) min_score = score;
909 if (score > max_score) max_score = score;
910 last_score = data['score_history'][halfmove_num][0];
912 scores.push(last_score);
914 if (data['plot_score']) {
915 scores.push(data['plot_score']);
917 // FIXME: at some widths, calling sparkline() seems to push
918 // #scorecontainer under the board.
919 $("#scorespark").sparkline(scores, {
922 chartRangeMin: min_score,
923 chartRangeMax: max_score,
924 tooltipFormatter: function(sparkline, options, fields) {
925 return format_tooltip(data, fields[0].offset + first_move_num);
929 $("#scorespark").text("");
932 $("#scorespark").text("");
937 * @param {number} num_viewers
939 var update_num_viewers = function(num_viewers) {
940 if (num_viewers === null) {
941 $("#numviewers").text("");
942 } else if (num_viewers == 1) {
943 $("#numviewers").text("You are the only current viewer");
945 $("#numviewers").text(num_viewers + " current viewers");
949 var update_clock = function() {
950 clearTimeout(clock_timer);
952 var data = displayed_analysis_data || current_analysis_data;
953 if (data['position']) {
954 var result = data['position']['result'];
955 if (result === '1-0') {
956 $("#whiteclock").text("1");
957 $("#blackclock").text("0");
958 $("#whiteclock").removeClass("running-clock");
959 $("#blackclock").removeClass("running-clock");
962 if (result === '1/2-1/2') {
963 $("#whiteclock").text("1/2");
964 $("#blackclock").text("1/2");
965 $("#whiteclock").removeClass("running-clock");
966 $("#blackclock").removeClass("running-clock");
969 if (result === '0-1') {
970 $("#whiteclock").text("0");
971 $("#blackclock").text("1");
972 $("#whiteclock").removeClass("running-clock");
973 $("#blackclock").removeClass("running-clock");
978 var white_clock_ms = null;
979 var black_clock_ms = null;
980 var show_seconds = false;
983 if (data['position'] &&
984 data['position']['white_clock'] &&
985 data['position']['black_clock']) {
986 white_clock_ms = data['position']['white_clock'] * 1000;
987 black_clock_ms = data['position']['black_clock'] * 1000;
990 // Dynamic clock (only one, obviously).
992 if (data['position']['white_clock_target']) {
994 $("#whiteclock").addClass("running-clock");
995 $("#blackclock").removeClass("running-clock");
996 } else if (data['position']['black_clock_target']) {
998 $("#whiteclock").removeClass("running-clock");
999 $("#blackclock").addClass("running-clock");
1001 $("#whiteclock").removeClass("running-clock");
1002 $("#blackclock").removeClass("running-clock");
1006 var now = new Date().getTime() + client_clock_offset_ms;
1007 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1008 if (color === "white") {
1009 white_clock_ms = remaining_ms;
1011 black_clock_ms = remaining_ms;
1015 if (white_clock_ms === null || black_clock_ms === null) {
1016 $("#whiteclock").empty();
1017 $("#blackclock").empty();
1021 // If either player has ten minutes or less left, add the second counters.
1022 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1025 // See when the clock will change next, and update right after that.
1028 next_update_ms = remaining_ms % 1000 + 100;
1030 next_update_ms = remaining_ms % 60000 + 100;
1032 clock_timer = setTimeout(update_clock, next_update_ms);
1035 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1036 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1040 * @param {Number} remaining_ms
1041 * @param {boolean} show_seconds
1043 var format_clock = function(remaining_ms, show_seconds) {
1044 if (remaining_ms <= 0) {
1052 var remaining = Math.floor(remaining_ms / 1000);
1053 var seconds = remaining % 60;
1054 remaining = (remaining - seconds) / 60;
1055 var minutes = remaining % 60;
1056 remaining = (remaining - minutes) / 60;
1057 var hours = remaining;
1059 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1061 return format_2d(hours) + ":" + format_2d(minutes);
1068 var format_2d = function(x) {
1077 * @param {string} move
1078 * @param {Number} move_num
1079 * @param {boolean} white_to_play
1081 var format_move_with_number = function(move, move_num, white_to_play) {
1083 if (white_to_play) {
1084 ret = (move_num - 1) + '… ';
1086 ret = move_num + '. ';
1093 * @param {string} move
1094 * @param {Number} halfmove_num
1096 var format_halfmove_with_number = function(move, halfmove_num) {
1097 return format_move_with_number(
1099 Math.floor(halfmove_num / 2) + 1,
1100 halfmove_num % 2 == 0);
1104 * @param {Object} data
1105 * @param {Number} halfmove_num
1107 var format_tooltip = function(data, halfmove_num) {
1108 if (data['score_history'][halfmove_num] ||
1109 halfmove_num === data['position']['pretty_history'].length) {
1112 if (halfmove_num === data['position']['pretty_history'].length) {
1113 move = data['position']['last_move'];
1114 short_score = data['short_score'];
1116 move = data['position']['pretty_history'][halfmove_num];
1117 short_score = data['score_history'][halfmove_num][1];
1119 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1121 return "After " + move_with_number + ": " + short_score;
1123 for (var i = halfmove_num; i --> 0; ) {
1124 if (data['score_history'][i]) {
1125 var move = data['position']['pretty_history'][i];
1126 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1133 * @param {boolean} sort_by_score
1135 var resort_refutation_lines = function(sort_by_score) {
1136 sort_refutation_lines_by_score = sort_by_score;
1137 if (supports_html5_storage()) {
1138 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1140 update_refutation_lines();
1142 window['resort_refutation_lines'] = resort_refutation_lines;
1145 * @param {boolean} truncate_history
1147 var set_truncate_history = function(truncate_history) {
1148 truncate_display_history = truncate_history;
1149 update_refutation_lines();
1151 window['set_truncate_history'] = set_truncate_history;
1154 * @param {number} line_num
1155 * @param {number} move_num
1157 var show_line = function(line_num, move_num) {
1158 if (line_num == -1) {
1159 current_display_line = null;
1160 current_display_move = null;
1161 if (displayed_analysis_data) {
1162 // TODO: Support exiting to history position if we are in an
1163 // analysis line of a history position.
1164 displayed_analysis_data = null;
1165 update_board(current_analysis_data, displayed_analysis_data);
1168 current_display_line = display_lines[line_num];
1169 current_display_move = move_num;
1171 current_display_line_is_history = (line_num == 0);
1173 update_historic_analysis();
1174 update_displayed_line();
1178 window['show_line'] = show_line;
1180 var prev_move = function() {
1181 if (current_display_move > -1) {
1182 --current_display_move;
1184 update_historic_analysis();
1185 update_displayed_line();
1187 window['prev_move'] = prev_move;
1189 var next_move = function() {
1190 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1191 ++current_display_move;
1193 update_historic_analysis();
1194 update_displayed_line();
1196 window['next_move'] = next_move;
1198 var update_historic_analysis = function() {
1199 if (!current_display_line_is_history) {
1202 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1203 displayed_analysis_data = null;
1204 update_board(current_analysis_data, displayed_analysis_data);
1207 // Fetch old analysis for this line if it exists.
1208 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1209 var filename = "/history/move" + (current_display_move + 1) + "-" +
1210 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1214 }).done(function(data, textstatus, xhr) {
1215 displayed_analysis_data = data;
1216 update_board(current_analysis_data, displayed_analysis_data);
1217 }).fail(function() {
1218 displayed_analysis_data = {'failed': true};
1219 update_board(current_analysis_data, displayed_analysis_data);
1224 * @param {string} fen
1226 var update_imbalance = function(fen) {
1227 var hiddenboard = new Chess(fen);
1228 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1229 for (var row = 0; row < 8; ++row) {
1230 for (var col = 0; col < 8; ++col) {
1231 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1232 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1233 var square = col_text + row_text;
1234 var contents = hiddenboard.get(square);
1235 if (contents !== null) {
1236 if (contents.color === 'w') {
1237 ++imbalance[contents.type];
1239 --imbalance[contents.type];
1244 var white_imbalance = '';
1245 var black_imbalance = '';
1246 for (var piece in imbalance) {
1247 for (var i = 0; i < imbalance[piece]; ++i) {
1248 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1250 for (var i = 0; i < -imbalance[piece]; ++i) {
1251 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1254 $('#whiteimbalance').html(white_imbalance);
1255 $('#blackimbalance').html(black_imbalance);
1258 var update_displayed_line = function() {
1259 if (highlighted_move !== null) {
1260 highlighted_move.removeClass('highlight');
1262 if (current_display_line === null) {
1263 $("#linenav").hide();
1264 $("#linemsg").show();
1265 board.position(fen);
1266 update_imbalance(fen);
1270 $("#linenav").show();
1271 $("#linemsg").hide();
1273 if (current_display_move <= 0) {
1274 $("#prevmove").html("Previous");
1276 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1278 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1279 $("#nextmove").html("Next");
1281 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1284 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1285 highlighted_move.addClass('highlight');
1287 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1288 board.position(hiddenboard.fen());
1289 update_imbalance(hiddenboard.fen());
1293 * @param {boolean} param_enable_sound
1295 var set_sound = function(param_enable_sound) {
1296 enable_sound = param_enable_sound;
1298 $("#soundon").html("<strong>On</strong>");
1299 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1301 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1302 // and also preload the file since the user has selected audio.
1303 var ding = document.getElementById('ding');
1304 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1305 ding.src = 'ding.opus';
1309 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1310 $("#soundoff").html("<strong>Off</strong>");
1312 if (supports_html5_storage()) {
1313 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1316 window['set_sound'] = set_sound;
1318 var init = function() {
1319 unique = get_unique();
1321 // Load settings from HTML5 local storage if available.
1322 if (supports_html5_storage() && localStorage['enable_sound']) {
1323 set_sound(parseInt(localStorage['enable_sound']));
1327 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1328 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1330 sort_refutation_lines_by_score = true;
1334 board = new window.ChessBoard('board', 'start');
1337 $(window).resize(function() {
1339 update_sparkline(displayed_analysis_data || current_analysis_data);
1343 $(window).keyup(function(event) {
1344 if (event.which == 39) {
1346 } else if (event.which == 37) {
1351 $(document).ready(init);