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