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');
141 if (Array.isArray(data)) {
142 new_data = JSON_delta.patch(current_analysis_data, data);
146 possibly_play_sound(current_analysis_data, new_data);
147 current_analysis_data = new_data;
148 update_board(current_analysis_data, displayed_analysis_data);
149 update_num_viewers(num_viewers);
152 setTimeout(function() { request_update(); }, 100);
154 // Wait ten seconds, then try again.
155 setTimeout(function() { request_update(); }, 10000);
159 var possibly_play_sound = function(old_data, new_data) {
163 if (old_data === null) {
166 var ding = document.getElementById('ding');
167 if (ding && ding.play) {
168 if (old_data['position'] && old_data['position']['fen'] &&
169 new_data['position'] && new_data['position']['fen'] &&
170 (old_data['position']['fen'] !== new_data['position']['fen'] ||
171 old_data['position']['move_num'] !== new_data['position']['move_num'])) {
178 * @type {!string} server_date_string
180 var sync_server_clock = function(server_date_string) {
181 var server_time_ms = new Date(server_date_string).getTime();
182 var client_time_ms = new Date().getTime();
183 var estimated_offset_ms = server_time_ms - client_time_ms;
185 // In order not to let the noise move us too much back and forth
186 // (the server only has one-second resolution anyway), we only
187 // change an existing skew if we are at least five seconds off.
188 if (client_clock_offset_ms === null ||
189 Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
190 client_clock_offset_ms = estimated_offset_ms;
194 var clear_arrows = function() {
195 for (var i = 0; i < arrows.length; ++i) {
197 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
198 delete arrows[i].svg;
203 occupied_by_arrows = [];
204 for (var y = 0; y < 8; ++y) {
205 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
209 var redraw_arrows = function() {
210 for (var i = 0; i < arrows.length; ++i) {
211 position_arrow(arrows[i]);
215 /** @param {!number} x
218 var sign = function(x) {
228 /** See if drawing this arrow on the board would cause unduly amount of confusion.
229 * @param {!string} from The square the arrow is from (e.g. e4).
230 * @param {!string} to The square the arrow is to (e.g. e4).
233 var interfering_arrow = function(from, to) {
234 var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
235 var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
236 var to_col = to.charCodeAt(0) - "a1".charCodeAt(0);
237 var to_row = to.charCodeAt(1) - "a1".charCodeAt(1);
239 occupied_by_arrows[from_row][from_col] = true;
241 // Knight move: Just check that we haven't been at the destination before.
242 if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
243 (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
244 return occupied_by_arrows[to_row][to_col];
247 // Sliding piece: Check if anything except the from-square is seen before.
248 var dx = sign(to_col - from_col);
249 var dy = sign(to_row - from_row);
255 if (occupied_by_arrows[y][x]) {
258 occupied_by_arrows[y][x] = true;
259 } while (x != to_col || y != to_row);
264 /** Find a point along the coordinate system given by the given line,
265 * <t> units forward from the start of the line, <u> units to the right of it.
266 * @param {!number} x1
267 * @param {!number} x2
268 * @param {!number} y1
269 * @param {!number} y2
272 * @return {!string} The point in "x y" form, suitable for SVG paths.
274 var point_from_start = function(x1, y1, x2, y2, t, u) {
278 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
282 var x = x1 + dx * t + dy * u;
283 var y = y1 + dy * t - dx * u;
287 /** Find a point along the coordinate system given by the given line,
288 * <t> units forward from the end of the line, <u> units to the right of it.
289 * @param {!number} x1
290 * @param {!number} x2
291 * @param {!number} y1
292 * @param {!number} y2
295 * @return {!string} The point in "x y" form, suitable for SVG paths.
297 var point_from_end = function(x1, y1, x2, y2, t, u) {
301 var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
305 var x = x2 + dx * t + dy * u;
306 var y = y2 + dy * t - dx * u;
310 var position_arrow = function(arrow) {
312 arrow.svg.parentElement.removeChild(arrow.svg);
315 if (current_display_line !== null && !current_display_line_is_history) {
319 var pos = $(".square-a8").position();
321 var zoom_factor = $("#board").width() / 400.0;
322 var line_width = arrow.line_width * zoom_factor;
323 var arrow_size = arrow.arrow_size * zoom_factor;
325 var square_width = $(".square-a8").width();
326 var from_y = (7 - arrow.from_row + 0.5)*square_width;
327 var to_y = (7 - arrow.to_row + 0.5)*square_width;
328 var from_x = (arrow.from_col + 0.5)*square_width;
329 var to_x = (arrow.to_col + 0.5)*square_width;
331 var SVG_NS = "http://www.w3.org/2000/svg";
332 var XHTML_NS = "http://www.w3.org/1999/xhtml";
333 var svg = document.createElementNS(SVG_NS, "svg");
334 svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
335 svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
336 svg.setAttribute("style", "position: absolute");
337 svg.setAttribute("position", "absolute");
338 svg.setAttribute("version", "1.1");
339 svg.setAttribute("class", "c1");
340 svg.setAttribute("xmlns", XHTML_NS);
348 var outline = document.createElementNS(SVG_NS, "path");
349 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));
350 outline.setAttribute("xmlns", XHTML_NS);
351 outline.setAttribute("stroke", "#666");
352 outline.setAttribute("stroke-width", line_width + 2);
353 outline.setAttribute("fill", "none");
354 svg.appendChild(outline);
356 var path = document.createElementNS(SVG_NS, "path");
357 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));
358 path.setAttribute("xmlns", XHTML_NS);
359 path.setAttribute("stroke", arrow.fg_color);
360 path.setAttribute("stroke-width", line_width);
361 path.setAttribute("fill", "none");
362 svg.appendChild(path);
364 // Then the arrow head.
365 var head = document.createElementNS(SVG_NS, "path");
366 head.setAttribute("d",
367 "M " + point_from_end(x1, y1, x2, y2, 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, -arrow_size * .623, 0.0) +
370 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
371 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
372 head.setAttribute("xmlns", XHTML_NS);
373 head.setAttribute("stroke", "#000");
374 head.setAttribute("stroke-width", "1");
375 head.setAttribute("fill", arrow.fg_color);
376 svg.appendChild(head);
378 $(svg).css({ top: pos.top, left: pos.left });
379 document.body.appendChild(svg);
384 * @param {!string} from_square
385 * @param {!string} to_square
386 * @param {!string} fg_color
387 * @param {number} line_width
388 * @param {number} arrow_size
390 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
391 var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
392 var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
393 var to_col = to_square.charCodeAt(0) - "a1".charCodeAt(0);
394 var to_row = to_square.charCodeAt(1) - "a1".charCodeAt(1);
402 line_width: line_width,
403 arrow_size: arrow_size,
407 position_arrow(arrow);
411 var compare_by_sort_key = function(refutation_lines, a, b) {
412 var ska = refutation_lines[a]['sort_key'];
413 var skb = refutation_lines[b]['sort_key'];
414 if (ska < skb) return -1;
415 if (ska > skb) return 1;
419 var compare_by_score = function(refutation_lines, a, b) {
420 var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
421 var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
426 * Fake multi-PV using the refutation lines. Find all “relevant” moves,
427 * sorted by quality, descending.
429 * @param {!Object} data
430 * @param {number} margin The maximum number of centipawns worse than the
431 * best move can be and still be included.
432 * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
433 * moves, in score order.
435 var find_nonstupid_moves = function(data, margin) {
436 // First of all, if there are any moves that are more than 0.5 ahead of
437 // the primary move, the refutation lines are probably bunk, so just
439 var best_score = undefined;
440 var pv_score = undefined;
441 for (var move in data['refutation_lines']) {
442 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
443 if (move == data['pv_uci'][0]) {
446 if (best_score === undefined || score > best_score) {
449 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
454 if (best_score - pv_score > 50) {
458 // Now find all moves that are within “margin” of the best score.
459 // The PV move will always be first.
461 for (var move in data['refutation_lines']) {
462 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
463 if (move != data['pv_uci'][0] && best_score - score <= margin) {
467 moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
468 moves.unshift(data['pv_uci'][0]);
477 var thousands = function(x) {
478 return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
482 * @param {!string} fen
483 * @param {Array.<string>} pretty_pv
484 * @param {number} move_num
485 * @param {!string} toplay
486 * @param {number=} opt_limit
487 * @param {boolean=} opt_showlast
489 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
492 pretty_pv: pretty_pv,
493 line_number: display_lines.length
495 return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
499 * @param {number} line_num
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 print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
509 if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
510 // Truncate the PV at the beginning (instead of at the end).
511 // We assume here that toplay is 'W'. We also assume that if
512 // opt_showlast is set, then it is the history, and thus,
513 // the UI should be to expand the history.
514 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
515 i = pretty_pv.length - opt_limit;
520 } else if (toplay == 'B' && pretty_pv.length > 0) {
521 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
522 pv = move_num + '. … ' + move;
527 for ( ; i < pretty_pv.length; ++i) {
528 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
531 if (i > opt_limit && !opt_showlast) {
537 pv += move_num + '. ' + move;
548 var update_highlight = function() {
549 $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
550 if ((current_display_line === null || current_display_line_is_history) &&
551 highlight_from !== undefined && highlight_to !== undefined) {
552 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
553 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
557 var update_history = function() {
558 if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
559 $("#history").html("No history");
560 } else if (truncate_display_history) {
561 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
564 '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
565 print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
570 * @param {!boolean} truncate_history
572 var collapse_history = function(truncate_history) {
573 truncate_display_history = truncate_history;
576 window['collapse_history'] = collapse_history;
578 var update_refutation_lines = function() {
582 if (display_lines.length > 2) {
583 display_lines = [ display_lines[0], display_lines[1] ];
586 var tbl = $("#refutationlines");
590 for (var move in refutation_lines) {
593 var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
594 moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
595 for (var i = 0; i < moves.length; ++i) {
596 var line = refutation_lines[moves[i]];
598 var tr = document.createElement("tr");
600 var move_td = document.createElement("td");
601 tr.appendChild(move_td);
602 $(move_td).addClass("move");
603 if (line['pv_pretty'].length == 0) {
604 $(move_td).text(line['pretty_move']);
606 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
607 $(move_td).html(move);
610 var score_td = document.createElement("td");
611 tr.appendChild(score_td);
612 $(score_td).addClass("score");
613 $(score_td).text(line['pretty_score']);
615 var depth_td = document.createElement("td");
616 tr.appendChild(depth_td);
617 $(depth_td).addClass("depth");
618 $(depth_td).text("d" + line['depth']);
620 var pv_td = document.createElement("td");
621 tr.appendChild(pv_td);
622 $(pv_td).addClass("pv");
623 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
628 // Make one of the links clickable and the other nonclickable.
629 if (sort_refutation_lines_by_score) {
630 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
631 $("#sortbyscore1").html("<strong>Score</strong>");
633 $("#sortbyscore0").html("<strong>Move</strong>");
634 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
639 * @param {?string} fen
640 * @param {Array.<string>} moves
641 * @param {number} last_move
643 var chess_from = function(fen, moves, last_move) {
644 var hiddenboard = new Chess();
646 hiddenboard.load(fen);
648 for (var i = 0; i <= last_move; ++i) {
649 if (moves[i] === '0-0') {
650 hiddenboard.move('O-O');
651 } else if (moves[i] === '0-0-0') {
652 hiddenboard.move('O-O-O');
654 hiddenboard.move(moves[i]);
661 * @param {Object} data
662 * @param {?Object} display_data
664 var update_board = function(current_data, display_data) {
665 var data = display_data || current_data;
669 // Print the history. This is pretty much the only thing that's
670 // unconditionally taken from current_data (we're not interested in
671 // historic history).
672 if (current_data['position']['pretty_history']) {
673 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
675 display_lines.push(null);
679 // The headline. Names are always fetched from current_data;
680 // the rest can depend a bit.
683 current_data['position']['player_w'] && current_data['position']['player_b']) {
684 headline = current_data['position']['player_w'] + '–' +
685 current_data['position']['player_b'] + ', analysis';
687 headline = 'Analysis';
692 // Displaying some non-current position, pick out the last move
693 // from the history. This will work even if the fetch failed.
694 last_move = format_move_with_number(
695 current_display_line.pretty_pv[current_display_move],
696 Math.floor((current_display_move + 1) / 2) + 1,
697 (current_display_move % 2 == 1));
698 headline += ' after ' + last_move;
699 } else if (data['position']['last_move'] !== 'none') {
700 last_move = format_move_with_number(
701 data['position']['last_move'],
702 data['position']['move_num'],
703 data['position']['toplay'] == 'W');
704 headline += ' after ' + last_move;
708 $("#headline").text(headline);
710 // The <title> contains a very brief headline.
711 var title_elems = [];
712 if (data['short_score'] !== undefined && data['short_score'] !== null) {
713 title_elems.push(data['short_score'].replace(/^ /, ""));
715 if (last_move !== null) {
716 title_elems.push(last_move);
719 if (title_elems.length != 0) {
720 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
722 document.title = 'analysis.sesse.net';
725 // The last move (shown by highlighting the from and to squares).
726 if (data['position'] && data['position']['last_move_uci']) {
727 highlight_from = data['position']['last_move_uci'].substr(0, 2);
728 highlight_to = data['position']['last_move_uci'].substr(2, 2);
729 } else if (current_display_line_is_history && current_display_move >= 0) {
730 // We don't have historic analysis for this position, but we
731 // can reconstruct what the last move was by just replaying
733 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
734 var moves = hiddenboard.history({ verbose: true });
735 var last_move = moves.pop();
736 highlight_from = last_move.from;
737 highlight_to = last_move.to;
739 highlight_from = highlight_to = undefined;
743 if (data['failed']) {
744 $("#score").text("No analysis for this move");
746 $("#searchstats").html(" ");
747 $("#refutationlines").empty();
748 $("#whiteclock").empty();
749 $("#blackclock").empty();
750 refutation_lines = [];
751 update_refutation_lines();
753 update_displayed_line();
760 if (data['id'] && data['id']['name'] !== null) {
761 $("#engineid").text(data['id']['name']);
765 if (data['score'] !== null) {
766 $("#score").text(data['score']);
770 if (data['tablebase'] == 1) {
771 $("#searchstats").text("Tablebase result");
772 } else if (data['nodes'] && data['nps'] && data['depth']) {
773 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
774 if (data['seldepth']) {
775 stats += ' (' + data['seldepth'] + ' selective)';
777 if (data['tbhits'] && data['tbhits'] > 0) {
778 if (data['tbhits'] == 1) {
779 stats += ', one Syzygy hit';
781 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
785 $("#searchstats").text(stats);
787 $("#searchstats").text("");
790 // Update the board itself.
791 fen = data['position']['fen'];
792 update_displayed_line();
795 $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
797 // Update the PV arrow.
799 if (data['pv_uci'].length >= 1) {
800 // draw a continuation arrow as long as it's the same piece
801 for (var i = 0; i < data['pv_uci'].length; i += 2) {
802 var from = data['pv_uci'][i].substr(0, 2);
803 var to = data['pv_uci'][i].substr(2,4);
804 if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
805 interfering_arrow(from, to)) {
808 create_arrow(from, to, '#f66', 6, 20);
811 var alt_moves = find_nonstupid_moves(data, 30);
812 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
813 create_arrow(alt_moves[i].substr(0, 2),
814 alt_moves[i].substr(2, 2), '#f66', 1, 10);
818 // See if all semi-reasonable moves have only one possible response.
819 if (data['pv_uci'].length >= 2) {
820 var nonstupid_moves = find_nonstupid_moves(data, 300);
821 var response = data['pv_uci'][1];
822 for (var i = 0; i < nonstupid_moves.length; ++i) {
823 if (nonstupid_moves[i] == data['pv_uci'][0]) {
824 // ignore the PV move for refutation lines.
827 if (!data['refutation_lines'] ||
828 !data['refutation_lines'][nonstupid_moves[i]] ||
829 !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
830 data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
831 // Incomplete PV, abort.
832 response = undefined;
835 var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
836 if (response !== this_response) {
837 // Different response depending on lines, abort.
838 response = undefined;
843 if (nonstupid_moves.length > 0 && response !== undefined) {
844 create_arrow(response.substr(0, 2),
845 response.substr(2, 2), '#66f', 6, 20);
849 // Update the refutation lines.
850 fen = data['position']['fen'];
851 move_num = data['position']['move_num'];
852 toplay = data['position']['toplay'];
853 refutation_lines = data['refutation_lines'];
854 update_refutation_lines();
858 * @param {number} num_viewers
860 var update_num_viewers = function(num_viewers) {
861 if (num_viewers === null) {
862 $("#numviewers").text("");
863 } else if (num_viewers == 1) {
864 $("#numviewers").text("You are the only current viewer");
866 $("#numviewers").text(num_viewers + " current viewers");
870 var update_clock = function() {
871 clearTimeout(clock_timer);
873 var data = displayed_analysis_data || current_analysis_data;
874 if (data['position']) {
875 var result = data['position']['result'];
876 if (result === '1-0') {
877 $("#whiteclock").text("1");
878 $("#blackclock").text("0");
879 $("#whiteclock").removeClass("running-clock");
880 $("#blackclock").removeClass("running-clock");
883 if (result === '1/2-1/2') {
884 $("#whiteclock").text("1/2");
885 $("#blackclock").text("1/2");
886 $("#whiteclock").removeClass("running-clock");
887 $("#blackclock").removeClass("running-clock");
890 if (result === '0-1') {
891 $("#whiteclock").text("0");
892 $("#blackclock").text("1");
893 $("#whiteclock").removeClass("running-clock");
894 $("#blackclock").removeClass("running-clock");
899 var white_clock_ms = null;
900 var black_clock_ms = null;
901 var show_seconds = false;
904 if (data['position'] &&
905 data['position']['white_clock'] &&
906 data['position']['black_clock']) {
907 white_clock_ms = data['position']['white_clock'] * 1000;
908 black_clock_ms = data['position']['black_clock'] * 1000;
911 // Dynamic clock (only one, obviously).
913 if (data['position']['white_clock_target']) {
915 $("#whiteclock").addClass("running-clock");
916 $("#blackclock").removeClass("running-clock");
917 } else if (data['position']['black_clock_target']) {
919 $("#whiteclock").removeClass("running-clock");
920 $("#blackclock").addClass("running-clock");
922 $("#whiteclock").removeClass("running-clock");
923 $("#blackclock").removeClass("running-clock");
927 var now = new Date().getTime() + client_clock_offset_ms;
928 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
929 if (color === "white") {
930 white_clock_ms = remaining_ms;
932 black_clock_ms = remaining_ms;
936 if (white_clock_ms === null || black_clock_ms === null) {
937 $("#whiteclock").empty();
938 $("#blackclock").empty();
942 // If either player has ten minutes or less left, add the second counters.
943 var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
946 // See when the clock will change next, and update right after that.
949 next_update_ms = remaining_ms % 1000 + 100;
951 next_update_ms = remaining_ms % 60000 + 100;
953 clock_timer = setTimeout(update_clock, next_update_ms);
956 $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
957 $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
961 * @param {Number} remaining_ms
962 * @param {boolean} show_seconds
964 var format_clock = function(remaining_ms, show_seconds) {
965 if (remaining_ms <= 0) {
973 var remaining = Math.floor(remaining_ms / 1000);
974 var seconds = remaining % 60;
975 remaining = (remaining - seconds) / 60;
976 var minutes = remaining % 60;
977 remaining = (remaining - minutes) / 60;
978 var hours = remaining;
980 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
982 return format_2d(hours) + ":" + format_2d(minutes);
989 var format_2d = function(x) {
998 * @param {string} move
999 * @param {Number} move_num
1000 * @param {boolean} white_to_play
1002 var format_move_with_number = function(move, move_num, white_to_play) {
1004 if (white_to_play) {
1005 ret = (move_num - 1) + '… ';
1007 ret = move_num + '. ';
1014 * @param {boolean} sort_by_score
1016 var resort_refutation_lines = function(sort_by_score) {
1017 sort_refutation_lines_by_score = sort_by_score;
1018 if (supports_html5_storage()) {
1019 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1021 update_refutation_lines();
1023 window['resort_refutation_lines'] = resort_refutation_lines;
1026 * @param {boolean} truncate_history
1028 var set_truncate_history = function(truncate_history) {
1029 truncate_display_history = truncate_history;
1030 update_refutation_lines();
1032 window['set_truncate_history'] = set_truncate_history;
1035 * @param {number} line_num
1036 * @param {number} move_num
1038 var show_line = function(line_num, move_num) {
1039 if (line_num == -1) {
1040 current_display_line = null;
1041 current_display_move = null;
1042 if (displayed_analysis_data) {
1043 // TODO: Support exiting to history position if we are in an
1044 // analysis line of a history position.
1045 displayed_analysis_data = null;
1046 update_board(current_analysis_data, displayed_analysis_data);
1049 current_display_line = display_lines[line_num];
1050 current_display_move = move_num;
1052 current_display_line_is_history = (line_num == 0);
1054 update_historic_analysis();
1055 update_displayed_line();
1059 window['show_line'] = show_line;
1061 var prev_move = function() {
1062 if (current_display_move > -1) {
1063 --current_display_move;
1065 update_historic_analysis();
1066 update_displayed_line();
1068 window['prev_move'] = prev_move;
1070 var next_move = function() {
1071 if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1072 ++current_display_move;
1074 update_historic_analysis();
1075 update_displayed_line();
1077 window['next_move'] = next_move;
1079 var update_historic_analysis = function() {
1080 if (!current_display_line_is_history) {
1083 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1084 displayed_analysis_data = null;
1085 update_board(current_analysis_data, displayed_analysis_data);
1088 // Fetch old analysis for this line if it exists.
1089 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1090 var filename = "/history/move" + (current_display_move + 1) + "-" +
1091 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1095 }).done(function(data, textstatus, xhr) {
1096 displayed_analysis_data = data;
1097 update_board(current_analysis_data, displayed_analysis_data);
1098 }).fail(function() {
1099 displayed_analysis_data = {'failed': true};
1100 update_board(current_analysis_data, displayed_analysis_data);
1105 * @param {string} fen
1107 var update_imbalance = function(fen) {
1108 var hiddenboard = new Chess(fen);
1109 var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1110 for (var row = 0; row < 8; ++row) {
1111 for (var col = 0; col < 8; ++col) {
1112 var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1113 var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1114 var square = col_text + row_text;
1115 var contents = hiddenboard.get(square);
1116 if (contents !== null) {
1117 if (contents.color === 'w') {
1118 ++imbalance[contents.type];
1120 --imbalance[contents.type];
1125 var white_imbalance = '';
1126 var black_imbalance = '';
1127 for (var piece in imbalance) {
1128 for (var i = 0; i < imbalance[piece]; ++i) {
1129 white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1131 for (var i = 0; i < -imbalance[piece]; ++i) {
1132 black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1135 $('#whiteimbalance').html(white_imbalance);
1136 $('#blackimbalance').html(black_imbalance);
1139 var update_displayed_line = function() {
1140 if (highlighted_move !== null) {
1141 highlighted_move.removeClass('highlight');
1143 if (current_display_line === null) {
1144 $("#linenav").hide();
1145 $("#linemsg").show();
1146 board.position(fen);
1147 update_imbalance(fen);
1151 $("#linenav").show();
1152 $("#linemsg").hide();
1154 if (current_display_move <= 0) {
1155 $("#prevmove").html("Previous");
1157 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1159 if (current_display_move == current_display_line.pretty_pv.length - 1) {
1160 $("#nextmove").html("Next");
1162 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1165 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1166 highlighted_move.addClass('highlight');
1168 var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1169 board.position(hiddenboard.fen());
1170 update_imbalance(hiddenboard.fen());
1174 * @param {boolean} param_enable_sound
1176 var set_sound = function(param_enable_sound) {
1177 enable_sound = param_enable_sound;
1179 $("#soundon").html("<strong>On</strong>");
1180 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1182 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1183 // and also preload the file since the user has selected audio.
1184 var ding = document.getElementById('ding');
1185 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1186 ding.src = 'ding.opus';
1190 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1191 $("#soundoff").html("<strong>Off</strong>");
1193 if (supports_html5_storage()) {
1194 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1197 window['set_sound'] = set_sound;
1199 var init = function() {
1200 unique = get_unique();
1202 // Load settings from HTML5 local storage if available.
1203 if (supports_html5_storage() && localStorage['enable_sound']) {
1204 set_sound(parseInt(localStorage['enable_sound']));
1208 if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1209 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1211 sort_refutation_lines_by_score = true;
1215 board = new window.ChessBoard('board', 'start');
1218 $(window).resize(function() {
1223 $(window).keyup(function(event) {
1224 if (event.which == 39) {
1226 } else if (event.which == 37) {
1231 $(document).ready(init);