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