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