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