3 /** @type {window.ChessBoard} @private */
7 * The most recent analysis data we have from the server
8 * (about the most recent position).
12 var current_analysis_data = null;
15 * If we are displaying previous analysis, this is non-null,
16 * and will override most of current_analysis_data.
21 var displayed_analysis_data = null;
36 /** @type {Array.<Array.<boolean>>} */
37 var occupied_by_arrows = [];
39 var refutation_lines = [];
41 /** @type {!number} @private */
44 /** @type {!string} @private */
47 /** @type {number} @private */
50 /** @type {boolean} @private */
51 var sort_refutation_lines_by_score = true;
53 /** @type {boolean} @private */
54 var truncate_display_history = true;
56 /** @type {!string|undefined} @private */
57 var highlight_from = undefined;
59 /** @type {!string|undefined} @private */
60 var highlight_to = undefined;
62 /** @type {?jQuery} @private */
63 var highlighted_move = null;
65 /** @type {?number} @private */
68 /** @type {boolean} @private */
69 var enable_sound = false;
72 * Our best estimate of how many milliseconds we need to add to
73 * new Date() to get the true UTC time. Calibrated against the
79 var client_clock_offset_ms = null;
81 var clock_timer = null;
83 /** The current position on the board, represented as a FEN string.
91 * uci_pv: Array.<string>,
92 * pretty_pv: Array.<string>,
97 /** @type {Array.<DisplayLine>}
100 var display_lines = [];
102 /** @type {?DisplayLine} @private */
103 var current_display_line = null;
105 /** @type {boolean} @private */
106 var current_display_line_is_history = false;
108 /** @type {?number} @private */
109 var current_display_move = null;
111 var supports_html5_storage = function() {
113 return 'localStorage' in window && window['localStorage'] !== null;
119 // Make the unique token persistent so people refreshing the page won't count twice.
120 // Of course, you can never fully protect against people deliberately wanting to spam.
121 var get_unique = function() {
122 var use_local_storage = supports_html5_storage();
123 if (use_local_storage && localStorage['unique']) {
124 return localStorage['unique'];
126 var unique = Math.random();
127 if (use_local_storage) {
128 localStorage['unique'] = unique;
133 var request_update = function() {
135 url: "/analysis.pl?ims=" + ims + "&unique=" + unique
136 }).done(function(data, textstatus, xhr) {
137 sync_server_clock(xhr.getResponseHeader('Date'));
138 ims = xhr.getResponseHeader('X-RGLM');
139 var num_viewers = xhr.getResponseHeader('X-RGNV');
140 possibly_play_sound(current_analysis_data, data);
141 if (Array.isArray(data)) {
142 current_analysis_data = JSON_delta.patch(current_analysis_data, data);
144 current_analysis_data = data;
146 update_board(current_analysis_data, displayed_analysis_data);
147 update_num_viewers(num_viewers);
150 setTimeout(function() { request_update(); }, 100);
152 // Wait ten seconds, then try again.
153 setTimeout(function() { request_update(); }, 10000);
157 var possibly_play_sound = function(old_data, new_data) {
161 if (old_data === null) {
164 var ding = document.getElementById('ding');
165 if (ding && ding.play) {
166 if (old_data['position'] && old_data['position']['fen'] &&
167 new_data['position'] && new_data['position']['fen'] &&
168 (old_data['position']['fen'] !== new_data['position']['fen'] ||
169 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
176 * @type {!string} server_date_string
178 var sync_server_clock = function(server_date_string) {
179 var server_time_ms = new Date(server_date_string).getTime();
180 var client_time_ms = new Date().getTime();
181 var estimated_offset_ms = server_time_ms - client_time_ms;
183 // In order not to let the noise move us too much back and forth
184 // (the server only has one-second resolution anyway), we only
185 // change an existing skew if we are at least five seconds off.
186 if (client_clock_offset_ms === null ||
187 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
188 client_clock_offset_ms = estimated_offset_ms;
192 var clear_arrows = function() {
193 for (var i = 0; i < arrows.length; ++i) {
195 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
196 delete arrows[i].svg;
201 occupied_by_arrows = [];
202 for (var y = 0; y < 8; ++y) {
203 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
207 var redraw_arrows = function() {
208 for (var i = 0; i < arrows.length; ++i) {
209 position_arrow(arrows[i]);
213 /** @param {!number} x
216 var sign = function(x) {
226 /** See if drawing this arrow on the board would cause unduly amount of confusion.
227 * @param {!string} from The square the arrow is from (e.g. e4).
228 * @param {!string} to The square the arrow is to (e.g. e4).
231 var interfering_arrow = function(from, to) {
232 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
233 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
234 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
235 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
237 occupied_by_arrows[from_row][from_col] = true;
239 // Knight move: Just check that we haven't been at the destination before.
240 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
241 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
242 return occupied_by_arrows[to_row][to_col];
245 // Sliding piece: Check if anything except the from-square is seen before.
246 var dx = sign(to_col - from_col);
247 var dy = sign(to_row - from_row);
253 if (occupied_by_arrows[y][x]) {
256 occupied_by_arrows[y][x] = true;
257 } while (x != to_col || y != to_row);
262 /** Find a point along the coordinate system given by the given line,
263 * <t> units forward from the start of the line, <u> units to the right of it.
264 * @param {!number} x1
265 * @param {!number} x2
266 * @param {!number} y1
267 * @param {!number} y2
270 * @return {!string} The point in "x y" form, suitable for SVG paths.
272 var point_from_start = function(x1, y1, x2, y2, t, u) {
276 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
280 var x = x1 + dx * t + dy * u;
281 var y = y1 + dy * t - dx * u;
285 /** Find a point along the coordinate system given by the given line,
286 * <t> units forward from the end of the line, <u> units to the right of it.
287 * @param {!number} x1
288 * @param {!number} x2
289 * @param {!number} y1
290 * @param {!number} y2
293 * @return {!string} The point in "x y" form, suitable for SVG paths.
295 var point_from_end = function(x1, y1, x2, y2, t, u) {
299 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
303 var x = x2 + dx * t + dy * u;
304 var y = y2 + dy * t - dx * u;
308 var position_arrow = function(arrow) {
310 arrow.svg.parentElement.removeChild(arrow.svg);
313 if (current_display_line !== null && !current_display_line_is_history) {
317 var pos = $(".square-a8").position();
319 var zoom_factor = $("#board").width() / 400.0;
320 var line_width = arrow.line_width * zoom_factor;
321 var arrow_size = arrow.arrow_size * zoom_factor;
323 var square_width = $(".square-a8").width();
324 var from_y = (7 - arrow.from_row + 0.5)*square_width;
325 var to_y = (7 - arrow.to_row + 0.5)*square_width;
326 var from_x = (arrow.from_col + 0.5)*square_width;
327 var to_x = (arrow.to_col + 0.5)*square_width;
329 var SVG_NS = "http://www.w3.org/2000/svg";
330 var XHTML_NS = "http://www.w3.org/1999/xhtml";
331 var svg = document.createElementNS(SVG_NS, "svg");
332 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
333 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
334 svg.setAttribute("style", "position: absolute");
335 svg.setAttribute("position", "absolute");
336 svg.setAttribute("version", "1.1");
337 svg.setAttribute("class", "c1");
338 svg.setAttribute("xmlns", XHTML_NS);
346 var outline = document.createElementNS(SVG_NS, "path");
347 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));
348 outline.setAttribute("xmlns", XHTML_NS);
349 outline.setAttribute("stroke", "#666");
350 outline.setAttribute("stroke-width", line_width + 2);
351 outline.setAttribute("fill", "none");
352 svg.appendChild(outline);
354 var path = document.createElementNS(SVG_NS, "path");
355 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));
356 path.setAttribute("xmlns", XHTML_NS);
357 path.setAttribute("stroke", arrow.fg_color);
358 path.setAttribute("stroke-width", line_width);
359 path.setAttribute("fill", "none");
360 svg.appendChild(path);
362 // Then the arrow head.
363 var head = document.createElementNS(SVG_NS, "path");
364 head.setAttribute("d",
365 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
366 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
367 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
368 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
369 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
370 head.setAttribute("xmlns", XHTML_NS);
371 head.setAttribute("stroke", "#000");
372 head.setAttribute("stroke-width", "1");
373 head.setAttribute("fill", arrow.fg_color);
374 svg.appendChild(head);
376 $(svg).css({ top: pos.top, left: pos.left });
377 document.body.appendChild(svg);
382 * @param {!string} from_square
383 * @param {!string} to_square
384 * @param {!string} fg_color
385 * @param {number} line_width
386 * @param {number} arrow_size
388 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
389 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
390 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
391 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
392 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
400 line_width: line_width,
401 arrow_size: arrow_size,
405 position_arrow(arrow);
409 var compare_by_sort_key = function(refutation_lines, a, b) {
410 var ska = refutation_lines[a]['sort_key'];
411 var skb = refutation_lines[b]['sort_key'];
412 if (ska < skb) return -1;
413 if (ska > skb) return 1;
417 var compare_by_score = function(refutation_lines, a, b) {
418 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
419 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
424 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
425 * sorted by quality, descending.
427 * @param {!Object} data
428 * @param {number} margin The maximum number of centipawns worse than the
429 * best move can be and still be included.
430 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
431 * moves, in score order.
433 var find_nonstupid_moves = function(data, margin) {
434 // First of all, if there are any moves that are more than 0.5 ahead of
435 // the primary move, the refutation lines are probably bunk, so just
437 var best_score = undefined;
438 var pv_score = undefined;
439 for (var move in data['refutation_lines']) {
440 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
441 if (move == data['pv_uci'][0]) {
444 if (best_score === undefined || score > best_score) {
447 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
452 if (best_score - pv_score > 50) {
456 // Now find all moves that are within “margin” of the best score.
457 // The PV move will always be first.
459 for (var move in data['refutation_lines']) {
460 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
461 if (move != data['pv_uci'][0] && best_score - score <= margin) {
465 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
466 moves.unshift(data['pv_uci'][0]);
475 var thousands = function(x) {
476 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
480 * @param {!string} fen
481 * @param {Array.<string>} pretty_pv
482 * @param {number} move_num
483 * @param {!string} toplay
484 * @param {number=} opt_limit
485 * @param {boolean=} opt_showlast
487 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
490 pretty_pv: pretty_pv,
491 line_number: display_lines.length
493 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
497 * @param {number} line_num
498 * @param {Array.<string>} pretty_pv
499 * @param {number} move_num
500 * @param {!string} toplay
501 * @param {number=} opt_limit
502 * @param {boolean=} opt_showlast
504 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
507 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
508 // Truncate the PV at the beginning (instead of at the end).
509 // We assume here that toplay is 'W'. We also assume that if
510 // opt_showlast is set, then it is the history, and thus,
511 // the UI should be to expand the history.
512 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
513 i = pretty_pv.length - opt_limit;
518 } else if (toplay == 'B' && pretty_pv.length > 0) {
519 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
520 pv = move_num + '. … ' + move;
525 for ( ; i < pretty_pv.length; ++i) {
526 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
529 if (i > opt_limit && !opt_showlast) {
535 pv += move_num + '. ' + move;
546 var update_highlight = function() {
547 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
548 if ((current_display_line === null || current_display_line_is_history) &&
549 highlight_from !== undefined && highlight_to !== undefined) {
550 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
551 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
555 var update_history = function() {
556 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
557 $("#history").html("No history");
558 } else if (truncate_display_history) {
559 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
562 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
563 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
568 * @param {!boolean} truncate_history
570 var collapse_history = function(truncate_history) {
571 truncate_display_history = truncate_history;
574 window['collapse_history'] = collapse_history;
576 var update_refutation_lines = function() {
580 if (display_lines.length > 2) {
581 display_lines = [ display_lines[0], display_lines[1] ];
584 var tbl = $("#refutationlines");
588 for (var move in refutation_lines) {
591 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
592 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
593 for (var i = 0; i < moves.length; ++i) {
594 var line = refutation_lines[moves[i]];
596 var tr = document.createElement("tr");
598 var move_td = document.createElement("td");
599 tr.appendChild(move_td);
600 $(move_td).addClass("move");
601 if (line['pv_pretty'].length == 0) {
602 $(move_td).text(line['pretty_move']);
604 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
605 $(move_td).html(move);
608 var score_td = document.createElement("td");
609 tr.appendChild(score_td);
610 $(score_td).addClass("score");
611 $(score_td).text(line['pretty_score']);
613 var depth_td = document.createElement("td");
614 tr.appendChild(depth_td);
615 $(depth_td).addClass("depth");
616 $(depth_td).text("d" + line['depth']);
618 var pv_td = document.createElement("td");
619 tr.appendChild(pv_td);
620 $(pv_td).addClass("pv");
621 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
626 // Make one of the links clickable and the other nonclickable.
627 if (sort_refutation_lines_by_score) {
628 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
629 $("#sortbyscore1").html("<strong>Score</strong>");
631 $("#sortbyscore0").html("<strong>Move</strong>");
632 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
637 * @param {?string} fen
638 * @param {Array.<string>} moves
639 * @param {number} last_move
641 var chess_from = function(fen, moves, last_move) {
642 var hiddenboard = new Chess();
644 hiddenboard.load(fen);
646 for (var i = 0; i <= last_move; ++i) {
647 if (moves[i] === '0-0') {
648 hiddenboard.move('O-O');
649 } else if (moves[i] === '0-0-0') {
650 hiddenboard.move('O-O-O');
652 hiddenboard.move(moves[i]);
659 * @param {Object} data
660 * @param {?Object} display_data
662 var update_board = function(current_data, display_data) {
663 var data = display_data || current_data;
667 // Print the history. This is pretty much the only thing that's
668 // unconditionally taken from current_data (we're not interested in
669 // historic history).
670 if (current_data['position']['pretty_history']) {
671 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
673 display_lines.push(null);
677 // The headline. Names are always fetched from current_data;
678 // the rest can depend a bit.
681 current_data['position']['player_w'] && current_data['position']['player_b']) {
682 headline = current_data['position']['player_w'] + '–' +
683 current_data['position']['player_b'] + ', analysis';
685 headline = 'Analysis';
690 // Displaying some non-current position, pick out the last move
691 // from the history. This will work even if the fetch failed.
692 last_move = format_move_with_number(
693 current_display_line.pretty_pv[current_display_move],
694 Math.floor((current_display_move + 1) / 2) + 1,
695 (current_display_move % 2 == 1));
696 headline += ' after ' + last_move;
697 } else if (data['position']['last_move'] !== 'none') {
698 last_move = format_move_with_number(
699 data['position']['last_move'],
700 data['position']['move_num'],
701 data['position']['toplay'] == 'W');
702 headline += ' after ' + last_move;
706 $("#headline").text(headline);
708 // The <title> contains a very brief headline.
709 var title_elems = [];
710 if (data['short_score'] !== undefined && data['short_score'] !== null) {
711 title_elems.push(data['short_score'].replace(/^ /, ""));
713 if (last_move !== null) {
714 title_elems.push(last_move);
717 if (title_elems.length != 0) {
718 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
720 document.title = 'analysis.sesse.net';
723 // The last move (shown by highlighting the from and to squares).
724 if (data['position'] && data['position']['last_move_uci']) {
725 highlight_from = data['position']['last_move_uci'].substr(0, 2);
726 highlight_to = data['position']['last_move_uci'].substr(2, 2);
727 } else if (current_display_line_is_history && current_display_move >= 0) {
728 // We don't have historic analysis for this position, but we
729 // can reconstruct what the last move was by just replaying
731 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
732 var moves = hiddenboard.history({ verbose: true });
733 var last_move = moves.pop();
734 highlight_from = last_move.from;
735 highlight_to = last_move.to;
737 highlight_from = highlight_to = undefined;
741 if (data['failed']) {
742 $("#score").text("No analysis for this move");
744 $("#searchstats").html(" ");
745 $("#refutationlines").empty();
746 $("#whiteclock").empty();
747 $("#blackclock").empty();
748 refutation_lines = [];
749 update_refutation_lines();
751 update_displayed_line();
758 if (data['id'] && data['id']['name'] !== null) {
759 $("#engineid").text(data['id']['name']);
763 if (data['score'] !== null) {
764 $("#score").text(data['score']);
768 if (data['tablebase'] == 1) {
769 $("#searchstats").text("Tablebase result");
770 } else if (data['nodes'] && data['nps'] && data['depth']) {
771 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
772 if (data['seldepth']) {
773 stats += ' (' + data['seldepth'] + ' selective)';
775 if (data['tbhits'] && data['tbhits'] > 0) {
776 if (data['tbhits'] == 1) {
777 stats += ', one Syzygy hit';
779 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
783 $("#searchstats").text(stats);
785 $("#searchstats").text("");
788 // Update the board itself.
789 fen = data['position']['fen'];
790 update_displayed_line();
793 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
795 // Update the PV arrow.
797 if (data['pv_uci'].length >= 1) {
798 // draw a continuation arrow as long as it's the same piece
799 for (var i = 0; i < data['pv_uci'].length; i += 2) {
800 var from = data['pv_uci'][i].substr(0, 2);
801 var to = data['pv_uci'][i].substr(2,4);
802 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
803 interfering_arrow(from, to)) {
806 create_arrow(from, to, '#f66', 6, 20);
809 var alt_moves = find_nonstupid_moves(data, 30);
810 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
811 create_arrow(alt_moves[i].substr(0, 2),
812 alt_moves[i].substr(2, 2), '#f66', 1, 10);
816 // See if all semi-reasonable moves have only one possible response.
817 if (data['pv_uci'].length >= 2) {
818 var nonstupid_moves = find_nonstupid_moves(data, 300);
819 var response = data['pv_uci'][1];
820 for (var i = 0; i < nonstupid_moves.length; ++i) {
821 if (nonstupid_moves[i] == data['pv_uci'][0]) {
822 // ignore the PV move for refutation lines.
825 if (!data['refutation_lines'] ||
826 !data['refutation_lines'][nonstupid_moves[i]] ||
827 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
828 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
829 // Incomplete PV, abort.
830 response = undefined;
833 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
834 if (response !== this_response) {
835 // Different response depending on lines, abort.
836 response = undefined;
841 if (nonstupid_moves.length > 0 && response !== undefined) {
842 create_arrow(response.substr(0, 2),
843 response.substr(2, 2), '#66f', 6, 20);
847 // Update the refutation lines.
848 fen = data['position']['fen'];
849 move_num = data['position']['move_num'];
850 toplay = data['position']['toplay'];
851 refutation_lines = data['refutation_lines'];
852 update_refutation_lines();
856 * @param {number} num_viewers
858 var update_num_viewers = function(num_viewers) {
859 if (num_viewers === null) {
860 $("#numviewers").text("");
861 } else if (num_viewers == 1) {
862 $("#numviewers").text("You are the only current viewer");
864 $("#numviewers").text(num_viewers + " current viewers");
868 var update_clock = function() {
869 clearTimeout(clock_timer);
871 var data = displayed_analysis_data || current_analysis_data;
872 if (data['position']) {
873 var result = data['position']['result'];
874 if (result === '1-0') {
875 $("#whiteclock").text("1");
876 $("#blackclock").text("0");
877 $("#whiteclock").removeClass("running-clock");
878 $("#blackclock").removeClass("running-clock");
881 if (result === '1/2-1/2') {
882 $("#whiteclock").text("1/2");
883 $("#blackclock").text("1/2");
884 $("#whiteclock").removeClass("running-clock");
885 $("#blackclock").removeClass("running-clock");
888 if (result === '0-1') {
889 $("#whiteclock").text("0");
890 $("#blackclock").text("1");
891 $("#whiteclock").removeClass("running-clock");
892 $("#blackclock").removeClass("running-clock");
897 var white_clock_ms = null;
898 var black_clock_ms = null;
899 var show_seconds = false;
902 if (data['position'] &&
903 data['position']['white_clock'] &&
904 data['position']['black_clock']) {
905 white_clock_ms = data['position']['white_clock'] * 1000;
906 black_clock_ms = data['position']['black_clock'] * 1000;
909 // Dynamic clock (only one, obviously).
911 if (data['position']['white_clock_target']) {
913 $("#whiteclock").addClass("running-clock");
914 $("#blackclock").removeClass("running-clock");
915 } else if (data['position']['black_clock_target']) {
917 $("#whiteclock").removeClass("running-clock");
918 $("#blackclock").addClass("running-clock");
920 $("#whiteclock").removeClass("running-clock");
921 $("#blackclock").removeClass("running-clock");
925 var now = new Date().getTime() + client_clock_offset_ms;
926 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
927 if (color === "white") {
928 white_clock_ms = remaining_ms;
930 black_clock_ms = remaining_ms;
934 if (white_clock_ms === null || black_clock_ms === null) {
935 $("#whiteclock").empty();
936 $("#blackclock").empty();
940 // If either player has ten minutes or less left, add the second counters.
941 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
944 // See when the clock will change next, and update right after that.
947 next_update_ms = remaining_ms % 1000 + 100;
949 next_update_ms = remaining_ms % 60000 + 100;
951 clock_timer = setTimeout(update_clock, next_update_ms);
954 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
955 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
959 * @param {Number} remaining_ms
960 * @param {boolean} show_seconds
962 var format_clock = function(remaining_ms, show_seconds) {
963 if (remaining_ms <= 0) {
971 var remaining = Math.floor(remaining_ms / 1000);
972 var seconds = remaining % 60;
973 remaining = (remaining - seconds) / 60;
974 var minutes = remaining % 60;
975 remaining = (remaining - minutes) / 60;
976 var hours = remaining;
978 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
980 return format_2d(hours) + ":" + format_2d(minutes);
987 var format_2d = function(x) {
996 * @param {string} move
997 * @param {Number} move_num
998 * @param {boolean} white_to_play
1000 var format_move_with_number = function(move, move_num, white_to_play) {
1002 if (white_to_play) {
1003 ret = (move_num - 1) + '… ';
1005 ret = move_num + '. ';
1012 * @param {boolean} sort_by_score
1014 var resort_refutation_lines = function(sort_by_score) {
1015 sort_refutation_lines_by_score = sort_by_score;
1016 if (supports_html5_storage()) {
1017 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1019 update_refutation_lines();
1021 window['resort_refutation_lines'] = resort_refutation_lines;
1024 * @param {boolean} truncate_history
1026 var set_truncate_history = function(truncate_history) {
1027 truncate_display_history = truncate_history;
1028 update_refutation_lines();
1030 window['set_truncate_history'] = set_truncate_history;
1033 * @param {number} line_num
1034 * @param {number} move_num
1036 var show_line = function(line_num, move_num) {
1037 if (line_num == -1) {
1038 current_display_line = null;
1039 current_display_move = null;
1040 if (displayed_analysis_data) {
1041 // TODO: Support exiting to history position if we are in an
1042 // analysis line of a history position.
1043 displayed_analysis_data = null;
1044 update_board(current_analysis_data, displayed_analysis_data);
1047 current_display_line = display_lines[line_num];
1048 current_display_move = move_num;
1050 current_display_line_is_history = (line_num == 0);
1052 update_historic_analysis();
1053 update_displayed_line();
1057 window['show_line'] = show_line;
1059 var prev_move = function() {
1060 if (current_display_move > -1) {
1061 --current_display_move;
1063 update_historic_analysis();
1064 update_displayed_line();
1066 window['prev_move'] = prev_move;
1068 var next_move = function() {
1069 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1070 ++current_display_move;
1072 update_historic_analysis();
1073 update_displayed_line();
1075 window['next_move'] = next_move;
1077 var update_historic_analysis = function() {
1078 if (!current_display_line_is_history) {
1081 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1082 displayed_analysis_data = null;
1083 update_board(current_analysis_data, displayed_analysis_data);
1086 // Fetch old analysis for this line if it exists.
1087 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1088 var filename = "/history/move" + (current_display_move + 1) + "-" +
1089 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1093 }).done(function(data, textstatus, xhr) {
1094 displayed_analysis_data = data;
1095 update_board(current_analysis_data, displayed_analysis_data);
1096 }).fail(function() {
1097 displayed_analysis_data = {'failed': true};
1098 update_board(current_analysis_data, displayed_analysis_data);
1102 var update_displayed_line = function() {
1103 if (highlighted_move !== null) {
1104 highlighted_move.removeClass('highlight');
1106 if (current_display_line === null) {
1107 $("#linenav").hide();
1108 $("#linemsg").show();
1109 board.position(fen);
1113 $("#linenav").show();
1114 $("#linemsg").hide();
1116 if (current_display_move <= 0) {
1117 $("#prevmove").html("Previous");
1119 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1121 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1122 $("#nextmove").html("Next");
1124 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1127 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1128 highlighted_move.addClass('highlight');
1130 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1131 board.position(hiddenboard.fen());
1135 * @param {boolean} param_enable_sound
1137 var set_sound = function(param_enable_sound) {
1138 enable_sound = param_enable_sound;
1140 $("#soundon").html("<strong>On</strong>");
1141 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1143 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1144 // and also preload the file since the user has selected audio.
1145 var ding = document.getElementById('ding');
1146 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1147 ding.src = 'ding.opus';
1151 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1152 $("#soundoff").html("<strong>Off</strong>");
1154 if (supports_html5_storage()) {
1155 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1158 window['set_sound'] = set_sound;
1160 var init = function() {
1161 unique = get_unique();
1163 // Load settings from HTML5 local storage if available.
1164 if (supports_html5_storage() && localStorage['enable_sound']) {
1165 set_sound(parseInt(localStorage['enable_sound']));
1169 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1170 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1172 sort_refutation_lines_by_score = true;
1176 board = new window.ChessBoard('board', 'start');
1179 $(window).resize(function() {
1184 $(window).keyup(function(event) {
1185 if (event.which == 39) {
1187 } else if (event.which == 37) {
1192 $(document).ready(init);