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