]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
Fix SVG positioning when we are scrolled.
[remoteglot] / www / js / remoteglot.js
1 (function() {
2
3 /**
4  * Version of this script. If the server returns a version larger than
5  * this, it is a sign we should reload to upgrade ourselves.
6  *
7  * @type {Number}
8  * @const
9  * @private */
10 var SCRIPT_VERSION = 2021021300;
11
12 /**
13  * The current backend URL.
14  *
15  * @type {!string}
16  * @private
17  */
18 var backend_url = "/analysis.pl";
19 var backend_hash_url = "/hash";
20
21 /** @type {window.ChessBoard} @private */
22 var board = null;
23
24 /** @type {boolean} @private */
25 var board_is_animating = false;
26
27 /**
28  * The most recent analysis data we have from the server
29  * (about the most recent position).
30  *
31  * @type {?Object}
32  * @private */
33 var current_analysis_data = null;
34
35 /**
36  * If we are displaying previous analysis or from hash, this is non-null,
37  * and will override most of current_analysis_data.
38  *
39  * @type {?Object}
40  * @private
41  */
42 var displayed_analysis_data = null;
43
44 /**
45  * Games currently in progress, if any.
46  *
47  * @type {?Array.<{
48  *      name: string,
49  *      url: string,
50  *      hashurl: string,
51  *      id: string,
52  *      score: Object=,
53  *      result: string=,
54  * }>}
55  * @private
56  */
57 var current_games = null;
58
59 /** @type {Array.<{
60  *      from_col: number,
61  *      from_row: number,
62  *      to_col: number,
63  *      to_row: number,
64  *      line_width: number,
65  *      arrow_size: number,
66  *      fg_color: string
67  * }>}
68  * @private
69  */
70 var arrows = [];
71
72 /** @type {Array.<Array.<boolean>>} */
73 var occupied_by_arrows = [];
74
75 /** Currently displayed refutation lines (on-screen).
76  * Can either come from the current_analysis_data, displayed_analysis_data,
77  * or hash_refutation_lines.
78  */
79 var refutation_lines = [];
80
81 /** Refutation lines from current hash probe.
82  *
83  * If non-null, will override refutation lines from the base position.
84  * Note that these are relative to display_fen, not base_fen.
85  */
86 var hash_refutation_lines = null;
87
88 /** @type {!number} @private */
89 var move_num = 1;
90
91 /** @type {!string} @private */
92 var toplay = 'W';
93
94 /** @type {number} @private */
95 var ims = 0;
96
97 /** @type {boolean} @private */
98 var truncate_display_history = true;
99
100 /** @type {!string|undefined} @private */
101 var highlight_from = undefined;
102
103 /** @type {!string|undefined} @private */
104 var highlight_to = undefined;
105
106 /** The HTML object of the move currently being highlighted (in red).
107  * @type {?Element}
108  * @private */
109 var highlighted_move = null;
110
111 /** Currently suggested/recommended move when dragging.
112  * @type {?{from: !string, to: !string}}
113  * @private
114  */
115 var recommended_move = null;
116
117 /** If reverse-dragging (dragging from the destination square to the
118  * source square), the destination square.
119  * @type {?string}
120  * @private
121  */
122 var reverse_dragging_from = null;
123
124 /** @type {?number} @private */
125 var unique = null;
126
127 /** @type {boolean} @private */
128 var enable_sound = false;
129
130 /** @type {!number} @private */
131 var delay_ms = 0;
132
133 /**
134  * Our best estimate of how many milliseconds we need to add to 
135  * new Date() to get the true UTC time. Calibrated against the
136  * server clock.
137  *
138  * @type {?number}
139  * @private
140  */
141 var client_clock_offset_ms = null;
142
143 var clock_timer = null;
144
145 /** The current position being analyzed, represented as a FEN string.
146  * Note that this is not necessarily the same as display_fen.
147  * @type {?string}
148  * @private
149  */
150 var base_fen = null;
151
152 /** The current position on the board, represented as a FEN string.
153  * Note that board.fen() does not contain e.g. who is to play.
154  * @type {?string}
155  * @private
156  */
157 var display_fen = null;
158
159 /** @typedef {{
160  *    start_fen: string,
161  *    pv: Array.<string>,
162  *    move_num: number,
163  *    toplay: string,
164  *    scores: Array<{first_move: number, score: Object}>,
165  *    start_display_move_num: number
166  * }} DisplayLine
167  *
168  * "start_display_move_num" is the (half-)move number to start displaying the PV at.
169  * "score" is also evaluated at this point.
170  */
171
172 /** All PVs that we currently know of.
173  *
174  * Element 0 is history (or null if no history).
175  * Element 1 is current main PV, or explored line if nowhere else on the screen.
176  * All remaining elements are refutation lines (multi-PV).
177  *
178  * @type {Array.<DisplayLine>}
179  * @private
180  */
181 var display_lines = [];
182
183 /** @type {?DisplayLine} @private */
184 var current_display_line = null;
185
186 /** @type {boolean} @private */
187 var current_display_line_is_history = false;
188
189 /** @type {?number} @private */
190 var current_display_move = null;
191
192 /**
193  * The current backend request to get main analysis (not history), if any,
194  * so that we can abort it.
195  *
196  * @type {?AbortController}
197  * @private
198  */
199 var current_analysis_xhr = null;
200
201 /**
202  * The current timer to fire off a request to get main analysis (not history),
203  * if any, so that we can abort it.
204  *
205  * @type {?Number}
206  * @private
207  */
208 var current_analysis_request_timer = null;
209
210 /**
211  * The current backend request to get historic data, if any.
212  *
213  * @type {?AbortController}
214  * @private
215  */
216 var current_historic_xhr = null;
217
218 /**
219  * The current backend request to get hash probes, if any, so that we can abort it.
220  *
221  * @type {?AbortController}
222  * @private
223  */
224 var current_hash_xhr = null;
225
226 /**
227  * The current timer to display hash probe information (it could be waiting on the
228  * board to stop animating), if any, so that we can abort it.
229  *
230  * @type {?Number}
231  * @private
232  */
233 var current_hash_display_timer = null;
234
235 var supports_html5_storage = function() {
236         try {
237                 return 'localStorage' in window && window['localStorage'] !== null;
238         } catch (e) {
239                 return false;
240         }
241 }
242
243 // Make the unique token persistent so people refreshing the page won't count twice.
244 // Of course, you can never fully protect against people deliberately wanting to spam.
245 var get_unique = function() {
246         var use_local_storage = supports_html5_storage();
247         if (use_local_storage && localStorage['unique']) {
248                 return localStorage['unique'];
249         }
250         var unique = Math.random();
251         if (use_local_storage) {
252                 localStorage['unique'] = unique;
253         }
254         return unique;
255 }
256
257 var request_update = function() {
258         current_analysis_request_timer = null;
259
260         let handle_err = () => {
261                 // Backend error or similar. Wait ten seconds, then try again.
262                 current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
263         };
264
265         current_analysis_xhr = new AbortController();
266         const signal = current_analysis_xhr.signal;
267         fetch(backend_url + "?ims=" + ims + "&unique=" + unique, { signal })
268                 .then((response) => response.json().then(data => ({ok: response.ok, headers: response.headers, json: data})))  // ick
269                 .then((obj) => {
270                         if (!obj.ok) {
271                                 handle_err();
272                                 return;
273                         }
274
275                         if (delay_ms === 0) {
276                                 process_update_response(obj.json, obj.headers);
277                         } else {
278                                 setTimeout(function() { process_update_response(obj.json, obj.headers); }, delay_ms);
279                         }
280
281                         // Next update.
282                         if (!backend_url.match(/history/)) {
283                                 var timeout = 100;
284                                 current_analysis_request_timer = setTimeout(function() { request_update(); }, timeout);
285                         }
286                 })
287                 .catch((err) => {
288                         if (err.name === 'AbortError') {
289                                 // Aborted because we are switching backends. Abandon and don't retry,
290                                 // because another one is already started for us.
291                         } else {
292                                 console.log(err);
293                                 handle_err(err);
294                         }
295                 })
296                 .finally(() => {
297                         // Display.
298                         document.body.style.opacity = null;
299                 })
300
301 }
302
303 var process_update_response = function(data, headers) {
304         sync_server_clock(headers.get('Date'));
305         ims = headers.get('X-RGLM');
306         var num_viewers = headers.get('X-RGNV');
307         var new_data;
308         if (Array.isArray(data)) {
309                 new_data = JSON.parse(JSON.stringify(current_analysis_data));
310                 JSON_delta.patch(new_data, data);
311         } else {
312                 new_data = data;
313         }
314
315         var minimum_version = headers.get('X-RGMV');
316         if (minimum_version && minimum_version > SCRIPT_VERSION) {
317                 // Upgrade to latest version with a force-reload.
318                 location.reload(true);
319         }
320
321         // Verify that the PV makes sense.
322         var valid = true;
323         if (new_data['pv']) {
324                 var hiddenboard = new Chess(new_data['position']['fen']);
325                 for (var i = 0; i < new_data['pv'].length; ++i) {
326                         if (hiddenboard.move(new_data['pv'][i]) === null) {
327                                 valid = false;
328                                 break;
329                         }
330                 }
331         }
332
333         if (valid) {
334                 possibly_play_sound(current_analysis_data, new_data);
335                 current_analysis_data = new_data;
336                 update_board();
337                 update_num_viewers(num_viewers);
338         } else {
339                 console.log("Received invalid update, waiting five seconds and trying again.");
340                 setTimeout(function() { location.reload(true); }, 5000);
341         }
342 }
343
344 var possibly_play_sound = function(old_data, new_data) {
345         if (!enable_sound) {
346                 return;
347         }
348         if (old_data === null) {
349                 return;
350         }
351         var ding = document.getElementById('ding');
352         if (ding && ding.play) {
353                 if (old_data['position'] && old_data['position']['fen'] &&
354                     new_data['position'] && new_data['position']['fen'] &&
355                     (old_data['position']['fen'] !== new_data['position']['fen'] ||
356                      old_data['position']['move_num'] !== new_data['position']['move_num'])) {
357                         ding.play();
358                 }
359         }
360 }
361
362 /**
363  * @type {!string} server_date_string
364  */
365 var sync_server_clock = function(server_date_string) {
366         var server_time_ms = new Date(server_date_string).getTime();
367         var client_time_ms = new Date().getTime();
368         var estimated_offset_ms = server_time_ms - client_time_ms;
369
370         // In order not to let the noise move us too much back and forth
371         // (the server only has one-second resolution anyway), we only
372         // change an existing skew if we are at least five seconds off.
373         if (client_clock_offset_ms === null ||
374             Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
375                 client_clock_offset_ms = estimated_offset_ms;
376         }
377 }
378
379 var clear_arrows = function() {
380         for (var i = 0; i < arrows.length; ++i) {
381                 if (arrows[i].svg) {
382                         if (arrows[i].svg.parentElement) {
383                                 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
384                         }
385                         delete arrows[i].svg;
386                 }
387         }
388         arrows = [];
389
390         occupied_by_arrows = [];
391         for (var y = 0; y < 8; ++y) {
392                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
393         }
394 }
395
396 var redraw_arrows = function() {
397         for (var i = 0; i < arrows.length; ++i) {
398                 position_arrow(arrows[i]);
399         }
400 }
401
402 /** @param {!number} x
403  * @return {!number}
404  */
405 var sign = function(x) {
406         if (x > 0) {
407                 return 1;
408         } else if (x < 0) {
409                 return -1;
410         } else {
411                 return 0;
412         }
413 }
414
415 /** See if drawing this arrow on the board would cause unduly amount of confusion.
416  * @param {!string} from The square the arrow is from (e.g. e4).
417  * @param {!string} to The square the arrow is to (e.g. e4).
418  * @return {boolean}
419  */
420 var interfering_arrow = function(from, to) {
421         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
422         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
423         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
424         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
425
426         occupied_by_arrows[from_row][from_col] = true;
427
428         // Knight move: Just check that we haven't been at the destination before.
429         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
430             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
431                 return occupied_by_arrows[to_row][to_col];
432         }
433
434         // Sliding piece: Check if anything except the from-square is seen before.
435         var dx = sign(to_col - from_col);
436         var dy = sign(to_row - from_row);
437         var x = from_col;
438         var y = from_row;
439         do {
440                 x += dx;
441                 y += dy;
442                 if (occupied_by_arrows[y][x]) {
443                         return true;
444                 }
445                 occupied_by_arrows[y][x] = true;
446         } while (x != to_col || y != to_row);
447
448         return false;
449 }
450
451 /** Find a point along the coordinate system given by the given line,
452  * <t> units forward from the start of the line, <u> units to the right of it.
453  * @param {!number} x1
454  * @param {!number} x2
455  * @param {!number} y1
456  * @param {!number} y2
457  * @param {!number} t
458  * @param {!number} u
459  * @return {!string} The point in "x y" form, suitable for SVG paths.
460  */
461 var point_from_start = function(x1, y1, x2, y2, t, u) {
462         var dx = x2 - x1;
463         var dy = y2 - y1;
464
465         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
466         dx *= norm;
467         dy *= norm;
468
469         var x = x1 + dx * t + dy * u;
470         var y = y1 + dy * t - dx * u;
471         return x + " " + y;
472 }
473
474 /** Find a point along the coordinate system given by the given line,
475  * <t> units forward from the end of the line, <u> units to the right of it.
476  * @param {!number} x1
477  * @param {!number} x2
478  * @param {!number} y1
479  * @param {!number} y2
480  * @param {!number} t
481  * @param {!number} u
482  * @return {!string} The point in "x y" form, suitable for SVG paths.
483  */
484 var point_from_end = function(x1, y1, x2, y2, t, u) {
485         var dx = x2 - x1;
486         var dy = y2 - y1;
487
488         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
489         dx *= norm;
490         dy *= norm;
491
492         var x = x2 + dx * t + dy * u;
493         var y = y2 + dy * t - dx * u;
494         return x + " " + y;
495 }
496
497 var position_arrow = function(arrow) {
498         if (arrow.svg) {
499                 if (arrow.svg.parentElement) {
500                         arrow.svg.parentElement.removeChild(arrow.svg);
501                 }
502                 delete arrow.svg;
503         }
504         if (current_display_line !== null && !current_display_line_is_history) {
505                 return;
506         }
507
508         var zoom_factor = document.getElementById("board").getBoundingClientRect().width / 400.0;
509         var line_width = arrow.line_width * zoom_factor;
510         var arrow_size = arrow.arrow_size * zoom_factor;
511
512         var square_width = document.querySelector(".square-a8").getBoundingClientRect().width;
513         var from_y, to_y, from_x, to_x;
514         if (board.orientation() === 'black') {
515                 from_y = (arrow.from_row + 0.5)*square_width;
516                 to_y = (arrow.to_row + 0.5)*square_width;
517                 from_x = (7 - arrow.from_col + 0.5)*square_width;
518                 to_x = (7 - arrow.to_col + 0.5)*square_width;
519         } else {
520                 from_y = (7 - arrow.from_row + 0.5)*square_width;
521                 to_y = (7 - arrow.to_row + 0.5)*square_width;
522                 from_x = (arrow.from_col + 0.5)*square_width;
523                 to_x = (arrow.to_col + 0.5)*square_width;
524         }
525
526         var SVG_NS = "http://www.w3.org/2000/svg";
527         var XHTML_NS = "http://www.w3.org/1999/xhtml";
528         var svg = document.createElementNS(SVG_NS, "svg");
529         svg.setAttribute("width", /** @type{number} */ (document.getElementById("board").getBoundingClientRect().width));
530         svg.setAttribute("height", /** @type{number} */ (document.getElementById("board").getBoundingClientRect().height));
531         svg.setAttribute("style", "position: absolute");
532         svg.setAttribute("position", "absolute");
533         svg.setAttribute("version", "1.1");
534         svg.setAttribute("class", "c1");
535         svg.setAttribute("xmlns", XHTML_NS);
536
537         var x1 = from_x;
538         var y1 = from_y;
539         var x2 = to_x;
540         var y2 = to_y;
541
542         // Draw the line.
543         var outline = document.createElementNS(SVG_NS, "path");
544         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));
545         outline.setAttribute("xmlns", XHTML_NS);
546         outline.setAttribute("stroke", "#666");
547         outline.setAttribute("stroke-width", line_width + 2);
548         outline.setAttribute("fill", "none");
549         svg.appendChild(outline);
550
551         var path = document.createElementNS(SVG_NS, "path");
552         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));
553         path.setAttribute("xmlns", XHTML_NS);
554         path.setAttribute("stroke", arrow.fg_color);
555         path.setAttribute("stroke-width", line_width);
556         path.setAttribute("fill", "none");
557         svg.appendChild(path);
558
559         // Then the arrow head.
560         var head = document.createElementNS(SVG_NS, "path");
561         head.setAttribute("d",
562                 "M " +  point_from_end(x1, y1, x2, y2, 0, 0) +
563                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
564                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
565                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
566                 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
567         head.setAttribute("xmlns", XHTML_NS);
568         head.setAttribute("stroke", "#000");
569         head.setAttribute("stroke-width", "1");
570         head.setAttribute("fill", arrow.fg_color);
571         svg.appendChild(head);
572
573         svg.style.top = '2px';  /* Border for .board-b72b1. */
574         svg.style.left = '2px';
575         svg.style.pointerEvents = 'none';
576         document.getElementById('board').appendChild(svg);
577         arrow.svg = svg;
578 }
579
580 /**
581  * @param {!string} from_square
582  * @param {!string} to_square
583  * @param {!string} fg_color
584  * @param {number} line_width
585  * @param {number} arrow_size
586  */
587 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
588         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
589         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
590         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
591         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
592
593         // Create arrow.
594         var arrow = {
595                 from_col: from_col,
596                 from_row: from_row,
597                 to_col: to_col,
598                 to_row: to_row,
599                 line_width: line_width,
600                 arrow_size: arrow_size,
601                 fg_color: fg_color
602         };
603
604         position_arrow(arrow);
605         arrows.push(arrow);
606 }
607
608 var compare_by_score = function(refutation_lines, invert, a, b) {
609         var sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
610         var sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
611         return sa - sb;
612 }
613
614 /**
615  * Fake multi-PV using the refutation lines. Find all “relevant” moves,
616  * sorted by quality, descending.
617  *
618  * @param {!Object} data
619  * @param {number} margin The maximum number of centipawns worse than the
620  *     best move can be and still be included.
621  * @param {boolean} invert Whether black is to play.
622  * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
623  *     moves, in score order.
624  */
625 var find_nonstupid_moves = function(data, margin, invert) {
626         // First of all, if there are any moves that are more than 0.5 ahead of
627         // the primary move, the refutation lines are probably bunk, so just
628         // kill them all. 
629         var best_score = undefined;
630         var pv_score = undefined;
631         for (var move in data['refutation_lines']) {
632                 var line = data['refutation_lines'][move];
633                 var score = compute_score_sort_key(line['score'], line['depth'], invert, false);
634                 if (move == data['pv'][0]) {
635                         pv_score = score;
636                 }
637                 if (best_score === undefined || score > best_score) {
638                         best_score = score;
639                 }
640                 if (line['depth'] < 8) {
641                         return [];
642                 }
643         }
644
645         if (best_score - pv_score > 50) {
646                 return [];
647         }
648
649         // Now find all moves that are within “margin” of the best score.
650         // The PV move will always be first.
651         var moves = [];
652         for (var move in data['refutation_lines']) {
653                 var line = data['refutation_lines'][move];
654                 var score = compute_score_sort_key(line['score'], line['depth'], invert);
655                 if (move != data['pv'][0] && best_score - score <= margin) {
656                         moves.push(move);
657                 }
658         }
659         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
660         moves.unshift(data['pv'][0]);
661
662         return moves;
663 }
664
665 /**
666  * @param {number} x
667  * @return {!string}
668  */
669 var thousands = function(x) {
670         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
671 }
672
673 /**
674  * @param {!string} start_fen
675  * @param {Array.<string>} pv
676  * @param {number} move_num
677  * @param {!string} toplay
678  * @param {Array<{ first_move: integer, score: Object }>} scores
679  * @param {number} start_display_move_num
680  * @param {number=} opt_limit
681  * @param {boolean=} opt_showlast
682  */
683 var add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
684         display_lines.push({
685                 start_fen: start_fen,
686                 pv: pv,
687                 move_num: parseInt(move_num),
688                 toplay: toplay,
689                 scores: scores,
690                 start_display_move_num: start_display_move_num
691         });
692         var splicepos = null;
693         if (scores !== null && scores.length >= 1 &&
694             scores[scores.length - 1].score !== undefined &&
695             scores[scores.length - 1].score !== null &&
696             (scores[scores.length - 1].score[0] === 'T' ||
697              scores[scores.length - 1].score[0] === 't')) {
698                 splicepos = scores[scores.length - 1].score[1];
699         }
700         return print_pv(display_lines.length - 1, splicepos, opt_limit, opt_showlast);
701 }
702
703 /**
704  * @param {number} line_num
705  * @param {?number} splicepos If non-null, where the tablebase-spliced portion of the TB starts.
706  * @param {number=} opt_limit If set, show at most this number of moves.
707  * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
708  */
709 var print_pv = function(line_num, splicepos, opt_limit, opt_showlast) {
710         var display_line = display_lines[line_num];
711         var pv = display_line.pv;
712         var move_num = display_line.move_num;
713         var toplay = display_line.toplay;
714
715         // Truncate PV at the start if needed.
716         var start_display_move_num = display_line.start_display_move_num;
717         if (start_display_move_num > 0) {
718                 pv = pv.slice(start_display_move_num);
719                 var to_add = start_display_move_num;
720                 if (toplay === 'B') {
721                         ++move_num;
722                         toplay = 'W';
723                         --to_add;
724                 }
725                 if (to_add % 2 == 1) {
726                         toplay = 'B';
727                         --to_add;
728                 }
729                 move_num += to_add / 2;
730                 if (splicepos !== null && splicepos > 0) {
731                         --splicepos;
732                 }
733         }
734
735         var ret = '';
736         var i = 0;
737         var in_tb = false;
738         if (opt_limit && opt_showlast && pv.length > opt_limit) {
739                 // Truncate the PV at the beginning (instead of at the end).
740                 // We assume here that toplay is 'W'. We also assume that if
741                 // opt_showlast is set, then it is the history, and thus,
742                 // the UI should be to expand the history.
743                 ret = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
744                 i = pv.length - opt_limit;
745                 if (i % 2 == 1) {
746                         ++i;
747                 }
748                 move_num += i / 2;
749         } else if (toplay == 'B' && pv.length > 0) {
750                 var move = "";
751                 if (splicepos === 0) {
752                         move += "(TB: ";
753                         in_tb = true;
754                 }
755                 move += "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pv[0] + "</a>";
756                 ret = move_num + '. … ' + move;
757                 toplay = 'W';
758                 ++i;
759                 ++move_num;
760         }
761         for ( ; i < pv.length; ++i) {
762                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pv[i] + "</a>";
763                 if (splicepos === i) {
764                         ret += " (TB: ";
765                         in_tb = true;
766                 }
767
768                 if (toplay == 'W') {
769                         if (i > opt_limit && !opt_showlast) {
770                                 if (in_tb) {
771                                         ret += ")";
772                                 }
773                                 return ret + ' (…)';
774                         }
775                         if (ret != '') {
776                                 ret += ' ';
777                         }
778                         ret += move_num + '. ' + move;
779                         ++move_num;
780                         toplay = 'B';
781                 } else {
782                         ret += ' ' + move;
783                         toplay = 'W';
784                 }
785         }
786         if (in_tb) {
787                 ret += ")";
788         }
789         return ret;
790 }
791
792 /** Update the highlighted to/from squares on the board.
793  * Based on the global "highlight_from" and "highlight_to" variables.
794  */
795 var update_board_highlight = function() {
796         document.getElementById("board").querySelector('.square-55d63').classList.remove('nonuglyhighlight');
797         if ((current_display_line === null || current_display_line_is_history) &&
798             highlight_from !== undefined && highlight_to !== undefined) {
799                 document.getElementById("board").querySelector('.square-' + highlight_from).classList.add('nonuglyhighlight');
800                 document.getElementById("board").querySelector('.square-' + highlight_to).classList.add('nonuglyhighlight');
801         }
802 }
803
804 var update_history = function() {
805         if (display_lines[0] === null || display_lines[0].pv.length == 0) {
806                 document.getElementById("history").innerHTML = "No history";
807         } else if (truncate_display_history) {
808                 document.getElementById("history").innerHTML = print_pv(0, null, 8, true);
809         } else {
810                 document.getElementById("history").innerHTML =
811                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
812                         print_pv(0, null);
813         }
814 }
815
816 /**
817  * @param {!boolean} truncate_history
818  */
819 var collapse_history = function(truncate_history) {
820         truncate_display_history = truncate_history;
821         update_history();
822 }
823 window['collapse_history'] = collapse_history;
824
825 /** Update the HTML display of multi-PV from the global "refutation_lines".
826  *
827  * Also recreates the global "display_lines".
828  */
829 var update_refutation_lines = function() {
830         if (base_fen === null) {
831                 return;
832         }
833         if (display_lines.length > 2) {
834                 // Truncate so that only the history and PV is left.
835                 display_lines = [ display_lines[0], display_lines[1] ];
836         }
837         var tbl = document.getElementById("refutationlines");
838         tbl.replaceChildren();
839
840         if (display_lines.length < 2) {
841                 return;
842         }
843
844         // Find out where the lines start from.
845         var base_line = [];
846         var base_scores = display_lines[1].scores;
847         var start_display_move_num = 0;
848         if (hash_refutation_lines) {
849                 base_line = current_display_line.pv.slice(0, current_display_move + 1);
850                 base_scores = current_display_line.scores;
851                 start_display_move_num = base_line.length;
852         }
853
854         var moves = [];
855         for (var move in refutation_lines) {
856                 moves.push(move);
857         }
858
859         var invert = (toplay === 'B');
860         if (current_display_line && current_display_move % 2 == 0 && !current_display_line_is_history) {
861                 invert = !invert;
862         }
863         moves = moves.sort(function(a, b) { return compare_by_score(refutation_lines, invert, a, b) });
864         for (var i = 0; i < moves.length; ++i) {
865                 var line = refutation_lines[moves[i]];
866
867                 var tr = document.createElement("tr");
868
869                 var move_td = document.createElement("td");
870                 tr.appendChild(move_td);
871                 move_td.classList.add("move");
872
873                 var scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
874
875                 if (line['pv'].length == 0) {
876                         // Not found, so just make a one-move PV.
877                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
878                         move_td.innerHTML = move;
879                         var score_td = document.createElement("td");
880
881                         score_td.classList.add("score");
882                         score_td.textContent = "—";
883                         tr.appendChild(score_td);
884
885                         var depth_td = document.createElement("td");
886                         tr.appendChild(depth_td);
887                         depth_td.classList.add("depth");
888                         depth_td.textContent = "—";
889
890                         var pv_td = document.createElement("td");
891                         tr.appendChild(pv_td);
892                         pv_td.classList.add("pv");
893                         pv_td.innerHTML = add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num);
894
895                         tbl.append(tr);
896                         continue;
897                 }
898
899                 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
900                 move_td.innerHTML = move;
901
902                 var score_td = document.createElement("td");
903                 tr.appendChild(score_td);
904                 score_td.classList.add("score");
905                 score_td.textContent = format_short_score(line['score']);
906
907                 var depth_td = document.createElement("td");
908                 tr.appendChild(depth_td);
909                 depth_td.classList.add("depth");
910                 if (line['depth'] && line['depth'] >= 0) {
911                         depth_td.textContent = "d" + line['depth'];
912                 } else {
913                         depth_td.textContent = "—";
914                 }
915
916                 var pv_td = document.createElement("td");
917                 tr.appendChild(pv_td);
918                 pv_td.classList.add("pv");
919                 pv_td.innerHTML = add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10);
920
921                 tbl.append(tr);
922         }
923
924         // Update the move highlight, as we've rewritten all the HTML.
925         update_move_highlight();
926 }
927
928 /**
929  * Create a Chess.js board object, containing the given position plus the given moves,
930  * up to the given limit.
931  *
932  * @param {?string} fen
933  * @param {Array.<string>} moves
934  * @param {number} last_move
935  */
936 var chess_from = function(fen, moves, last_move) {
937         var hiddenboard = new Chess();
938         if (fen !== null && fen !== undefined) {
939                 hiddenboard.load(fen);
940         }
941         for (var i = 0; i <= last_move; ++i) {
942                 if (moves[i] === '0-0') {
943                         hiddenboard.move('O-O');
944                 } else if (moves[i] === '0-0-0') {
945                         hiddenboard.move('O-O-O');
946                 } else {
947                         hiddenboard.move(moves[i]);
948                 }
949         }
950         return hiddenboard;
951 }
952
953 var update_game_list = function(games) {
954         document.getElementById("games").textContent = "";
955         if (games === null) {
956                 return;
957         }
958
959         var games_div = document.getElementById('games');
960         for (var game_num = 0; game_num < games.length; ++game_num) {
961                 var game = games[game_num];
962                 var game_span = document.createElement("span");
963                 game_span.setAttribute("class", "game");
964
965                 var game_name = document.createTextNode(game['name']);
966                 if (game['url'] === backend_url) {
967                         // This game.
968                         game_span.appendChild(game_name);
969
970                         if (current_analysis_data && current_analysis_data['position']) {
971                                 var score;
972                                 if (current_analysis_data['position']['result']) {
973                                         score = " (" + current_analysis_data['position']['result'] + ")";
974                                 } else {
975                                         score = " (" + format_short_score(current_analysis_data['score']) + ")";
976                                 }
977                                 game_span.appendChild(document.createTextNode(score));
978                         }
979                 } else {
980                         // Some other game.
981                         var game_a = document.createElement("a");
982                         game_a.setAttribute("href", "#" + game['id']);
983                         game_a.appendChild(game_name);
984                         game_span.appendChild(game_a);
985
986                         var score;
987                         if (game['result']) {
988                                 score = " (" + game['result'] + ")";
989                         } else {
990                                 score = " (" + format_short_score(game['score']) + ")";
991                         }
992                         game_span.appendChild(document.createTextNode(score));
993                 }
994
995                 games_div.appendChild(game_span);
996         }
997 }
998
999 /**
1000  * Try to find a running game that matches with the current hash,
1001  * and switch to it if we're not already displaying it.
1002  */
1003 var possibly_switch_game_from_hash = function() {
1004         var history_match = window.location.hash.match(/^#history=([a-zA-Z0-9_-]+)/);
1005         if (history_match !== null) {
1006                 var game_id = history_match[1];
1007                 var fake_game = {
1008                         url: '/history/' + game_id + '.json',
1009                         hashurl: '',
1010                         id: 'history=' + game_id
1011                 };
1012                 switch_backend(fake_game);
1013                 return;
1014         }
1015
1016         if (current_games === null) {
1017                 return;
1018         }
1019
1020         var hash = window.location.hash.replace(/^#/,'');
1021         for (var i = 0; i < current_games.length; ++i) {
1022                 if (current_games[i]['id'] === hash) {
1023                         if (backend_url !== current_games[i]['url']) {
1024                                 switch_backend(current_games[i]);
1025                         }
1026                         return;
1027                 }
1028         }
1029 }
1030
1031 /**
1032  * If this is a Chess960 castling which doesn't move the king,
1033  * move the rook instead.
1034 */
1035 var patch_move = function(move) {
1036         if (move === null) return null;
1037         if (move.from !== move.to) return move;
1038
1039         var f = move.rook_sq & 15;
1040         var r = move.rook_sq >> 4;
1041         var from = ('abcdefgh'.substring(f,f+1) + '87654321'.substring(r,r+1));
1042         var to = move.to;
1043
1044         if (move.to === 'g1') {
1045                 to = 'f1';
1046         } else if (move.to === 'g8') {
1047                 to = 'f8';
1048         } else if (move.to === 'b1') {
1049                 to = 'c1';
1050         } else if (move.to === 'b8') {
1051                 to = 'c8';
1052         }
1053
1054         return { from: from, to: to };
1055 }
1056
1057 /** Update all the HTML on the page, based on current global state.
1058  */
1059 var update_board = function() {
1060         document.body.style.opacity = null;
1061
1062         var data = displayed_analysis_data || current_analysis_data;
1063         var current_data = current_analysis_data;  // Convenience alias.
1064
1065         display_lines = [];
1066
1067         // Print the history. This is pretty much the only thing that's
1068         // unconditionally taken from current_data (we're not interested in
1069         // historic history).
1070         if (current_data['position']['history']) {
1071                 var start = (current_data['position'] && current_data['position']['start_fen']) ? current_data['position']['start_fen'] : 'start';
1072                 add_pv(start, current_data['position']['history'], 1, 'W', null, 0, 8, true);
1073         } else {
1074                 display_lines.push(null);
1075         }
1076         update_history();
1077
1078         // Games currently in progress, if any.
1079         if (current_data['games']) {
1080                 current_games = current_data['games'];
1081                 possibly_switch_game_from_hash();
1082         } else {
1083                 current_games = null;
1084         }
1085         update_game_list(current_games);
1086
1087         // The headline. Names are always fetched from current_data;
1088         // the rest can depend a bit.
1089         var headline;
1090         if (current_data &&
1091             current_data['position']['player_w'] && current_data['position']['player_b']) {
1092                 headline = current_data['position']['player_w'] + '–' +
1093                         current_data['position']['player_b'] + ', analysis';
1094         } else {
1095                 headline = 'Analysis';
1096         }
1097
1098         // Credits, where applicable. Note that we don't want the footer to change a lot
1099         // when e.g. viewing history, so if any of these changed during the game,
1100         // use the current one still.
1101         if (current_data['using_lomonosov']) {
1102                 document.getElementById("lomonosov").style.display = null;
1103         } else {
1104                 document.getElementById("lomonosov").style.display = 'none';
1105         }
1106
1107         // Credits: The engine name/version.
1108         if (current_data['engine'] && current_data['engine']['name'] !== null) {
1109                 document.getElementById("engineid").textContent = current_data['engine']['name'];
1110         }
1111
1112         // Credits: The engine URL.
1113         if (current_data['engine'] && current_data['engine']['url']) {
1114                 document.getElementById("engineid").setAttribute("href", current_data['engine']['url']);
1115         } else {
1116                 document.getElementById("engineid").removeAttribute("href");
1117         }
1118
1119         // Credits: Engine details.
1120         if (current_data['engine'] && current_data['engine']['details']) {
1121                 document.getElementById("enginedetails").textContent = " (" + current_data['engine']['details'] + ")";
1122         } else {
1123                 document.getElementById("enginedetails").textContent = "";
1124         }
1125
1126         // Credits: Move source, possibly with URL.
1127         if (current_data['move_source'] && current_data['move_source_url']) {
1128                 document.getElementById("movesource").textContent = "Moves provided by ";
1129                 var movesource_a = document.createElement("a");
1130                 movesource_a.setAttribute("href", current_data['move_source_url']);
1131                 var movesource_text = document.createTextNode(current_data['move_source']);
1132                 movesource_a.appendChild(movesource_text);
1133                 var movesource_period = document.createTextNode(".");
1134                 document.getElementById("movesource").appendChild(movesource_a);
1135                 document.getElementById("movesource").appendChild(movesource_period);
1136         } else if (current_data['move_source']) {
1137                 document.getElementById("movesource").textContent = "Moves provided by " + current_data['move_source'] + ".";
1138         } else {
1139                 document.getElementById("movesource").textContent = "";
1140         }
1141
1142         var last_move;
1143         if (displayed_analysis_data) {
1144                 // Displaying some non-current position, pick out the last move
1145                 // from the history. This will work even if the fetch failed.
1146                 if (current_display_move !== -1) {
1147                         last_move = format_halfmove_with_number(
1148                                 current_display_line.pv[current_display_move],
1149                                 current_display_move);
1150                         headline += ' after ' + last_move;
1151                 }
1152         } else if (data['position']['last_move'] !== 'none') {
1153                 // Find the previous move.
1154                 var previous_move_num, previous_toplay;
1155                 if (data['position']['toplay'] == 'B') {
1156                         previous_move_num = data['position']['move_num'];
1157                         previous_toplay = 'W';
1158                 } else {
1159                         previous_move_num = data['position']['move_num'] - 1;
1160                         previous_toplay = 'B';
1161                 }
1162
1163                 last_move = format_move_with_number(
1164                         data['position']['last_move'],
1165                         previous_move_num,
1166                         previous_toplay == 'W');
1167                 headline += ' after ' + last_move;
1168         } else {
1169                 last_move = null;
1170         }
1171         document.getElementById("headline").textContent = headline;
1172
1173         // The <title> contains a very brief headline.
1174         var title_elems = [];
1175         if (data['position'] && data['position']['result']) {
1176                 title_elems.push(data['position']['result']);
1177         } else if (data['score']) {
1178                 title_elems.push(format_short_score(data['score']));
1179         }
1180         if (last_move !== null) {
1181                 title_elems.push(last_move);
1182         }
1183
1184         if (title_elems.length != 0) {
1185                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1186         } else {
1187                 document.title = 'analysis.sesse.net';
1188         }
1189
1190         // The last move (shown by highlighting the from and to squares).
1191         if (data['position'] && data['position']['last_move_uci']) {
1192                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1193                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1194         } else if (current_display_line_is_history && current_display_line && current_display_move >= 0) {
1195                 // We don't have historic analysis for this position, but we
1196                 // can reconstruct what the last move was by just replaying
1197                 // from the start.
1198                 var position = (data['position'] && data['position']['start_fen']) ? data['position']['start_fen'] : null;
1199                 var hiddenboard = chess_from(position, current_display_line.pv, current_display_move);
1200                 var moves = hiddenboard.history({ verbose: true });
1201                 last_move = moves.pop();
1202                 highlight_from = last_move.from;
1203                 highlight_to = last_move.to;
1204         } else {
1205                 highlight_from = highlight_to = undefined;
1206         }
1207         update_board_highlight();
1208
1209         if (data['failed']) {
1210                 document.getElementById("score").textContent = "No analysis for this move";
1211                 document.getElementById("pvtitle").textContent = "PV:";
1212                 document.getElementById("pv").replaceChildren();
1213                 document.getElementById("searchstats").innerHTML = "&nbsp;";
1214                 document.getElementById("refutationlines").replaceChildren();
1215                 document.getElementById("whiteclock").replaceChildren();
1216                 document.getElementById("blackclock").replaceChildren();
1217                 refutation_lines = [];
1218                 update_refutation_lines();
1219                 clear_arrows();
1220                 update_displayed_line();
1221                 update_move_highlight();
1222                 return;
1223         }
1224
1225         update_clock();
1226
1227         // The score.
1228         if (current_display_line && !current_display_line_is_history) {
1229                 var score;
1230                 if (current_display_line.scores && current_display_line.scores.length > 0) {
1231                         for (var i = 0; i < current_display_line.scores.length; ++i) {
1232                                 if (current_display_move < current_display_line.scores[i].first_move) {
1233                                         break;
1234                                 }
1235                                 score = current_display_line.scores[i].score;
1236                         }
1237                 }
1238                 if (score) {
1239                         document.getElementById("score").textContent = format_long_score(score);
1240                 } else {
1241                         document.getElementById("score").textContent = "No score for this line";
1242                 }
1243         } else if (data['score']) {
1244                 document.getElementById("score").textContent = format_long_score(data['score']);
1245         }
1246
1247         // The search stats.
1248         if (data['searchstats']) {
1249                 document.getElementById("searchstats").innerHTML = data['searchstats'];
1250         } else if (data['tablebase'] == 1) {
1251                 document.getElementById("searchstats").textContent = "Tablebase result";
1252         } else if (data['nodes'] && data['nps'] && data['depth']) {
1253                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1254                 if (data['seldepth']) {
1255                         stats += ' (' + data['seldepth'] + ' selective)';
1256                 }
1257                 if (data['tbhits'] && data['tbhits'] > 0) {
1258                         if (data['tbhits'] == 1) {
1259                                 stats += ', one Syzygy hit';
1260                         } else {
1261                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1262                         }
1263                 }
1264
1265                 document.getElementById("searchstats").textContent = stats;
1266         } else {
1267                 document.getElementById("searchstats").textContent = "";
1268         }
1269
1270         // Update the board itself.
1271         base_fen = data['position']['fen'];
1272         update_displayed_line();
1273
1274         // Print the PV.
1275         document.getElementById("pvtitle").textContent = "PV:";
1276
1277         var scores = [{ first_move: -1, score: data['score'] }];
1278         document.getElementById("pv").innerHTML = add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0);
1279
1280         // Update the PV arrow.
1281         clear_arrows();
1282         if (data['pv'].length >= 1) {
1283                 var hiddenboard = new Chess(base_fen);
1284
1285                 // draw a continuation arrow as long as it's the same piece
1286                 var last_to;
1287                 for (var i = 0; i < data['pv'].length; i += 2) {
1288                         var move = patch_move(hiddenboard.move(data['pv'][i]));
1289
1290                         if ((i >= 2 && move.from != last_to) ||
1291                              interfering_arrow(move.from, move.to)) {
1292                                 break;
1293                         }
1294                         create_arrow(move.from, move.to, '#f66', 6, 20);
1295                         last_to = move.to;
1296                         hiddenboard.move(data['pv'][i + 1]);  // To keep continuity.
1297                 }
1298
1299                 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1300                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1301                         hiddenboard = new Chess(base_fen);
1302                         var move = patch_move(hiddenboard.move(alt_moves[i]));
1303                         if (move !== null) {
1304                                 create_arrow(move.from, move.to, '#f66', 1, 10);
1305                         }
1306                 }
1307         }
1308
1309         // See if all semi-reasonable moves have only one possible response.
1310         if (data['pv'].length >= 2) {
1311                 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1312                 var response;
1313                 {
1314                         var hiddenboard = new Chess(base_fen);
1315                         hiddenboard.move(data['pv'][0]);
1316                         response = hiddenboard.move(data['pv'][1]);
1317                 }
1318                 for (var i = 0; i < nonstupid_moves.length; ++i) {
1319                         if (nonstupid_moves[i] == data['pv'][0]) {
1320                                 // ignore the PV move for refutation lines.
1321                                 continue;
1322                         }
1323                         if (!data['refutation_lines'] ||
1324                             !data['refutation_lines'][nonstupid_moves[i]] ||
1325                             !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1326                             data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 2) {
1327                                 // Incomplete PV, abort.
1328                                 response = undefined;
1329                                 break;
1330                         }
1331                         var line = data['refutation_lines'][nonstupid_moves[i]];
1332                         hiddenboard = new Chess(base_fen);
1333                         hiddenboard.move(line['pv'][0]);
1334                         var this_response = hiddenboard.move(line['pv'][1]);
1335                         if (this_response === null) {
1336                                 console.log("BUG: ", i);
1337                                 console.log(data);
1338                                 console.log(line['pv']);
1339                         }
1340                         if (response.from !== this_response.from || response.to !== this_response.to) {
1341                                 // Different response depending on lines, abort.
1342                                 response = undefined;
1343                                 break;
1344                         }
1345                 }
1346
1347                 if (nonstupid_moves.length > 0 && response !== undefined) {
1348                         create_arrow(response.from, response.to, '#66f', 6, 20);
1349                 }
1350         }
1351
1352         // Update the refutation lines.
1353         base_fen = data['position']['fen'];
1354         move_num = parseInt(data['position']['move_num']);
1355         toplay = data['position']['toplay'];
1356         refutation_lines = hash_refutation_lines || data['refutation_lines'];
1357         update_refutation_lines();
1358
1359         // Update the sparkline last, since its size depends on how everything else reflowed.
1360         update_sparkline(data);
1361 }
1362
1363 var update_sparkline = function(data) {
1364         if (data && data['score_history']) {
1365                 var first_move_num = undefined;
1366                 for (var halfmove_num in data['score_history']) {
1367                         halfmove_num = parseInt(halfmove_num);
1368                         if (first_move_num === undefined || halfmove_num < first_move_num) {
1369                                 first_move_num = halfmove_num;
1370                         }
1371                 }
1372                 if (first_move_num !== undefined) {
1373                         var last_move_num = data['position']['move_num'] * 2 - 3;
1374                         if (data['position']['toplay'] === 'B') {
1375                                 ++last_move_num;
1376                         }
1377
1378                         // Possibly truncate some moves if we don't have enough width.
1379                         // FIXME: Sometimes width() for #scorecontainer (and by extent,
1380                         // #scoresparkcontainer) on Chrome for mobile seems to start off
1381                         // at something very small, and then suddenly snap back into place.
1382                         // Figure out why.
1383                         var max_moves = Math.floor(document.getElementById("scoresparkcontainer").getBoundingClientRect().width / 5) - 5;
1384                         if (last_move_num - first_move_num > max_moves) {
1385                                 first_move_num = last_move_num - max_moves;
1386                         }
1387
1388                         var min_score = -100;
1389                         var max_score = 100;
1390                         var last_score = null;
1391                         var scores = [];
1392                         for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1393                                 if (data['score_history'][halfmove_num]) {
1394                                         var score = compute_plot_score(data['score_history'][halfmove_num]);
1395                                         last_score = score;
1396                                         if (score < min_score) min_score = score;
1397                                         if (score > max_score) max_score = score;
1398                                 }
1399                                 scores.push(last_score);
1400                         }
1401                         if (data['score']) {
1402                                 scores.push(compute_plot_score(data['score']));
1403                         }
1404                         // FIXME: at some widths, calling sparkline() seems to push
1405                         // #scorecontainer under the board.
1406                         $('#scorespark').unbind('sparklineClick');
1407                         $('#scorespark').sparkline(scores, {
1408                                 type: 'bar',
1409                                 zeroColor: 'gray',
1410                                 chartRangeMin: min_score,
1411                                 chartRangeMax: max_score,
1412                                 tooltipFormatter: function(sparkline, options, fields) {
1413                                         // score_history contains the Nth _position_, but format_tooltip
1414                                         // wants to format the Nth _move_; thus the -1.
1415                                         return format_tooltip(data, fields[0].offset + first_move_num - 1);
1416                                 }
1417                         });
1418                         $('#scorespark').unbind('sparklineClick');
1419                         $('#scorespark').bind('sparklineClick', function(event) {
1420                                 var sparkline = event.sparklines[0];
1421                                 var region = sparkline.getCurrentRegionFields();
1422                                 if (region[0].offset !== undefined) {
1423                                         show_line(0, first_move_num + region[0].offset - 1);
1424                                 }
1425                         });
1426                 } else {
1427                         document.getElementById("scorespark").textContent = "";
1428                 }
1429         } else {
1430                 document.getElementById("scorespark").textContent = "";
1431         }
1432 }
1433
1434 /**
1435  * @param {number} num_viewers
1436  */
1437 var update_num_viewers = function(num_viewers) {
1438         var text = "";
1439         if (num_viewers === null) {
1440                 text = "";
1441         } else if (num_viewers == 1) {
1442                 text = "You are the only current viewer";
1443         } else {
1444                 text = num_viewers + " current viewers";
1445         }
1446         if (display_fen !== null) {
1447                 var counter = Math.floor(display_fen.split(" ")[4] / 2);
1448                 if (counter >= 20) {
1449                         text = text.replace("current ", "");
1450                         text += " | 50-move rule: " + counter;
1451                 }
1452         }
1453         document.getElementById("numviewers").textContent = text;
1454 }
1455
1456 var update_clock = function() {
1457         clearTimeout(clock_timer);
1458
1459         var data = displayed_analysis_data || current_analysis_data;
1460         if (!data) return;
1461
1462         if (data['position']) {
1463                 var result = data['position']['result'];
1464                 if (result === '1-0') {
1465                         document.getElementById("whiteclock").textContent = "1";
1466                         document.getElementById("blackclock").textContent = "0";
1467                         document.getElementById("whiteclock").classList.remove("running-clock");
1468                         document.getElementById("blackclock").classList.remove("running-clock");
1469                         return;
1470                 }
1471                 if (result === '1/2-1/2') {
1472                         document.getElementById("whiteclock").textContent = "1/2";
1473                         document.getElementById("blackclock").textContent = "1/2";
1474                         document.getElementById("whiteclock").classList.remove("running-clock");
1475                         document.getElementById("blackclock").classList.remove("running-clock");
1476                         return;
1477                 }       
1478                 if (result === '0-1') {
1479                         document.getElementById("whiteclock").textContent = "0";
1480                         document.getElementById("blackclock").textContent = "1";
1481                         document.getElementById("whiteclock").classList.remove("running-clock");
1482                         document.getElementById("blackclock").classList.remove("running-clock");
1483                         return;
1484                 }
1485         }
1486
1487         var white_clock_ms = null;
1488         var black_clock_ms = null;
1489
1490         // Static clocks.
1491         if (data['position'] &&
1492             data['position']['white_clock'] &&
1493             data['position']['black_clock']) {
1494                 white_clock_ms = data['position']['white_clock'] * 1000;
1495                 black_clock_ms = data['position']['black_clock'] * 1000;
1496         }
1497
1498         // Dynamic clock (only one, obviously).
1499         var color;
1500         if (data['position']['white_clock_target']) {
1501                 color = "white";
1502                 document.getElementById("whiteclock").classList.add("running-clock");
1503                 document.getElementById("blackclock").classList.remove("running-clock");
1504         } else if (data['position']['black_clock_target']) {
1505                 color = "black";
1506                 document.getElementById("whiteclock").classList.remove("running-clock");
1507                 document.getElementById("blackclock").classList.add("running-clock");
1508         } else {
1509                 document.getElementById("whiteclock").classList.remove("running-clock");
1510                 document.getElementById("blackclock").classList.remove("running-clock");
1511         }
1512         var remaining_ms;
1513         if (color) {
1514                 var now = new Date().getTime() + client_clock_offset_ms;
1515                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1516                 if (color === "white") {
1517                         white_clock_ms = remaining_ms;
1518                 } else {
1519                         black_clock_ms = remaining_ms;
1520                 }
1521         }
1522
1523         if (white_clock_ms === null || black_clock_ms === null) {
1524                 document.getElementById("whiteclock").replaceChildren();
1525                 document.getElementById("blackclock").replaceChildren();
1526                 return;
1527         }
1528
1529         // If either player has twenty minutes or less left, add the second counters.
1530         // This matches what DGT clocks do.
1531         var show_seconds = (white_clock_ms < 60 * 20 * 1000 || black_clock_ms < 60 * 20 * 1000);
1532
1533         if (color) {
1534                 // See when the clock will change next, and update right after that.
1535                 var next_update_ms;
1536                 if (show_seconds) {
1537                         next_update_ms = remaining_ms % 1000 + 100;
1538                 } else {
1539                         next_update_ms = remaining_ms % 60000 + 100;
1540                 }
1541                 clock_timer = setTimeout(update_clock, next_update_ms);
1542         }
1543
1544         document.getElementById("whiteclock").textContent = format_clock(white_clock_ms, show_seconds);
1545         document.getElementById("blackclock").textContent = format_clock(black_clock_ms, show_seconds);
1546 }
1547
1548 /**
1549  * @param {Number} remaining_ms
1550  * @param {boolean} show_seconds
1551  */
1552 var format_clock = function(remaining_ms, show_seconds) {
1553         if (remaining_ms <= 0) {
1554                 if (show_seconds) {
1555                         return "00:00:00";
1556                 } else {
1557                         return "00:00";
1558                 }
1559         }
1560
1561         var remaining = Math.floor(remaining_ms / 1000);
1562         var seconds = remaining % 60;
1563         remaining = (remaining - seconds) / 60;
1564         var minutes = remaining % 60;
1565         remaining = (remaining - minutes) / 60;
1566         var hours = remaining;
1567         if (show_seconds) {
1568                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1569         } else {
1570                 return format_2d(hours) + ":" + format_2d(minutes);
1571         }
1572 }
1573
1574 /**
1575  * @param {Number} x
1576  */
1577 var format_2d = function(x) {
1578         if (x >= 10) {
1579                 return x;
1580         } else {
1581                 return "0" + x;
1582         }
1583 }
1584
1585 /**
1586  * @param {string} move
1587  * @param {Number} move_num Move number of this move.
1588  * @param {boolean} white_to_play Whether white is to play this move.
1589  */
1590 var format_move_with_number = function(move, move_num, white_to_play) {
1591         var ret;
1592         if (white_to_play) {
1593                 ret = move_num + '. ';
1594         } else {
1595                 ret = move_num + '… ';
1596         }
1597         ret += move;
1598         return ret;
1599 }
1600
1601 /**
1602  * @param {string} move
1603  * @param {Number} halfmove_num Half-move number that is to be played,
1604  *   starting from 0.
1605  */
1606 var format_halfmove_with_number = function(move, halfmove_num) {
1607         return format_move_with_number(
1608                 move,
1609                 Math.floor(halfmove_num / 2) + 1,
1610                 halfmove_num % 2 == 0);
1611 }
1612
1613 /**
1614  * @param {Object} data
1615  * @param {Number} halfmove_num
1616  */
1617 var format_tooltip = function(data, halfmove_num) {
1618         if (data['score_history'][halfmove_num + 1] ||
1619             (halfmove_num + 1) === data['position']['history'].length) {
1620                 // Position is in the history, or it is the current position
1621                 // (which is implicitly tacked onto the history).
1622                 var move;
1623                 var short_score;
1624                 if ((halfmove_num + 1) === data['position']['history'].length) {
1625                         move = data['position']['last_move'];
1626                         short_score = format_short_score(data['score']);
1627                 } else {
1628                         move = data['position']['history'][halfmove_num];
1629                         short_score = format_short_score(data['score_history'][halfmove_num + 1]);
1630                 }
1631                 if (halfmove_num === -1) {
1632                         return "Start position: " + short_score;
1633                 } else {
1634                         var move_with_number = format_halfmove_with_number(move, halfmove_num);
1635                         return "After " + move_with_number + ": " + short_score;
1636                 }
1637         } else {
1638                 for (var i = halfmove_num; i --> -1; ) {
1639                         if (data['score_history'][i]) {
1640                                 var move = data['position']['history'][i];
1641                                 if (i === -1) {
1642                                         return "[Analysis kept from start position]";
1643                                 } else {
1644                                         return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1645                                 }
1646                         }
1647                 }
1648         }
1649 }
1650
1651 /**
1652  * @param {boolean} truncate_history
1653  */
1654 var set_truncate_history = function(truncate_history) {
1655         truncate_display_history = truncate_history;
1656         update_refutation_lines();
1657 }
1658 window['set_truncate_history'] = set_truncate_history;
1659
1660 /**
1661  * @param {number} line_num
1662  * @param {number} move_num
1663  */
1664 var show_line = function(line_num, move_num) {
1665         if (line_num == -1) {
1666                 current_display_line = null;
1667                 current_display_move = null;
1668                 hash_refutation_lines = null;
1669                 if (displayed_analysis_data) {
1670                         // TODO: Support exiting to history position if we are in an
1671                         // analysis line of a history position.
1672                         displayed_analysis_data = null;
1673                 }
1674                 update_board();
1675                 return;
1676         } else {
1677                 current_display_line = {...display_lines[line_num]};  // Shallow clone.
1678                 current_display_move = move_num + current_display_line.start_display_move_num;
1679         }
1680         current_display_line_is_history = (line_num == 0);
1681
1682         update_historic_analysis();
1683         update_displayed_line();
1684         update_board_highlight();
1685         update_move_highlight();
1686         redraw_arrows();
1687 }
1688 window['show_line'] = show_line;
1689
1690 var prev_move = function() {
1691         if (current_display_line &&
1692             current_display_move >= current_display_line.start_display_move_num) {
1693                 --current_display_move;
1694         }
1695         update_historic_analysis();
1696         update_displayed_line();
1697         update_move_highlight();
1698 }
1699 window['prev_move'] = prev_move;
1700
1701 var next_move = function() {
1702         if (current_display_line &&
1703             current_display_move < current_display_line.pv.length - 1) {
1704                 ++current_display_move;
1705         }
1706         update_historic_analysis();
1707         update_displayed_line();
1708         update_move_highlight();
1709 }
1710 window['next_move'] = next_move;
1711
1712 var next_game = function() {
1713         if (current_games === null) {
1714                 return;
1715         }
1716
1717         // Try to find the game we are currently looking at.
1718         for (var game_num = 0; game_num < current_games.length; ++game_num) {
1719                 var game = current_games[game_num];
1720                 if (game['url'] === backend_url) {
1721                         var next_game_num = (game_num + 1) % current_games.length;
1722                         switch_backend(current_games[next_game_num]);
1723                         return;
1724                 }
1725         }
1726
1727         // Couldn't find it; give up.
1728 }
1729
1730 var update_historic_analysis = function() {
1731         if (!current_display_line_is_history) {
1732                 return;
1733         }
1734         if (current_display_move == current_display_line.pv.length - 1) {
1735                 displayed_analysis_data = null;
1736                 update_board();
1737         }
1738
1739         // Fetch old analysis for this line if it exists.
1740         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1741         var filename = "/history/move" + (current_display_move + 1) + "-" +
1742                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1743
1744         let handle_err = () => {
1745                 displayed_analysis_data = {'failed': true};
1746                 update_board();
1747         };
1748
1749         current_historic_xhr = new AbortController();
1750         const signal = current_analysis_xhr.signal;
1751         fetch(filename, { signal })
1752                 .then((response) => response.json().then(data => ({ok: response.ok, json: data})))  // ick
1753                 .then((obj) => {
1754                         if (!obj.ok) {
1755                                 handle_err();
1756                                 return;
1757                         }
1758                         displayed_analysis_data = obj.json;
1759                         update_board();
1760                 })
1761                 .catch((err) => {
1762                         if (err.name === 'AbortError') {
1763                                 // Aborted because we are switching backends. Abandon and don't retry,
1764                                 // because another one is already started for us.
1765                         } else {
1766                                 console.log(err);
1767                                 handle_err();
1768                         }
1769                 });
1770 }
1771
1772 /**
1773  * @param {string} fen
1774  */
1775 var update_imbalance = function(fen) {
1776         var hiddenboard = new Chess(fen);
1777         var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1778         for (var row = 0; row < 8; ++row) {
1779                 for (var col = 0; col < 8; ++col) {
1780                         var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1781                         var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1782                         var square = col_text + row_text;
1783                         var contents = hiddenboard.get(square);
1784                         if (contents !== null) {
1785                                 if (contents.color === 'w') {
1786                                         ++imbalance[contents.type];
1787                                 } else {
1788                                         --imbalance[contents.type];
1789                                 }
1790                         }
1791                 }
1792         }
1793         var white_imbalance = '';
1794         var black_imbalance = '';
1795         for (var piece in imbalance) {
1796                 for (var i = 0; i < imbalance[piece]; ++i) {
1797                         white_imbalance += '<img src="' + svg_pieces['w' + piece.toUpperCase()] + '" alt="" style="width: 15px;height: 15px;" class="imbalance-piece">';
1798                         white_imbalance += '<img src="' + svg_pieces['b' + piece.toUpperCase()] + '" alt="" style="width: 15px;height: 15px;" class="imbalance-inverted-piece">';
1799                 }
1800                 for (var i = 0; i < -imbalance[piece]; ++i) {
1801                         black_imbalance += '<img src="' + svg_pieces['b' + piece.toUpperCase()] + '" alt="" style="width: 15px;height: 15px;" class="imbalance-piece">';
1802                         black_imbalance += '<img src="' + svg_pieces['w' + piece.toUpperCase()] + '" alt="" style="width: 15px;height: 15px;" class="imbalance-inverted-piece">';
1803                 }
1804         }
1805         document.getElementById('whiteimbalance').innerHTML = white_imbalance;
1806         document.getElementById('blackimbalance').innerHTML = black_imbalance;
1807 }
1808
1809 /** Mark the currently selected move in red.
1810  * Also replaces the PV with the current displayed line if it's not shown
1811  * anywhere else on the screen.
1812  */
1813 var update_move_highlight = function() {
1814         if (highlighted_move !== null) {
1815                 highlighted_move.classList.remove('highlight'); 
1816         }
1817         if (current_display_line) {
1818                 var display_line_num = find_display_line_matching_num();
1819                 if (display_line_num === null) {
1820                         // Replace the PV with the (complete) line.
1821                         document.getElementById("pvtitle").textContent = "Exploring:";
1822                         current_display_line.start_display_move_num = 0;
1823                         display_lines.push(current_display_line);
1824                         document.getElementById("pv").innerHTML = print_pv(display_lines.length - 1, null);  // FIXME
1825                         display_line_num = display_lines.length - 1;
1826
1827                         // Clear out the PV, so it's not selected by anything later.
1828                         display_lines[1].pv = [];
1829                 }
1830
1831                 highlighted_move = document.getElementById("automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1832                 if (highlighted_move !== null) {
1833                         highlighted_move.classList.add('highlight');
1834                 }
1835         }
1836 }
1837
1838 /**
1839  * See if the current displayed line is identical to any of the ones
1840  * we have on screen. (It might not be if e.g. the analysis reloaded
1841  * since we started looking.)
1842  *
1843  * @return {?number}
1844  */
1845 var find_display_line_matching_num = function() {
1846         for (var i = 0; i < display_lines.length; ++i) {
1847                 var line = display_lines[i];
1848                 if (line.start_display_move_num > 0) continue;
1849                 if (current_display_line.start_fen !== line.start_fen) continue;
1850                 if (current_display_line.pv.length !== line.pv.length) continue;
1851                 var ok = true;
1852                 for (var j = 0; j < line.pv.length; ++j) {
1853                         if (current_display_line.pv[j] !== line.pv[j]) {
1854                                 ok = false;
1855                                 break;
1856                         }
1857                 }
1858                 if (ok) {
1859                         return i;
1860                 }
1861         }
1862         return null;
1863 }
1864
1865 /** Update the board based on the currently displayed line.
1866  * 
1867  * TODO: This should really be called only whenever something changes,
1868  * instead of all the time.
1869  */
1870 var update_displayed_line = function() {
1871         if (current_display_line === null) {
1872                 document.getElementById("linenav").style.display = 'none';
1873                 document.getElementById("linemsg").style.display = 'revert';
1874                 display_fen = base_fen;
1875                 set_board_position(base_fen);
1876                 update_imbalance(base_fen);
1877                 return;
1878         }
1879
1880         document.getElementById("linenav").style.display = 'revert';
1881         document.getElementById("linemsg").style.display = 'none';
1882
1883         if (current_display_move <= 0) {
1884                 document.getElementById("prevmove").innerHTML = "Previous";
1885         } else {
1886                 document.getElementById("prevmove").innerHTML = "<a href=\"javascript:prev_move();\">Previous</a></span>";
1887         }
1888         if (current_display_move == current_display_line.pv.length - 1) {
1889                 document.getElementById("nextmove").innerHTML = "Next";
1890         } else {
1891                 document.getElementById("nextmove").innerHTML = "<a href=\"javascript:next_move();\">Next</a></span>";
1892         }
1893
1894         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1895         set_board_position(hiddenboard.fen());
1896         if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1897                 // Fire off a hash request, since we're now off the main position
1898                 // and it just changed.
1899                 explore_hash(hiddenboard.fen());
1900         }
1901         display_fen = hiddenboard.fen();
1902         update_imbalance(hiddenboard.fen());
1903 }
1904
1905 var set_board_position = function(new_fen) {
1906         board_is_animating = true;
1907         var old_fen = board.fen();
1908         board.position(new_fen);
1909         if (board.fen() === old_fen) {
1910                 board_is_animating = false;
1911         }
1912 }
1913
1914 /**
1915  * @param {boolean} param_enable_sound
1916  */
1917 var set_sound = function(param_enable_sound) {
1918         enable_sound = param_enable_sound;
1919         if (enable_sound) {
1920                 document.getElementById("soundon").innerHTML = "<strong>On</strong>";
1921                 document.getElementById("soundoff").innerHTML = "<a href=\"javascript:set_sound(false)\">Off</a>";
1922
1923                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1924                 // and also preload the file since the user has selected audio.
1925                 var ding = document.getElementById('ding');
1926                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1927                         ding.src = 'ding.opus';
1928                         ding.load();
1929                 }
1930         } else {
1931                 document.getElementById("soundon").innerHTML = "<a href=\"javascript:set_sound(true)\">On</a>";
1932                 document.getElementById("soundoff").innerHTML = "<strong>Off</strong>";
1933         }
1934         if (supports_html5_storage()) {
1935                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1936         }
1937 }
1938 window['set_sound'] = set_sound;
1939
1940 /** Send off a hash probe request to the backend.
1941  * @param {string} fen
1942  */
1943 var explore_hash = function(fen) {
1944         // If we already have a backend response going, abort it.
1945         if (current_hash_xhr) {
1946                 current_hash_xhr.abort();
1947         }
1948         if (current_hash_display_timer) {
1949                 clearTimeout(current_hash_display_timer);
1950                 current_hash_display_timer = null;
1951         }
1952         document.getElementById("refutationlines").replaceChildren();
1953
1954         current_hash_xhr = new AbortController();
1955         const signal = current_analysis_xhr.signal;
1956         fetch(backend_hash_url + "?fen=" + fen, { signal })
1957                 .then((response) => response.json())
1958                 .then((data) => { show_explore_hash_results(data, fen); });
1959 }
1960
1961 /** Process the JSON response from a hash probe request.
1962  * @param {!Object} data
1963  * @param {string} fen
1964  */
1965 var show_explore_hash_results = function(data, fen) {
1966         if (board_is_animating) {
1967                 // Updating while the animation is still going causes
1968                 // the animation to jerk. This is pretty crude, but it will do.
1969                 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1970                 return;
1971         }
1972         current_hash_display_timer = null;
1973         hash_refutation_lines = data['lines'];
1974         update_board();
1975 }
1976
1977 // almost all of this stuff comes from the chessboard.js example page
1978 var onDragStart = function(source, piece, position, orientation) {
1979         var pseudogame = new Chess(display_fen);
1980         if (pseudogame.game_over() === true ||
1981             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1982             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1983                 return false;
1984         }
1985
1986         recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1987         if (recommended_move) {
1988                 var squareEl = document.querySelector('#board .square-' + recommended_move.to);
1989                 squareEl.classList.add('highlight1-32417');
1990         }
1991         return true;
1992 }
1993
1994 var mousedownSquare = function(e) {
1995         if (!e.target || !e.target.matches('.square-55d63')) {
1996                 return;
1997         }
1998
1999         reverse_dragging_from = null;
2000         var square = e.target.getAttribute('data-square');
2001
2002         var pseudogame = new Chess(display_fen);
2003         if (pseudogame.game_over() === true) {
2004                 return;
2005         }
2006
2007         // If the square is empty, or has a piece of the side not to move,
2008         // we handle it. If not, normal piece dragging will take it.
2009         var position = board.position();
2010         if (!position.hasOwnProperty(square) ||
2011             (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
2012             (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
2013                 reverse_dragging_from = square;
2014                 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
2015                 if (recommended_move) {
2016                         var squareEl = document.querySelector('#board .square-' + recommended_move.from);
2017                         squareEl.classList.add('highlight1-32417');
2018                         squareEl = document.querySelector('#board .square-' + recommended_move.to);
2019                         squareEl.classList.add('highlight1-32417');
2020                 }
2021         }
2022 }
2023
2024 var mouseupSquare = function(e) {
2025         if (!e.target || !e.target.matches('.square-55d63')) {
2026                 return;
2027         }
2028         if (reverse_dragging_from === null) {
2029                 return;
2030         }
2031         var source = e.target.getAttribute('data-square');
2032         var target = reverse_dragging_from;
2033         reverse_dragging_from = null;
2034         if (onDrop(source, target) !== 'snapback') {
2035                 onSnapEnd(source, target);
2036         }
2037         document.getElementById("board").querySelectorAll('.square-55d63.highlight1-32417').forEach((square) => {
2038                 square.classList.remove('highlight1-32417');
2039         });
2040 }
2041
2042 var get_best_move = function(game, source, target, invert) {
2043         var moves = game.moves({ verbose: true });
2044         if (source !== null) {
2045                 moves = moves.filter(function(move) { return move.from == source; });
2046         }
2047         if (target !== null) {
2048                 moves = moves.filter(function(move) { return move.to == target; });
2049         }
2050         if (moves.length == 0) {
2051                 return null;
2052         }
2053         if (moves.length == 1) {
2054                 return moves[0];
2055         }
2056
2057         // More than one move. Use the display lines (if we have them)
2058         // to disambiguate; otherwise, we have no information.
2059         var move_hash = {};
2060         for (var i = 0; i < moves.length; ++i) {
2061                 move_hash[moves[i].san] = moves[i];
2062         }
2063
2064         // See if we're already exploring some line.
2065         if (current_display_line &&
2066             current_display_move < current_display_line.pv.length - 1) {
2067                 var first_move = current_display_line.pv[current_display_move + 1];
2068                 if (move_hash[first_move]) {
2069                         return move_hash[first_move];
2070                 }
2071         }
2072
2073         // History and PV take priority over the display lines.
2074         for (var i = 0; i < 2; ++i) {
2075                 var line = display_lines[i];
2076                 var first_move = line.pv[line.start_display_move_num];
2077                 if (move_hash[first_move]) {
2078                         return move_hash[first_move];
2079                 }
2080         }
2081
2082         var best_move = null;
2083         var best_move_score = null;
2084
2085         for (var move in refutation_lines) {
2086                 var line = refutation_lines[move];
2087                 if (!line['score']) {
2088                         continue;
2089                 }
2090                 var first_move = line['pv'][0];
2091                 if (move_hash[first_move]) {
2092                         var score = compute_score_sort_key(line['score'], line['depth'], invert);
2093                         if (best_move_score === null || score > best_move_score) {
2094                                 best_move = move_hash[first_move];
2095                                 best_move_score = score;
2096                         }
2097                 }
2098         }
2099         return best_move;
2100 }
2101
2102 var onDrop = function(source, target) {
2103         if (source === target) {
2104                 if (recommended_move === null) {
2105                         return 'snapback';
2106                 } else {
2107                         // Accept the move. It will be changed in onSnapEnd.
2108                         return;
2109                 }
2110         } else {
2111                 // Suggestion not asked for.
2112                 recommended_move = null;
2113         }
2114
2115         // see if the move is legal
2116         var pseudogame = new Chess(display_fen);
2117         var move = pseudogame.move({
2118                 from: source,
2119                 to: target,
2120                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2121         });
2122
2123         // illegal move
2124         if (move === null) return 'snapback';
2125 }
2126
2127 var onSnapEnd = function(source, target) {
2128         if (source === target && recommended_move !== null) {
2129                 source = recommended_move.from;
2130                 target = recommended_move.to;
2131         }
2132         recommended_move = null;
2133         var pseudogame = new Chess(display_fen);
2134         var move = pseudogame.move({
2135                 from: source,
2136                 to: target,
2137                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2138         });
2139
2140         if (current_display_line &&
2141             current_display_move < current_display_line.pv.length - 1 &&
2142             current_display_line.pv[current_display_move + 1] === move.san) {
2143                 next_move();
2144                 return;
2145         }
2146
2147         // Walk down the displayed lines until we find one that starts with
2148         // this move, then select that. Note that this gives us a good priority
2149         // order (history first, then PV, then multi-PV lines).
2150         for (var i = 0; i < display_lines.length; ++i) {
2151                 if (i == 1 && current_display_line) {
2152                         // Do not choose PV if not on it.
2153                         continue;
2154                 }
2155                 var line = display_lines[i];
2156                 if (line.pv[line.start_display_move_num] === move.san) {
2157                         show_line(i, 0);
2158                         return;
2159                 }
2160         }
2161
2162         // Shouldn't really be here if we have hash probes, but there's really
2163         // nothing we can do.
2164 }
2165 // End of dragging-related code.
2166
2167 var fmt_cp = function(v) {
2168         if (v === 0) {
2169                 return "0.00";
2170         } else if (v > 0) {
2171                 return "+" + (v / 100).toFixed(2);
2172         } else {
2173                 v = -v;
2174                 return "-" + (v / 100).toFixed(2);
2175         }
2176 }
2177
2178 var format_short_score = function(score) {
2179         if (!score) {
2180                 return "???";
2181         }
2182         if (score[0] === 'T' || score[0] === 't') {
2183                 var ret = "TB\u00a0";
2184                 if (score[2]) {  // Is a bound.
2185                         ret = score[2] + "\u00a0TB\u00a0";
2186                 }
2187                 if (score[0] === 'T') {
2188                         return ret + Math.ceil(score[1] / 2);
2189                 } else {
2190                         return ret + "-" + Math.ceil(score[1] / 2);
2191                 }
2192         } else if (score[0] === 'M' || score[0] === 'm') {
2193                 var sign = (score[0] === 'm') ? '-' : '';
2194                 if (score[2]) {  // Is a bound.
2195                         return score[2] + "\u00a0M " + sign + score[1];
2196                 } else {
2197                         return "M " + sign + score[1];
2198                 }
2199         } else if (score[0] === 'd') {
2200                 return "TB =0";
2201         } else if (score[0] === 'cp') {
2202                 if (score[2]) {  // Is a bound.
2203                         return score[2] + "\u00a0" + fmt_cp(score[1]);
2204                 } else {
2205                         return fmt_cp(score[1]);
2206                 }
2207         }
2208         return null;
2209 }
2210
2211 var format_long_score = function(score) {
2212         if (!score) {
2213                 return "???";
2214         }
2215         if (score[0] === 'T') {
2216                 if (score[1] == 0) {
2217                         return "Won for white (tablebase)";
2218                 } else {
2219                         return "White wins in " + Math.ceil(score[1] / 2);
2220                 }
2221         } else if (score[0] === 't') {
2222                 if (score[1] == -1) {
2223                         return "Won for black (tablebase)";
2224                 } else {
2225                         return "Black wins in " + Math.ceil(score[1] / 2);
2226                 }
2227         } else if (score[0] === 'M') {
2228                 if (score[1] == 0) {
2229                         return "White wins by checkmate";
2230                 } else {
2231                         return "White mates in " + score[1];
2232                 }
2233         } else if (score[0] === 'm') {
2234                 if (score[1] == 0) {
2235                         return "Black wins by checkmate";
2236                 } else {
2237                         return "Black mates in " + score[1];
2238                 }
2239         } else if (score[0] === 'd') {
2240                 return "Theoretical draw";
2241         } else if (score[0] === 'cp') {
2242                 return "Score: " + format_short_score(score);
2243         }
2244         return null;
2245 }
2246
2247 var compute_plot_score = function(score) {
2248         if (score[0] === 'M' || score[0] === 'T') {
2249                 return 500;
2250         } else if (score[0] === 'm' || score[0] === 't') {
2251                 return -500;
2252         } else if (score[0] === 'd') {
2253                 return 0;
2254         } else if (score[0] === 'cp') {
2255                 if (score[1] > 500) {
2256                         return 500;
2257                 } else if (score[1] < -500) {
2258                         return -500;
2259                 } else {
2260                         return score[1];
2261                 }
2262         }
2263         return null;
2264 }
2265
2266 /**
2267  * @param score The score digest tuple.
2268  * @param {?number} depth Depth the move has been computed to, or null.
2269  * @param {boolean} invert Whether black is to play.
2270  * @param {boolean=} depth_secondary_key
2271  * @return {number}
2272  */
2273 var compute_score_sort_key = function(score, depth, invert, depth_secondary_key) {
2274         var s;
2275         if (!score) {
2276                 return -10000000;
2277         }
2278         if (score[0] === 'T') {
2279                 // White reaches TB win.
2280                 s = 89999 - score[1];
2281         } else if (score[0] === 't') {
2282                 // Black reaches TB win.
2283                 s = -(89999 - score[1]);
2284         } else if (score[0] === 'M') {
2285                 // White mates.
2286                 s = 99999 - score[1];
2287         } else if (score[0] === 'm') {
2288                 // Black mates.
2289                 s = -(99999 - score[1]);
2290         } else if (score[0] === 'd') {
2291                 s = 0;
2292         } else if (score[0] === 'cp') {
2293                 s = score[1];
2294         }
2295         if (s) {
2296                 if (invert) s = -s;
2297                 if (depth_secondary_key) {
2298                         return s * 200 + (depth || 0);
2299                 } else {
2300                         return s;
2301                 }
2302         } else {
2303                 return null;
2304         }
2305 }
2306
2307 /**
2308  * @param {Object} game
2309  */
2310 var switch_backend = function(game) {
2311         // Stop looking at historic data.
2312         current_display_line = null;
2313         current_display_move = null;
2314         displayed_analysis_data = null;
2315         if (current_historic_xhr) {
2316                 current_historic_xhr.abort();
2317         }
2318
2319         // If we already have a backend response going, abort it.
2320         if (current_analysis_xhr) {
2321                 current_analysis_xhr.abort();
2322         }
2323         if (current_hash_xhr) {
2324                 current_hash_xhr.abort();
2325         }
2326
2327         // Otherwise, we should have a timer going to start a new one.
2328         // Kill that, too.
2329         if (current_analysis_request_timer) {
2330                 clearTimeout(current_analysis_request_timer);
2331                 current_analysis_request_timer = null;
2332         }
2333         if (current_hash_display_timer) {
2334                 clearTimeout(current_hash_display_timer);
2335                 current_hash_display_timer = null;
2336         }
2337
2338         // Request an immediate fetch with the new backend.
2339         backend_url = game['url'];
2340         backend_hash_url = game['hashurl'];
2341         window.location.hash = '#' + game['id'];
2342         current_analysis_data = null;
2343         ims = 0;
2344         request_update();
2345 }
2346 window['switch_backend'] = switch_backend;
2347
2348 window['flip'] = function() { board.flip(); redraw_arrows(); };
2349 window['set_delay_ms'] = function(ms) { delay_ms = ms; console.log('Delay is now ' + ms + ' ms.'); };
2350
2351 // Mostly from Wikipedia's chess set as of October 2022, but some pieces are from
2352 // the 2013 version, as I like those better (and it matches the 2014 PNGs; nobody
2353 // really likes change, do they?). That is wK, bK, bQ. wQ is also slightly different,
2354 // but not enough to notice.
2355 const svg_pieces = {
2356        'wK': 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSI0NSIgaGVpZ2h0PSI0NSI+CiAgPGcgc3R5bGU9ImZpbGw6bm9uZTsgZmlsbC1vcGFjaXR5OjE7IGZpbGwtcnVsZTpldmVub2RkOyBzdHJva2U6IzAwMDAwMDsgc3Ryb2tlLXdpZHRoOjEuNTsgc3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kO3N0cm9rZS1taXRlcmxpbWl0OjQ7IHN0cm9rZS1kYXNoYXJyYXk6bm9uZTsgc3Ryb2tlLW9wYWNpdHk6MTsiPgogICAgPHBhdGgKICAgICAgZD0iTSAyMi41LDExLjYzIEwgMjIuNSw2IgogICAgICBzdHlsZT0iZmlsbDpub25lOyBzdHJva2U6IzAwMDAwMDsgc3Ryb2tlLWxpbmVqb2luOm1pdGVyOyIgLz4KICAgIDxwYXRoCiAgICAgIGQ9Ik0gMjAsOCBMIDI1LDgiCiAgICAgIHN0eWxlPSJmaWxsOm5vbmU7IHN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M5LjUgSCAzNCBDIDM0LDMxLjU4IDI5LjU5LDI3LjA5IDI2LjU5LDI2LjAzIDI4LjA2LDI0Ljg0IDI5LDIzLjAzIDI5LDIxIDI5LDE4LjU5IDI3LjY3LDE2LjUgMjUuNzIsMTUuMzggMjYuMjEsMTQuNzEgMjYuNSwxMy44OSAyNi41LDEzIGMgMCwtMi4yMSAtMS43OSwtNCAtNCwtNCB6IiBzdHlsZT0ib3BhY2l0eToxOyBmaWxsOiMwMDAwMDA7IGZpbGwtb3BhY2l0eToxOyBmaWxsLXJ1bGU6bm9uemVybzsgc3Ryb2tlOiMwMDAwMDA7IHN0cm9rZS13aWR0aDoxLjU7IHN0cm9rZS1saW5lY2FwOnJvdW5kOyBzdHJva2UtbGluZWpvaW46bWl0ZXI7IHN0cm9rZS1taXRlcmxpbWl0OjQ7IHN0cm9rZS1kYXNoYXJyYXk6bm9uZTsgc3Ryb2tlLW9wYWNpdHk6MTsiLz4KPC9zdmc+Cg==',
2368 };
2369
2370 var svg_piece_theme = function(piece) {
2371         return svg_pieces[piece];
2372 }
2373
2374 var init = function() {
2375         unique = get_unique();
2376
2377         // Load settings from HTML5 local storage if available.
2378         if (supports_html5_storage() && localStorage['enable_sound']) {
2379                 set_sound(parseInt(localStorage['enable_sound']));
2380         } else {
2381                 set_sound(false);
2382         }
2383
2384         // Create board.
2385         board = new window.ChessBoard('board', {
2386                 onMoveEnd: function() { board_is_animating = false; },
2387
2388                 draggable: true,
2389                 pieceTheme: svg_piece_theme,
2390                 onDragStart: onDragStart,
2391                 onDrop: onDrop,
2392                 onSnapEnd: onSnapEnd
2393         });
2394         document.getElementById("board").addEventListener('mousedown', mousedownSquare);
2395         document.getElementById("board").addEventListener('mouseup', mouseupSquare);
2396
2397         request_update();
2398         window.addEventListener('resize', function() {
2399                 board.resize();
2400                 update_sparkline(displayed_analysis_data || current_analysis_data);
2401                 update_board_highlight();
2402                 redraw_arrows();
2403         });
2404         window.addEventListener('keyup', function(event) {
2405                 if (event.which == 39) {  // Left arrow.
2406                         next_move();
2407                 } else if (event.which == 37) {  // Right arrow.
2408                         prev_move();
2409                 } else if (event.which >= 49 && event.which <= 57) {  // 1-9.
2410                         var num = event.which - 49;
2411                         if (current_games && current_games.length >= num) {
2412                                 switch_backend(current_games[num]);
2413                         }
2414                 } else if (event.which == 78) {  // N.
2415                         next_game();
2416                 }
2417         });
2418         window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2419         possibly_switch_game_from_hash();
2420 };
2421 document.addEventListener('DOMContentLoaded', init);
2422
2423 })();