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