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-Remoteglot-Last-Modified');
139 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
140 possibly_play_sound(current_analysis_data, data);
141 current_analysis_data = data;
142 update_board(current_analysis_data, displayed_analysis_data);
143 update_num_viewers(num_viewers);
146 setTimeout(function() { request_update(); }, 100);
148 // Wait ten seconds, then try again.
149 setTimeout(function() { request_update(); }, 10000);
153 var possibly_play_sound = function(old_data, new_data) {
157 if (old_data === null) {
160 var ding = document.getElementById('ding');
161 if (ding && ding.play) {
162 if (old_data['position'] && old_data['position']['fen'] &&
163 new_data['position'] && new_data['position']['fen'] &&
164 (old_data['position']['fen'] !== new_data['position']['fen'] ||
165 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
172 * @type {!string} server_date_string
174 var sync_server_clock = function(server_date_string) {
175 var server_time_ms = new Date(server_date_string).getTime();
176 var client_time_ms = new Date().getTime();
177 var estimated_offset_ms = server_time_ms - client_time_ms;
179 // In order not to let the noise move us too much back and forth
180 // (the server only has one-second resolution anyway), we only
181 // change an existing skew if we are at least five seconds off.
182 if (client_clock_offset_ms === null ||
183 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
184 client_clock_offset_ms = estimated_offset_ms;
188 var clear_arrows = function() {
189 for (var i = 0; i < arrows.length; ++i) {
191 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
192 delete arrows[i].svg;
197 occupied_by_arrows = [];
198 for (var y = 0; y < 8; ++y) {
199 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
203 var redraw_arrows = function() {
204 for (var i = 0; i < arrows.length; ++i) {
205 position_arrow(arrows[i]);
209 /** @param {!number} x
212 var sign = function(x) {
222 /** See if drawing this arrow on the board would cause unduly amount of confusion.
223 * @param {!string} from The square the arrow is from (e.g. e4).
224 * @param {!string} to The square the arrow is to (e.g. e4).
227 var interfering_arrow = function(from, to) {
228 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
229 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
230 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
231 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
233 occupied_by_arrows[from_row][from_col] = true;
235 // Knight move: Just check that we haven't been at the destination before.
236 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
237 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
238 return occupied_by_arrows[to_row][to_col];
241 // Sliding piece: Check if anything except the from-square is seen before.
242 var dx = sign(to_col - from_col);
243 var dy = sign(to_row - from_row);
249 if (occupied_by_arrows[y][x]) {
252 occupied_by_arrows[y][x] = true;
253 } while (x != to_col || y != to_row);
258 /** Find a point along the coordinate system given by the given line,
259 * <t> units forward from the start of the line, <u> units to the right of it.
260 * @param {!number} x1
261 * @param {!number} x2
262 * @param {!number} y1
263 * @param {!number} y2
266 * @return {!string} The point in "x y" form, suitable for SVG paths.
268 var point_from_start = function(x1, y1, x2, y2, t, u) {
272 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
276 var x = x1 + dx * t + dy * u;
277 var y = y1 + dy * t - dx * u;
281 /** Find a point along the coordinate system given by the given line,
282 * <t> units forward from the end 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_end = function(x1, y1, x2, y2, t, u) {
295 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
299 var x = x2 + dx * t + dy * u;
300 var y = y2 + dy * t - dx * u;
304 var position_arrow = function(arrow) {
306 arrow.svg.parentElement.removeChild(arrow.svg);
309 if (current_display_line !== null && !current_display_line_is_history) {
313 var pos = $(".square-a8").position();
315 var zoom_factor = $("#board").width() / 400.0;
316 var line_width = arrow.line_width * zoom_factor;
317 var arrow_size = arrow.arrow_size * zoom_factor;
319 var square_width = $(".square-a8").width();
320 var from_y = (7 - arrow.from_row + 0.5)*square_width;
321 var to_y = (7 - arrow.to_row + 0.5)*square_width;
322 var from_x = (arrow.from_col + 0.5)*square_width;
323 var to_x = (arrow.to_col + 0.5)*square_width;
325 var SVG_NS = "http://www.w3.org/2000/svg";
326 var XHTML_NS = "http://www.w3.org/1999/xhtml";
327 var svg = document.createElementNS(SVG_NS, "svg");
328 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
329 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
330 svg.setAttribute("style", "position: absolute");
331 svg.setAttribute("position", "absolute");
332 svg.setAttribute("version", "1.1");
333 svg.setAttribute("class", "c1");
334 svg.setAttribute("xmlns", XHTML_NS);
342 var outline = document.createElementNS(SVG_NS, "path");
343 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));
344 outline.setAttribute("xmlns", XHTML_NS);
345 outline.setAttribute("stroke", "#666");
346 outline.setAttribute("stroke-width", line_width + 2);
347 outline.setAttribute("fill", "none");
348 svg.appendChild(outline);
350 var path = document.createElementNS(SVG_NS, "path");
351 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));
352 path.setAttribute("xmlns", XHTML_NS);
353 path.setAttribute("stroke", arrow.fg_color);
354 path.setAttribute("stroke-width", line_width);
355 path.setAttribute("fill", "none");
356 svg.appendChild(path);
358 // Then the arrow head.
359 var head = document.createElementNS(SVG_NS, "path");
360 head.setAttribute("d",
361 "M " + point_from_end(x1, y1, x2, y2, 0, 0) +
362 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
363 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
364 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
365 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
366 head.setAttribute("xmlns", XHTML_NS);
367 head.setAttribute("stroke", "#000");
368 head.setAttribute("stroke-width", "1");
369 head.setAttribute("fill", arrow.fg_color);
370 svg.appendChild(head);
372 $(svg).css({ top: pos.top, left: pos.left });
373 document.body.appendChild(svg);
378 * @param {!string} from_square
379 * @param {!string} to_square
380 * @param {!string} fg_color
381 * @param {number} line_width
382 * @param {number} arrow_size
384 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
385 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
386 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
387 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
388 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
396 line_width: line_width,
397 arrow_size: arrow_size,
401 position_arrow(arrow);
405 var compare_by_sort_key = function(refutation_lines, a, b) {
406 var ska = refutation_lines[a]['sort_key'];
407 var skb = refutation_lines[b]['sort_key'];
408 if (ska < skb) return -1;
409 if (ska > skb) return 1;
413 var compare_by_score = function(refutation_lines, a, b) {
414 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
415 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
420 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
421 * sorted by quality, descending.
423 * @param {!Object} data
424 * @param {number} margin The maximum number of centipawns worse than the
425 * best move can be and still be included.
426 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
427 * moves, in score order.
429 var find_nonstupid_moves = function(data, margin) {
430 // First of all, if there are any moves that are more than 0.5 ahead of
431 // the primary move, the refutation lines are probably bunk, so just
433 var best_score = undefined;
434 var pv_score = undefined;
435 for (var move in data['refutation_lines']) {
436 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
437 if (move == data['pv_uci'][0]) {
440 if (best_score === undefined || score > best_score) {
443 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
448 if (best_score - pv_score > 50) {
452 // Now find all moves that are within “margin” of the best score.
453 // The PV move will always be first.
455 for (var move in data['refutation_lines']) {
456 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
457 if (move != data['pv_uci'][0] && best_score - score <= margin) {
461 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
462 moves.unshift(data['pv_uci'][0]);
471 var thousands = function(x) {
472 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
476 * @param {!string} fen
477 * @param {Array.<string>} pretty_pv
478 * @param {number} move_num
479 * @param {!string} toplay
480 * @param {number=} opt_limit
481 * @param {boolean=} opt_showlast
483 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
486 pretty_pv: pretty_pv,
487 line_number: display_lines.length
489 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
493 * @param {number} line_num
494 * @param {Array.<string>} pretty_pv
495 * @param {number} move_num
496 * @param {!string} toplay
497 * @param {number=} opt_limit
498 * @param {boolean=} opt_showlast
500 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
503 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
504 // Truncate the PV at the beginning (instead of at the end).
505 // We assume here that toplay is 'W'. We also assume that if
506 // opt_showlast is set, then it is the history, and thus,
507 // the UI should be to expand the history.
508 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
509 i = pretty_pv.length - opt_limit;
514 } else if (toplay == 'B' && pretty_pv.length > 0) {
515 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
516 pv = move_num + '. … ' + move;
521 for ( ; i < pretty_pv.length; ++i) {
522 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
525 if (i > opt_limit && !opt_showlast) {
531 pv += move_num + '. ' + move;
542 var update_highlight = function() {
543 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
544 if ((current_display_line === null || current_display_line_is_history) &&
545 highlight_from !== undefined && highlight_to !== undefined) {
546 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
547 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
551 var update_history = function() {
552 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
553 $("#history").html("No history");
554 } else if (truncate_display_history) {
555 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
558 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
559 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
564 * @param {!boolean} truncate_history
566 var collapse_history = function(truncate_history) {
567 truncate_display_history = truncate_history;
570 window['collapse_history'] = collapse_history;
572 var update_refutation_lines = function() {
576 if (display_lines.length > 2) {
577 display_lines = [ display_lines[0], display_lines[1] ];
580 var tbl = $("#refutationlines");
584 for (var move in refutation_lines) {
587 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
588 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
589 for (var i = 0; i < moves.length; ++i) {
590 var line = refutation_lines[moves[i]];
592 var tr = document.createElement("tr");
594 var move_td = document.createElement("td");
595 tr.appendChild(move_td);
596 $(move_td).addClass("move");
597 if (line['pv_pretty'].length == 0) {
598 $(move_td).text(line['pretty_move']);
600 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
601 $(move_td).html(move);
604 var score_td = document.createElement("td");
605 tr.appendChild(score_td);
606 $(score_td).addClass("score");
607 $(score_td).text(line['pretty_score']);
609 var depth_td = document.createElement("td");
610 tr.appendChild(depth_td);
611 $(depth_td).addClass("depth");
612 $(depth_td).text("d" + line['depth']);
614 var pv_td = document.createElement("td");
615 tr.appendChild(pv_td);
616 $(pv_td).addClass("pv");
617 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
622 // Make one of the links clickable and the other nonclickable.
623 if (sort_refutation_lines_by_score) {
624 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
625 $("#sortbyscore1").html("<strong>Score</strong>");
627 $("#sortbyscore0").html("<strong>Move</strong>");
628 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
633 * @param {Object} data
634 * @param {?Object} display_data
636 var update_board = function(current_data, display_data) {
637 var data = display_data || current_data;
641 // Print the history. This is pretty much the only thing that's
642 // unconditionally taken from current_data (we're not interested in
643 // historic history).
644 if (current_data['position']['pretty_history']) {
645 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
647 display_lines.push(null);
651 // The headline. Names are always fetched from current_data;
652 // the rest can depend a bit.
655 current_data['position']['player_w'] && current_data['position']['player_b']) {
656 headline = current_data['position']['player_w'] + '–' +
657 current_data['position']['player_b'] + ', analysis';
659 headline = 'Analysis';
664 // Displaying some non-current position, pick out the last move
665 // from the history. This will work even if the fetch failed.
666 last_move = format_move_with_number(
667 current_display_line.pretty_pv[current_display_move],
668 Math.floor((current_display_move + 1) / 2) + 1,
669 (current_display_move % 2 == 1));
670 headline += ' after ' + last_move;
671 } else if (data['position']['last_move'] !== 'none') {
672 last_move = format_move_with_number(
673 data['position']['last_move'],
674 data['position']['move_num'],
675 data['position']['toplay'] == 'W');
676 headline += ' after ' + last_move;
680 $("#headline").text(headline);
682 // The <title> contains a very brief headline.
683 var title_elems = [];
684 if (data['short_score'] !== undefined && data['short_score'] !== null) {
685 title_elems.push(data['short_score'].replace(/^ /, ""));
687 if (last_move !== null) {
688 title_elems.push(last_move);
691 if (title_elems.length != 0) {
692 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
694 document.title = 'analysis.sesse.net';
697 // The last move (shown by highlighting the from and to squares).
698 if (data['position'] && data['position']['last_move_uci']) {
699 highlight_from = data['position']['last_move_uci'].substr(0, 2);
700 highlight_to = data['position']['last_move_uci'].substr(2, 2);
701 } else if (current_display_line_is_history && current_display_move >= 0) {
702 // We don't have historic analysis for this position, but we
703 // can reconstruct what the last move was by just replaying
705 var hiddenboard = new Chess();
706 for (var i = 0; i <= current_display_move; ++i) {
707 hiddenboard.move(current_display_line.pretty_pv[i]);
709 var moves = hiddenboard.history({ verbose: true });
710 var last_move = moves.pop();
711 highlight_from = last_move.from;
712 highlight_to = last_move.to;
714 highlight_from = highlight_to = undefined;
718 if (data['failed']) {
719 $("#score").text("No analysis for this move");
721 $("#searchstats").html(" ");
722 $("#refutationlines").empty();
723 $("#whiteclock").empty();
724 $("#blackclock").empty();
725 refutation_lines = [];
726 update_refutation_lines();
728 update_displayed_line();
735 if (data['id'] && data['id']['name'] !== null) {
736 $("#engineid").text(data['id']['name']);
740 if (data['score'] !== null) {
741 $("#score").text(data['score']);
745 if (data['tablebase'] == 1) {
746 $("#searchstats").text("Tablebase result");
747 } else if (data['nodes'] && data['nps'] && data['depth']) {
748 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
749 if (data['seldepth']) {
750 stats += ' (' + data['seldepth'] + ' selective)';
752 if (data['tbhits'] && data['tbhits'] > 0) {
753 if (data['tbhits'] == 1) {
754 stats += ', one Syzygy hit';
756 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
760 $("#searchstats").text(stats);
762 $("#searchstats").text("");
765 // Update the board itself.
766 fen = data['position']['fen'];
767 update_displayed_line();
770 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
772 // Update the PV arrow.
774 if (data['pv_uci'].length >= 1) {
775 // draw a continuation arrow as long as it's the same piece
776 for (var i = 0; i < data['pv_uci'].length; i += 2) {
777 var from = data['pv_uci'][i].substr(0, 2);
778 var to = data['pv_uci'][i].substr(2,4);
779 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
780 interfering_arrow(from, to)) {
783 create_arrow(from, to, '#f66', 6, 20);
786 var alt_moves = find_nonstupid_moves(data, 30);
787 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
788 create_arrow(alt_moves[i].substr(0, 2),
789 alt_moves[i].substr(2, 2), '#f66', 1, 10);
793 // See if all semi-reasonable moves have only one possible response.
794 if (data['pv_uci'].length >= 2) {
795 var nonstupid_moves = find_nonstupid_moves(data, 300);
796 var response = data['pv_uci'][1];
797 for (var i = 0; i < nonstupid_moves.length; ++i) {
798 if (nonstupid_moves[i] == data['pv_uci'][0]) {
799 // ignore the PV move for refutation lines.
802 if (!data['refutation_lines'] ||
803 !data['refutation_lines'][nonstupid_moves[i]] ||
804 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
805 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
806 // Incomplete PV, abort.
807 response = undefined;
810 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
811 if (response !== this_response) {
812 // Different response depending on lines, abort.
813 response = undefined;
818 if (nonstupid_moves.length > 0 && response !== undefined) {
819 create_arrow(response.substr(0, 2),
820 response.substr(2, 2), '#66f', 6, 20);
824 // Update the refutation lines.
825 fen = data['position']['fen'];
826 move_num = data['position']['move_num'];
827 toplay = data['position']['toplay'];
828 refutation_lines = data['refutation_lines'];
829 update_refutation_lines();
833 * @param {number} num_viewers
835 var update_num_viewers = function(num_viewers) {
836 if (num_viewers === null) {
837 $("#numviewers").text("");
838 } else if (num_viewers == 1) {
839 $("#numviewers").text("You are the only current viewer");
841 $("#numviewers").text(num_viewers + " current viewers");
845 var update_clock = function() {
846 clearTimeout(clock_timer);
848 var data = displayed_analysis_data || current_analysis_data;
849 if (data['position']) {
850 var result = data['position']['result'];
851 if (result === '1-0') {
852 $("#whiteclock").text("1");
853 $("#blackclock").text("0");
854 $("#whiteclock").removeClass("running-clock");
855 $("#blackclock").removeClass("running-clock");
858 if (result === '1/2-1/2') {
859 $("#whiteclock").text("1/2");
860 $("#blackclock").text("1/2");
861 $("#whiteclock").removeClass("running-clock");
862 $("#blackclock").removeClass("running-clock");
865 if (result === '0-1') {
866 $("#whiteclock").text("0");
867 $("#blackclock").text("1");
868 $("#whiteclock").removeClass("running-clock");
869 $("#blackclock").removeClass("running-clock");
874 var white_clock = "";
875 var black_clock = "";
878 if (data['position'] &&
879 data['position']['white_clock'] &&
880 data['position']['black_clock']) {
881 white_clock = data['position']['white_clock'].replace(/:[0-5][0-9]$/, "");
882 black_clock = data['position']['black_clock'].replace(/:[0-5][0-9]$/, "");
885 // Dynamic clock (only one, obviously).
887 if (data['position']['white_clock_target']) {
889 } else if (data['position']['black_clock_target']) {
893 var now = new Date().getTime() + client_clock_offset_ms;
894 var remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
895 if (color === "white") {
896 white_clock = format_clock(remaining_ms);
898 black_clock = format_clock(remaining_ms);
901 // See when the clock will change next, and update right after that.
902 var next_update_ms = remaining_ms % 60000 + 100;
903 clock_timer = setTimeout(update_clock, next_update_ms);
906 $("#whiteclock").text(white_clock);
907 $("#blackclock").text(black_clock);
910 $("#whiteclock").addClass("running-clock");
911 $("#blackclock").removeClass("running-clock");
913 $("#whiteclock").removeClass("running-clock");
914 $("#blackclock").addClass("running-clock");
919 * @param {Number} remaining_ms
921 var format_clock = function(remaining_ms) {
922 if (remaining_ms <= 0) {
926 var remaining = Math.floor(remaining_ms / 1000);
927 var seconds = remaining % 60;
928 remaining = (remaining - seconds) / 60;
929 var minutes = remaining % 60;
930 remaining = (remaining - minutes) / 60;
931 var hours = remaining;
932 return format_2d(hours) + ":" + format_2d(minutes);
938 var format_2d = function(x) {
947 * @param {string} move
948 * @param {Number} move_num
949 * @param {boolean} white_to_play
951 var format_move_with_number = function(move, move_num, white_to_play) {
954 ret = (move_num - 1) + '… ';
956 ret = move_num + '. ';
963 * @param {boolean} sort_by_score
965 var resort_refutation_lines = function(sort_by_score) {
966 sort_refutation_lines_by_score = sort_by_score;
967 if (supports_html5_storage()) {
968 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
970 update_refutation_lines();
972 window['resort_refutation_lines'] = resort_refutation_lines;
975 * @param {boolean} truncate_history
977 var set_truncate_history = function(truncate_history) {
978 truncate_display_history = truncate_history;
979 update_refutation_lines();
981 window['set_truncate_history'] = set_truncate_history;
984 * @param {number} line_num
985 * @param {number} move_num
987 var show_line = function(line_num, move_num) {
988 if (line_num == -1) {
989 current_display_line = null;
990 current_display_move = null;
991 if (displayed_analysis_data) {
992 // TODO: Support exiting to history position if we are in an
993 // analysis line of a history position.
994 displayed_analysis_data = null;
995 update_board(current_analysis_data, displayed_analysis_data);
998 current_display_line = display_lines[line_num];
999 current_display_move = move_num;
1001 current_display_line_is_history = (line_num == 0);
1003 update_historic_analysis();
1004 update_displayed_line();
1008 window['show_line'] = show_line;
1010 var prev_move = function() {
1011 if (current_display_move > -1) {
1012 --current_display_move;
1014 update_historic_analysis();
1015 update_displayed_line();
1017 window['prev_move'] = prev_move;
1019 var next_move = function() {
1020 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1021 ++current_display_move;
1023 update_historic_analysis();
1024 update_displayed_line();
1026 window['next_move'] = next_move;
1028 var update_historic_analysis = function() {
1029 if (!current_display_line_is_history) {
1032 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1033 displayed_analysis_data = null;
1034 update_board(current_analysis_data, displayed_analysis_data);
1037 // Fetch old analysis for this line if it exists.
1038 var hiddenboard = new Chess();
1039 for (var i = 0; i <= current_display_move; ++i) {
1040 hiddenboard.move(current_display_line.pretty_pv[i]);
1042 var filename = "/history/move" + (current_display_move + 1) + "-" +
1043 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1047 }).done(function(data, textstatus, xhr) {
1048 displayed_analysis_data = data;
1049 update_board(current_analysis_data, displayed_analysis_data);
1050 }).fail(function() {
1051 displayed_analysis_data = {'failed': true};
1052 update_board(current_analysis_data, displayed_analysis_data);
1056 var update_displayed_line = function() {
1057 if (highlighted_move !== null) {
1058 highlighted_move.removeClass('highlight');
1060 if (current_display_line === null) {
1061 $("#linenav").hide();
1062 $("#linemsg").show();
1063 board.position(fen);
1067 $("#linenav").show();
1068 $("#linemsg").hide();
1070 if (current_display_move <= 0) {
1071 $("#prevmove").html("Previous");
1073 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1075 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1076 $("#nextmove").html("Next");
1078 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1081 var hiddenboard = new Chess();
1082 hiddenboard.load(current_display_line.start_fen);
1083 for (var i = 0; i <= current_display_move; ++i) {
1084 hiddenboard.move(current_display_line.pretty_pv[i]);
1087 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1088 highlighted_move.addClass('highlight');
1090 board.position(hiddenboard.fen());
1094 * @param {boolean} param_enable_sound
1096 var set_sound = function(param_enable_sound) {
1097 enable_sound = param_enable_sound;
1099 $("#soundon").html("<strong>On</strong>");
1100 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1102 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1103 // and also preload the file since the user has selected audio.
1104 var ding = document.getElementById('ding');
1105 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1106 ding.src = 'ding.opus';
1110 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1111 $("#soundoff").html("<strong>Off</strong>");
1113 if (supports_html5_storage()) {
1114 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1117 window['set_sound'] = set_sound;
1119 var init = function() {
1120 unique = get_unique();
1122 // Load settings from HTML5 local storage if available.
1123 if (supports_html5_storage() && localStorage['enable_sound']) {
1124 set_sound(parseInt(localStorage['enable_sound']));
1128 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1129 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1131 sort_refutation_lines_by_score = true;
1135 board = new window.ChessBoard('board', 'start');
1138 $(window).resize(function() {
1143 $(window).keyup(function(event) {
1144 if (event.which == 39) {
1146 } else if (event.which == 37) {
1151 $(document).ready(init);