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