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