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