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