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