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