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