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