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