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