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