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