]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
Add a last-ditch resort for format_long_score(), if anything goes wrong.
[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'], refutation_lines[b]['depth'], invert);
564         var sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], 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 line = data['refutation_lines'][move];
587                 var score = compute_score_sort_key(line['score'], line['depth'], invert);
588                 if (move == data['pv_uci'][0]) {
589                         pv_score = score;
590                 }
591                 if (best_score === undefined || score > best_score) {
592                         best_score = score;
593                 }
594                 if (line['depth'] < 8) {
595                         return [];
596                 }
597         }
598
599         if (best_score - pv_score > 50) {
600                 return [];
601         }
602
603         // Now find all moves that are within “margin” of the best score.
604         // The PV move will always be first.
605         var moves = [];
606         for (var move in data['refutation_lines']) {
607                 var line = data['refutation_lines'][move];
608                 var score = compute_score_sort_key(line['score'], line['depth'], invert);
609                 if (move != data['pv_uci'][0] && best_score - score <= margin) {
610                         moves.push(move);
611                 }
612         }
613         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
614         moves.unshift(data['pv_uci'][0]);
615
616         return moves;
617 }
618
619 /**
620  * @param {number} x
621  * @return {!string}
622  */
623 var thousands = function(x) {
624         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
625 }
626
627 /**
628  * @param {!string} start_fen
629  * @param {Array.<string>} pretty_pv
630  * @param {number} move_num
631  * @param {!string} toplay
632  * @param {Array<{ first_move: integer, score: Object }>} scores
633  * @param {number} start_display_move_num
634  * @param {number=} opt_limit
635  * @param {boolean=} opt_showlast
636  */
637 var add_pv = function(start_fen, pretty_pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
638         display_lines.push({
639                 start_fen: start_fen,
640                 pretty_pv: pretty_pv,
641                 move_num: parseInt(move_num),
642                 toplay: toplay,
643                 scores: scores,
644                 start_display_move_num: start_display_move_num
645         });
646         return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
647 }
648
649 /**
650  * @param {number} line_num
651  * @param {number=} opt_limit If set, show at most this number of moves.
652  * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
653  */
654 var print_pv = function(line_num, opt_limit, opt_showlast) {
655         var display_line = display_lines[line_num];
656         var pretty_pv = display_line.pretty_pv;
657         var move_num = display_line.move_num;
658         var toplay = display_line.toplay;
659
660         // Truncate PV at the start if needed.
661         var start_display_move_num = display_line.start_display_move_num;
662         if (start_display_move_num > 0) {
663                 pretty_pv = pretty_pv.slice(start_display_move_num);
664                 var to_add = start_display_move_num;
665                 if (toplay === 'B') {
666                         ++move_num;
667                         toplay = 'W';
668                         --to_add;
669                 }
670                 if (to_add % 2 == 1) {
671                         toplay = 'B';
672                         --to_add;
673                 }
674                 move_num += to_add / 2;
675         }
676
677         var pv = '';
678         var i = 0;
679         if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
680                 // Truncate the PV at the beginning (instead of at the end).
681                 // We assume here that toplay is 'W'. We also assume that if
682                 // opt_showlast is set, then it is the history, and thus,
683                 // the UI should be to expand the history.
684                 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
685                 i = pretty_pv.length - opt_limit;
686                 if (i % 2 == 1) {
687                         ++i;
688                 }
689                 move_num += i / 2;
690         } else if (toplay == 'B' && pretty_pv.length > 0) {
691                 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
692                 pv = move_num + '. … ' + move;
693                 toplay = 'W';
694                 ++i;
695                 ++move_num;
696         }
697         for ( ; i < pretty_pv.length; ++i) {
698                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
699
700                 if (toplay == 'W') {
701                         if (i > opt_limit && !opt_showlast) {
702                                 return pv + ' (…)';
703                         }
704                         if (pv != '') {
705                                 pv += ' ';
706                         }
707                         pv += move_num + '. ' + move;
708                         ++move_num;
709                         toplay = 'B';
710                 } else {
711                         pv += ' ' + move;
712                         toplay = 'W';
713                 }
714         }
715         return pv;
716 }
717
718 /** Update the highlighted to/from squares on the board.
719  * Based on the global "highlight_from" and "highlight_to" variables.
720  */
721 var update_board_highlight = function() {
722         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
723         if ((current_display_line === null || current_display_line_is_history) &&
724             highlight_from !== undefined && highlight_to !== undefined) {
725                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
726                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
727         }
728 }
729
730 var update_history = function() {
731         if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
732                 $("#history").html("No history");
733         } else if (truncate_display_history) {
734                 $("#history").html(print_pv(0, 8, true));
735         } else {
736                 $("#history").html(
737                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
738                         print_pv(0));
739         }
740 }
741
742 /**
743  * @param {!boolean} truncate_history
744  */
745 var collapse_history = function(truncate_history) {
746         truncate_display_history = truncate_history;
747         update_history();
748 }
749 window['collapse_history'] = collapse_history;
750
751 /** Update the HTML display of multi-PV from the global "refutation_lines".
752  *
753  * Also recreates the global "display_lines".
754  */
755 var update_refutation_lines = function() {
756         if (base_fen === null) {
757                 return;
758         }
759         if (display_lines.length > 2) {
760                 // Truncate so that only the history and PV is left.
761                 display_lines = [ display_lines[0], display_lines[1] ];
762         }
763         var tbl = $("#refutationlines");
764         tbl.empty();
765
766         // Find out where the lines start from.
767         var base_line = [];
768         var base_scores = display_lines[1].scores;
769         var start_display_move_num = 0;
770         if (hash_refutation_lines) {
771                 base_line = current_display_line.pretty_pv.slice(0, current_display_move + 1);
772                 base_scores = current_display_line.scores;
773                 start_display_move_num = base_line.length;
774         }
775
776         var moves = [];
777         for (var move in refutation_lines) {
778                 moves.push(move);
779         }
780
781         var invert = (toplay === 'B');
782         if (current_display_line && current_display_move % 2 == 0) {
783                 invert = !invert;
784         }
785         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
786         moves = moves.sort(function(a, b) { return compare(refutation_lines, invert, a, b) });
787         for (var i = 0; i < moves.length; ++i) {
788                 var line = refutation_lines[moves[i]];
789
790                 var tr = document.createElement("tr");
791
792                 var move_td = document.createElement("td");
793                 tr.appendChild(move_td);
794                 $(move_td).addClass("move");
795
796                 var scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
797
798                 if (line['pv_pretty'].length == 0) {
799                         // Not found, so just make a one-move PV.
800                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
801                         $(move_td).html(move);
802                         var score_td = document.createElement("td");
803
804                         $(score_td).addClass("score");
805                         $(score_td).text("—");
806                         tr.appendChild(score_td);
807
808                         var depth_td = document.createElement("td");
809                         tr.appendChild(depth_td);
810                         $(depth_td).addClass("depth");
811                         $(depth_td).text("—");
812
813                         var pv_td = document.createElement("td");
814                         tr.appendChild(pv_td);
815                         $(pv_td).addClass("pv");
816                         $(pv_td).html(add_pv(base_fen, base_line.concat([ line['pretty_move'] ]), move_num, toplay, scores, start_display_move_num));
817
818                         tbl.append(tr);
819                         continue;
820                 }
821
822                 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
823                 $(move_td).html(move);
824
825                 var score_td = document.createElement("td");
826                 tr.appendChild(score_td);
827                 $(score_td).addClass("score");
828                 $(score_td).text(format_short_score(line['score']));
829
830                 var depth_td = document.createElement("td");
831                 tr.appendChild(depth_td);
832                 $(depth_td).addClass("depth");
833                 if (line['depth'] && line['depth'] >= 0) {
834                         $(depth_td).text("d" + line['depth']);
835                 } else {
836                         $(depth_td).text("—");
837                 }
838
839                 var pv_td = document.createElement("td");
840                 tr.appendChild(pv_td);
841                 $(pv_td).addClass("pv");
842                 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv_pretty']), move_num, toplay, scores, start_display_move_num, 10));
843
844                 tbl.append(tr);
845         }
846
847         // Make one of the links clickable and the other nonclickable.
848         if (sort_refutation_lines_by_score) {
849                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
850                 $("#sortbyscore1").html("<strong>Score</strong>");
851         } else {
852                 $("#sortbyscore0").html("<strong>Move</strong>");
853                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
854         }
855
856         // Update the move highlight, as we've rewritten all the HTML.
857         update_move_highlight();
858 }
859
860 /**
861  * Create a Chess.js board object, containing the given position plus the given moves,
862  * up to the given limit.
863  *
864  * @param {?string} fen
865  * @param {Array.<string>} moves
866  * @param {number} last_move
867  */
868 var chess_from = function(fen, moves, last_move) {
869         var hiddenboard = new Chess();
870         if (fen !== null) {
871                 hiddenboard.load(fen);
872         }
873         for (var i = 0; i <= last_move; ++i) {
874                 if (moves[i] === '0-0') {
875                         hiddenboard.move('O-O');
876                 } else if (moves[i] === '0-0-0') {
877                         hiddenboard.move('O-O-O');
878                 } else {
879                         hiddenboard.move(moves[i]);
880                 }
881         }
882         return hiddenboard;
883 }
884
885 var update_game_list = function(games) {
886         $("#games").text("");
887         if (games === null) {
888                 return;
889         }
890
891         var games_div = document.getElementById('games');
892         for (var game_num = 0; game_num < games.length; ++game_num) {
893                 var game = games[game_num];
894                 var game_span = document.createElement("span");
895                 game_span.setAttribute("class", "game");
896
897                 var game_name = document.createTextNode(game['name']);
898                 if (game['url'] === backend_url) {
899                         // This game.
900                         game_span.appendChild(game_name);
901
902                         if (current_analysis_data && current_analysis_data['position']) {
903                                 var score;
904                                 if (current_analysis_data['position']['result']) {
905                                         score = " (" + current_analysis_data['position']['result'] + ")";
906                                 } else {
907                                         score = " (" + format_short_score(current_analysis_data['score']) + ")";
908                                 }
909                                 game_span.appendChild(document.createTextNode(score));
910                         }
911                 } else {
912                         // Some other game.
913                         var game_a = document.createElement("a");
914                         game_a.setAttribute("href", "#" + game['id']);
915                         game_a.appendChild(game_name);
916                         game_span.appendChild(game_a);
917
918                         var score;
919                         if (game['result']) {
920                                 score = " (" + game['result'] + ")";
921                         } else {
922                                 score = " (" + format_short_score(game['score']) + ")";
923                         }
924                         game_span.appendChild(document.createTextNode(score));
925                 }
926
927                 games_div.appendChild(game_span);
928         }
929 }
930
931 /**
932  * Try to find a running game that matches with the current hash,
933  * and switch to it if we're not already displaying it.
934  */
935 var possibly_switch_game_from_hash = function() {
936         if (current_games === null) {
937                 return;
938         }
939
940         var hash = window.location.hash.replace(/^#/,'');
941         for (var i = 0; i < current_games.length; ++i) {
942                 if (current_games[i]['id'] === hash) {
943                         if (backend_url !== current_games[i]['url']) {
944                                 switch_backend(current_games[i]['url'], current_games[i]['hashurl']);
945                         }
946                         return;
947                 }
948         }
949 }
950
951 /** Update all the HTML on the page, based on current global state.
952  */
953 var update_board = function() {
954         var data = displayed_analysis_data || current_analysis_data;
955         var current_data = current_analysis_data;  // Convenience alias.
956
957         display_lines = [];
958
959         // Print the history. This is pretty much the only thing that's
960         // unconditionally taken from current_data (we're not interested in
961         // historic history).
962         if (current_data['position']['pretty_history']) {
963                 add_pv('start', current_data['position']['pretty_history'], 1, 'W', null, 0, 8, true);
964         } else {
965                 display_lines.push(null);
966         }
967         update_history();
968
969         // Games currently in progress, if any.
970         if (current_data['games']) {
971                 current_games = current_data['games'];
972                 possibly_switch_game_from_hash();
973         } else {
974                 current_games = null;
975         }
976         update_game_list(current_games);
977
978         // The headline. Names are always fetched from current_data;
979         // the rest can depend a bit.
980         var headline;
981         if (current_data &&
982             current_data['position']['player_w'] && current_data['position']['player_b']) {
983                 headline = current_data['position']['player_w'] + '–' +
984                         current_data['position']['player_b'] + ', analysis';
985         } else {
986                 headline = 'Analysis';
987         }
988
989         // Credits, where applicable. Note that we don't want the footer to change a lot
990         // when e.g. viewing history, so if any of these changed during the game,
991         // use the current one still.
992         if (current_data['using_lomonosov']) {
993                 $("#lomonosov").show();
994         } else {
995                 $("#lomonosov").hide();
996         }
997
998         // Credits: The engine name/version.
999         if (current_data['engine'] && current_data['engine']['name'] !== null) {
1000                 $("#engineid").text(current_data['engine']['name']);
1001         }
1002
1003         // Credits: The engine URL.
1004         if (current_data['engine'] && current_data['engine']['url']) {
1005                 $("#engineid").attr("href", current_data['engine']['url']);
1006         } else {
1007                 $("#engineid").removeAttr("href");
1008         }
1009
1010         // Credits: Engine details.
1011         if (current_data['engine'] && current_data['engine']['details']) {
1012                 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
1013         } else {
1014                 $("#enginedetails").text("");
1015         }
1016
1017         // Credits: Move source, possibly with URL.
1018         if (current_data['move_source'] && current_data['move_source_url']) {
1019                 $("#movesource").text("Moves provided by ");
1020                 var movesource_a = document.createElement("a");
1021                 movesource_a.setAttribute("href", current_data['move_source_url']);
1022                 var movesource_text = document.createTextNode(current_data['move_source']);
1023                 movesource_a.appendChild(movesource_text);
1024                 var movesource_period = document.createTextNode(".");
1025                 document.getElementById("movesource").appendChild(movesource_a);
1026                 document.getElementById("movesource").appendChild(movesource_period);
1027         } else if (current_data['move_source']) {
1028                 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
1029         } else {
1030                 $("#movesource").text("");
1031         }
1032
1033         var last_move;
1034         if (displayed_analysis_data) {
1035                 // Displaying some non-current position, pick out the last move
1036                 // from the history. This will work even if the fetch failed.
1037                 last_move = format_halfmove_with_number(
1038                         current_display_line.pretty_pv[current_display_move],
1039                         current_display_move + 1);
1040                 headline += ' after ' + last_move;
1041         } else if (data['position']['last_move'] !== 'none') {
1042                 last_move = format_move_with_number(
1043                         data['position']['last_move'],
1044                         data['position']['move_num'],
1045                         data['position']['toplay'] == 'W');
1046                 headline += ' after ' + last_move;
1047         } else {
1048                 last_move = null;
1049         }
1050         $("#headline").text(headline);
1051
1052         // The <title> contains a very brief headline.
1053         var title_elems = [];
1054         if (data['position'] && data['position']['result']) {
1055                 title_elems.push(data['position']['result']);
1056         } else if (data['score']) {
1057                 title_elems.push(format_short_score(data['score']));
1058         }
1059         if (last_move !== null) {
1060                 title_elems.push(last_move);
1061         }
1062
1063         if (title_elems.length != 0) {
1064                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1065         } else {
1066                 document.title = 'analysis.sesse.net';
1067         }
1068
1069         // The last move (shown by highlighting the from and to squares).
1070         if (data['position'] && data['position']['last_move_uci']) {
1071                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1072                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1073         } else if (current_display_line_is_history && current_display_move >= 0) {
1074                 // We don't have historic analysis for this position, but we
1075                 // can reconstruct what the last move was by just replaying
1076                 // from the start.
1077                 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1078                 var moves = hiddenboard.history({ verbose: true });
1079                 var last_move = moves.pop();
1080                 highlight_from = last_move.from;
1081                 highlight_to = last_move.to;
1082         } else {
1083                 highlight_from = highlight_to = undefined;
1084         }
1085         update_board_highlight();
1086
1087         if (data['failed']) {
1088                 $("#score").text("No analysis for this move");
1089                 $("#pvtitle").text("PV:");
1090                 $("#pv").empty();
1091                 $("#searchstats").html("&nbsp;");
1092                 $("#refutationlines").empty();
1093                 $("#whiteclock").empty();
1094                 $("#blackclock").empty();
1095                 refutation_lines = [];
1096                 update_refutation_lines();
1097                 clear_arrows();
1098                 update_displayed_line();
1099                 update_move_highlight();
1100                 return;
1101         }
1102
1103         update_clock();
1104
1105         // The score.
1106         if (current_display_line && !current_display_line_is_history) {
1107                 if (current_display_line.scores && current_display_line.scores.length > 0) {
1108                         var score;
1109                         for (var i = 0; i < current_display_line.scores.length; ++i) {
1110                                 if (current_display_move < current_display_line.scores[i].first_move) {
1111                                         break;
1112                                 }
1113                                 score = current_display_line.scores[i].score;
1114                         }
1115                         $("#score").text(format_long_score(score));
1116                 } else {
1117                         $("#score").text("No score for this move");
1118                 }
1119         } else if (data['score']) {
1120                 $("#score").text(format_long_score(data['score']));
1121         }
1122
1123         // The search stats.
1124         if (data['searchstats']) {
1125                 $("#searchstats").html(data['searchstats']);
1126         } else if (data['tablebase'] == 1) {
1127                 $("#searchstats").text("Tablebase result");
1128         } else if (data['nodes'] && data['nps'] && data['depth']) {
1129                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1130                 if (data['seldepth']) {
1131                         stats += ' (' + data['seldepth'] + ' selective)';
1132                 }
1133                 if (data['tbhits'] && data['tbhits'] > 0) {
1134                         if (data['tbhits'] == 1) {
1135                                 stats += ', one Syzygy hit';
1136                         } else {
1137                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1138                         }
1139                 }
1140
1141                 $("#searchstats").text(stats);
1142         } else {
1143                 $("#searchstats").text("");
1144         }
1145
1146         // Update the board itself.
1147         base_fen = data['position']['fen'];
1148         update_displayed_line();
1149
1150         // Print the PV.
1151         $("#pvtitle").text("PV:");
1152
1153         var scores = [{ first_move: -1, score: data['score'] }];
1154         $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1155
1156         // Update the PV arrow.
1157         clear_arrows();
1158         if (data['pv_uci'].length >= 1) {
1159                 // draw a continuation arrow as long as it's the same piece
1160                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
1161                         var from = data['pv_uci'][i].substr(0, 2);
1162                         var to = data['pv_uci'][i].substr(2,4);
1163                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
1164                              interfering_arrow(from, to)) {
1165                                 break;
1166                         }
1167                         create_arrow(from, to, '#f66', 6, 20);
1168                 }
1169
1170                 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1171                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1172                         create_arrow(alt_moves[i].substr(0, 2),
1173                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
1174                 }
1175         }
1176
1177         // See if all semi-reasonable moves have only one possible response.
1178         if (data['pv_uci'].length >= 2) {
1179                 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1180                 var response = data['pv_uci'][1];
1181                 for (var i = 0; i < nonstupid_moves.length; ++i) {
1182                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
1183                                 // ignore the PV move for refutation lines.
1184                                 continue;
1185                         }
1186                         if (!data['refutation_lines'] ||
1187                             !data['refutation_lines'][nonstupid_moves[i]] ||
1188                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1189                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1190                                 // Incomplete PV, abort.
1191                                 response = undefined;
1192                                 break;
1193                         }
1194                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1195                         if (response !== this_response) {
1196                                 // Different response depending on lines, abort.
1197                                 response = undefined;
1198                                 break;
1199                         }
1200                 }
1201
1202                 if (nonstupid_moves.length > 0 && response !== undefined) {
1203                         create_arrow(response.substr(0, 2),
1204                                      response.substr(2, 2), '#66f', 6, 20);
1205                 }
1206         }
1207
1208         // Update the refutation lines.
1209         base_fen = data['position']['fen'];
1210         move_num = parseInt(data['position']['move_num']);
1211         toplay = data['position']['toplay'];
1212         refutation_lines = hash_refutation_lines || data['refutation_lines'];
1213         update_refutation_lines();
1214
1215         // Update the sparkline last, since its size depends on how everything else reflowed.
1216         update_sparkline(data);
1217 }
1218
1219 var update_sparkline = function(data) {
1220         if (data && data['score_history']) {
1221                 var first_move_num = undefined;
1222                 for (var halfmove_num in data['score_history']) {
1223                         halfmove_num = parseInt(halfmove_num);
1224                         if (first_move_num === undefined || halfmove_num < first_move_num) {
1225                                 first_move_num = halfmove_num;
1226                         }
1227                 }
1228                 if (first_move_num !== undefined) {
1229                         var last_move_num = data['position']['move_num'] * 2 - 3;
1230                         if (data['position']['toplay'] === 'B') {
1231                                 ++last_move_num;
1232                         }
1233
1234                         // Possibly truncate some moves if we don't have enough width.
1235                         // FIXME: Sometimes width() for #scorecontainer (and by extent,
1236                         // #scoresparkcontainer) on Chrome for mobile seems to start off
1237                         // at something very small, and then suddenly snap back into place.
1238                         // Figure out why.
1239                         var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1240                         if (last_move_num - first_move_num > max_moves) {
1241                                 first_move_num = last_move_num - max_moves;
1242                         }
1243
1244                         var min_score = -100;
1245                         var max_score = 100;
1246                         var last_score = null;
1247                         var scores = [];
1248                         for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1249                                 if (data['score_history'][halfmove_num]) {
1250                                         var score = compute_plot_score(data['score_history'][halfmove_num]);
1251                                         last_score = score;
1252                                         if (score < min_score) min_score = score;
1253                                         if (score > max_score) max_score = score;
1254                                 }
1255                                 scores.push(last_score);
1256                         }
1257                         if (data['score']) {
1258                                 scores.push(compute_plot_score(data['score']));
1259                         }
1260                         // FIXME: at some widths, calling sparkline() seems to push
1261                         // #scorecontainer under the board.
1262                         $("#scorespark").sparkline(scores, {
1263                                 type: 'bar',
1264                                 zeroColor: 'gray',
1265                                 chartRangeMin: min_score,
1266                                 chartRangeMax: max_score,
1267                                 tooltipFormatter: function(sparkline, options, fields) {
1268                                         return format_tooltip(data, fields[0].offset + first_move_num);
1269                                 }
1270                         });
1271                 } else {
1272                         $("#scorespark").text("");
1273                 }
1274         } else {
1275                 $("#scorespark").text("");
1276         }
1277 }
1278
1279 /**
1280  * @param {number} num_viewers
1281  */
1282 var update_num_viewers = function(num_viewers) {
1283         if (num_viewers === null) {
1284                 $("#numviewers").text("");
1285         } else if (num_viewers == 1) {
1286                 $("#numviewers").text("You are the only current viewer");
1287         } else {
1288                 $("#numviewers").text(num_viewers + " current viewers");
1289         }
1290 }
1291
1292 var update_clock = function() {
1293         clearTimeout(clock_timer);
1294
1295         var data = displayed_analysis_data || current_analysis_data;
1296         if (!data) return;
1297
1298         if (data['position']) {
1299                 var result = data['position']['result'];
1300                 if (result === '1-0') {
1301                         $("#whiteclock").text("1");
1302                         $("#blackclock").text("0");
1303                         $("#whiteclock").removeClass("running-clock");
1304                         $("#blackclock").removeClass("running-clock");
1305                         return;
1306                 }
1307                 if (result === '1/2-1/2') {
1308                         $("#whiteclock").text("1/2");
1309                         $("#blackclock").text("1/2");
1310                         $("#whiteclock").removeClass("running-clock");
1311                         $("#blackclock").removeClass("running-clock");
1312                         return;
1313                 }       
1314                 if (result === '0-1') {
1315                         $("#whiteclock").text("0");
1316                         $("#blackclock").text("1");
1317                         $("#whiteclock").removeClass("running-clock");
1318                         $("#blackclock").removeClass("running-clock");
1319                         return;
1320                 }
1321         }
1322
1323         var white_clock_ms = null;
1324         var black_clock_ms = null;
1325         var show_seconds = false;
1326
1327         // Static clocks.
1328         if (data['position'] &&
1329             data['position']['white_clock'] &&
1330             data['position']['black_clock']) {
1331                 white_clock_ms = data['position']['white_clock'] * 1000;
1332                 black_clock_ms = data['position']['black_clock'] * 1000;
1333         }
1334
1335         // Dynamic clock (only one, obviously).
1336         var color;
1337         if (data['position']['white_clock_target']) {
1338                 color = "white";
1339                 $("#whiteclock").addClass("running-clock");
1340                 $("#blackclock").removeClass("running-clock");
1341         } else if (data['position']['black_clock_target']) {
1342                 color = "black";
1343                 $("#whiteclock").removeClass("running-clock");
1344                 $("#blackclock").addClass("running-clock");
1345         } else {
1346                 $("#whiteclock").removeClass("running-clock");
1347                 $("#blackclock").removeClass("running-clock");
1348         }
1349         var remaining_ms;
1350         if (color) {
1351                 var now = new Date().getTime() + client_clock_offset_ms;
1352                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1353                 if (color === "white") {
1354                         white_clock_ms = remaining_ms;
1355                 } else {
1356                         black_clock_ms = remaining_ms;
1357                 }
1358         }
1359
1360         if (white_clock_ms === null || black_clock_ms === null) {
1361                 $("#whiteclock").empty();
1362                 $("#blackclock").empty();
1363                 return;
1364         }
1365
1366         // If either player has ten minutes or less left, add the second counters.
1367         var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1368
1369         if (color) {
1370                 // See when the clock will change next, and update right after that.
1371                 var next_update_ms;
1372                 if (show_seconds) {
1373                         next_update_ms = remaining_ms % 1000 + 100;
1374                 } else {
1375                         next_update_ms = remaining_ms % 60000 + 100;
1376                 }
1377                 clock_timer = setTimeout(update_clock, next_update_ms);
1378         }
1379
1380         $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1381         $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1382 }
1383
1384 /**
1385  * @param {Number} remaining_ms
1386  * @param {boolean} show_seconds
1387  */
1388 var format_clock = function(remaining_ms, show_seconds) {
1389         if (remaining_ms <= 0) {
1390                 if (show_seconds) {
1391                         return "00:00:00";
1392                 } else {
1393                         return "00:00";
1394                 }
1395         }
1396
1397         var remaining = Math.floor(remaining_ms / 1000);
1398         var seconds = remaining % 60;
1399         remaining = (remaining - seconds) / 60;
1400         var minutes = remaining % 60;
1401         remaining = (remaining - minutes) / 60;
1402         var hours = remaining;
1403         if (show_seconds) {
1404                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1405         } else {
1406                 return format_2d(hours) + ":" + format_2d(minutes);
1407         }
1408 }
1409
1410 /**
1411  * @param {Number} x
1412  */
1413 var format_2d = function(x) {
1414         if (x >= 10) {
1415                 return x;
1416         } else {
1417                 return "0" + x;
1418         }
1419 }
1420
1421 /**
1422  * @param {string} move
1423  * @param {Number} move_num
1424  * @param {boolean} white_to_play
1425  */
1426 var format_move_with_number = function(move, move_num, white_to_play) {
1427         var ret;
1428         if (white_to_play) {
1429                 ret = (move_num - 1) + '… ';
1430         } else {
1431                 ret = move_num + '. ';
1432         }
1433         ret += move;
1434         return ret;
1435 }
1436
1437 /**
1438  * @param {string} move
1439  * @param {Number} halfmove_num
1440  */
1441 var format_halfmove_with_number = function(move, halfmove_num) {
1442         return format_move_with_number(
1443                 move,
1444                 Math.floor(halfmove_num / 2) + 1,
1445                 halfmove_num % 2 == 0);
1446 }
1447
1448 /**
1449  * @param {Object} data
1450  * @param {Number} halfmove_num
1451  */
1452 var format_tooltip = function(data, halfmove_num) {
1453         if (data['score_history'][halfmove_num] ||
1454             halfmove_num === data['position']['pretty_history'].length) {
1455                 var move;
1456                 var short_score;
1457                 if (halfmove_num === data['position']['pretty_history'].length) {
1458                         move = data['position']['last_move'];
1459                         short_score = format_short_score(data['score']);
1460                 } else {
1461                         move = data['position']['pretty_history'][halfmove_num];
1462                         short_score = format_short_score(data['score_history'][halfmove_num]);
1463                 }
1464                 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1465
1466                 return "After " + move_with_number + ": " + short_score;
1467         } else {
1468                 for (var i = halfmove_num; i --> 0; ) {
1469                         if (data['score_history'][i]) {
1470                                 var move = data['position']['pretty_history'][i];
1471                                 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1472                         }
1473                 }
1474         }
1475 }
1476
1477 /**
1478  * @param {boolean} sort_by_score
1479  */
1480 var resort_refutation_lines = function(sort_by_score) {
1481         sort_refutation_lines_by_score = sort_by_score;
1482         if (supports_html5_storage()) {
1483                 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1484         }
1485         update_refutation_lines();
1486 }
1487 window['resort_refutation_lines'] = resort_refutation_lines;
1488
1489 /**
1490  * @param {boolean} truncate_history
1491  */
1492 var set_truncate_history = function(truncate_history) {
1493         truncate_display_history = truncate_history;
1494         update_refutation_lines();
1495 }
1496 window['set_truncate_history'] = set_truncate_history;
1497
1498 /**
1499  * @param {number} line_num
1500  * @param {number} move_num
1501  */
1502 var show_line = function(line_num, move_num) {
1503         if (line_num == -1) {
1504                 current_display_line = null;
1505                 current_display_move = null;
1506                 hash_refutation_lines = null;
1507                 if (displayed_analysis_data) {
1508                         // TODO: Support exiting to history position if we are in an
1509                         // analysis line of a history position.
1510                         displayed_analysis_data = null;
1511                 }
1512                 update_board();
1513                 return;
1514         } else {
1515                 current_display_line = jQuery.extend({}, display_lines[line_num]);  // Shallow clone.
1516                 current_display_move = move_num + current_display_line.start_display_move_num;
1517         }
1518         current_display_line_is_history = (line_num == 0);
1519
1520         update_historic_analysis();
1521         update_displayed_line();
1522         update_board_highlight();
1523         update_move_highlight();
1524         redraw_arrows();
1525 }
1526 window['show_line'] = show_line;
1527
1528 var prev_move = function() {
1529         if (current_display_line &&
1530             current_display_move >= current_display_line.start_display_move_num) {
1531                 --current_display_move;
1532         }
1533         update_historic_analysis();
1534         update_displayed_line();
1535         update_move_highlight();
1536 }
1537 window['prev_move'] = prev_move;
1538
1539 var next_move = function() {
1540         if (current_display_line &&
1541             current_display_move < current_display_line.pretty_pv.length - 1) {
1542                 ++current_display_move;
1543         }
1544         update_historic_analysis();
1545         update_displayed_line();
1546         update_move_highlight();
1547 }
1548 window['next_move'] = next_move;
1549
1550 var next_game = function() {
1551         if (current_games === null) {
1552                 return;
1553         }
1554
1555         // Try to find the game we are currently looking at.
1556         for (var game_num = 0; game_num < current_games.length; ++game_num) {
1557                 var game = current_games[game_num];
1558                 if (game['url'] === backend_url) {
1559                         var next_game_num = (game_num + 1) % current_games.length;
1560                         switch_backend(current_games[next_game_num]['url'], current_games[next_game_num]['hashurl']);
1561                         return;
1562                 }
1563         }
1564
1565         // Couldn't find it; give up.
1566 }
1567
1568 var update_historic_analysis = function() {
1569         if (!current_display_line_is_history) {
1570                 return;
1571         }
1572         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1573                 displayed_analysis_data = null;
1574                 update_board();
1575         }
1576
1577         // Fetch old analysis for this line if it exists.
1578         var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1579         var filename = "/history/move" + (current_display_move + 1) + "-" +
1580                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1581
1582         current_historic_xhr = $.ajax({
1583                 url: filename
1584         }).done(function(data, textstatus, xhr) {
1585                 displayed_analysis_data = data;
1586                 update_board();
1587         }).fail(function(jqXHR, textStatus, errorThrown) {
1588                 if (textStatus === "abort") {
1589                         // Aborted because we are switching backends. Don't do anything;
1590                         // we will already have been cleared.
1591                 } else {
1592                         displayed_analysis_data = {'failed': true};
1593                         update_board();
1594                 }
1595         });
1596 }
1597
1598 /**
1599  * @param {string} fen
1600  */
1601 var update_imbalance = function(fen) {
1602         var hiddenboard = new Chess(fen);
1603         var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1604         for (var row = 0; row < 8; ++row) {
1605                 for (var col = 0; col < 8; ++col) {
1606                         var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1607                         var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1608                         var square = col_text + row_text;
1609                         var contents = hiddenboard.get(square);
1610                         if (contents !== null) {
1611                                 if (contents.color === 'w') {
1612                                         ++imbalance[contents.type];
1613                                 } else {
1614                                         --imbalance[contents.type];
1615                                 }
1616                         }
1617                 }
1618         }
1619         var white_imbalance = '';
1620         var black_imbalance = '';
1621         for (var piece in imbalance) {
1622                 for (var i = 0; i < imbalance[piece]; ++i) {
1623                         white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1624                 }
1625                 for (var i = 0; i < -imbalance[piece]; ++i) {
1626                         black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1627                 }
1628         }
1629         $('#whiteimbalance').html(white_imbalance);
1630         $('#blackimbalance').html(black_imbalance);
1631 }
1632
1633 /** Mark the currently selected move in red.
1634  * Also replaces the PV with the current displayed line if it's not shown
1635  * anywhere else on the screen.
1636  */
1637 var update_move_highlight = function() {
1638         if (highlighted_move !== null) {
1639                 highlighted_move.removeClass('highlight'); 
1640         }
1641         if (current_display_line) {
1642                 var display_line_num = find_display_line_matching_num();
1643                 if (display_line_num === null) {
1644                         // Replace the PV with the (complete) line.
1645                         $("#pvtitle").text("Exploring:");
1646                         current_display_line.start_display_move_num = 0;
1647                         display_lines.push(current_display_line);
1648                         $("#pv").html(print_pv(display_lines.length - 1));
1649                         display_line_num = display_lines.length - 1;
1650                 }
1651
1652                 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1653                 highlighted_move.addClass('highlight');
1654         }
1655 }
1656
1657 /**
1658  * See if the current displayed line is identical to any of the ones
1659  * we have on screen. (It might not be if e.g. the analysis reloaded
1660  * since we started looking.)
1661  *
1662  * @return {?number}
1663  */
1664 var find_display_line_matching_num = function() {
1665         for (var i = 0; i < display_lines.length; ++i) {
1666                 var line = display_lines[i];
1667                 if (line.start_display_move_num > 0) continue;
1668                 if (current_display_line.start_fen !== line.start_fen) continue;
1669                 if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1670                 var ok = true;
1671                 for (var j = 0; j < line.pretty_pv.length; ++j) {
1672                         if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1673                                 ok = false;
1674                                 break;
1675                         }
1676                 }
1677                 if (ok) {
1678                         return i;
1679                 }
1680         }
1681         return null;
1682 }
1683
1684 /** Update the board based on the currently displayed line.
1685  * 
1686  * TODO: This should really be called only whenever something changes,
1687  * instead of all the time.
1688  */
1689 var update_displayed_line = function() {
1690         if (current_display_line === null) {
1691                 $("#linenav").hide();
1692                 $("#linemsg").show();
1693                 display_fen = base_fen;
1694                 set_board_position(base_fen);
1695                 update_imbalance(base_fen);
1696                 return;
1697         }
1698
1699         $("#linenav").show();
1700         $("#linemsg").hide();
1701
1702         if (current_display_move <= 0) {
1703                 $("#prevmove").html("Previous");
1704         } else {
1705                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1706         }
1707         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1708                 $("#nextmove").html("Next");
1709         } else {
1710                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1711         }
1712
1713         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1714         set_board_position(hiddenboard.fen());
1715         if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1716                 // Fire off a hash request, since we're now off the main position
1717                 // and it just changed.
1718                 explore_hash(hiddenboard.fen());
1719         }
1720         display_fen = hiddenboard.fen();
1721         update_imbalance(hiddenboard.fen());
1722 }
1723
1724 var set_board_position = function(new_fen) {
1725         board_is_animating = true;
1726         var old_fen = board.fen();
1727         board.position(new_fen);
1728         if (board.fen() === old_fen) {
1729                 board_is_animating = false;
1730         }
1731 }
1732
1733 /**
1734  * @param {boolean} param_enable_sound
1735  */
1736 var set_sound = function(param_enable_sound) {
1737         enable_sound = param_enable_sound;
1738         if (enable_sound) {
1739                 $("#soundon").html("<strong>On</strong>");
1740                 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1741
1742                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1743                 // and also preload the file since the user has selected audio.
1744                 var ding = document.getElementById('ding');
1745                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1746                         ding.src = 'ding.opus';
1747                         ding.load();
1748                 }
1749         } else {
1750                 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1751                 $("#soundoff").html("<strong>Off</strong>");
1752         }
1753         if (supports_html5_storage()) {
1754                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1755         }
1756 }
1757 window['set_sound'] = set_sound;
1758
1759 /** Send off a hash probe request to the backend.
1760  * @param {string} fen
1761  */
1762 var explore_hash = function(fen) {
1763         // If we already have a backend response going, abort it.
1764         if (current_hash_xhr) {
1765                 current_hash_xhr.abort();
1766         }
1767         if (current_hash_display_timer) {
1768                 clearTimeout(current_hash_display_timer);
1769                 current_hash_display_timer = null;
1770         }
1771         $("#refutationlines").empty();
1772         current_hash_xhr = $.ajax({
1773                 url: backend_hash_url + "?fen=" + fen
1774         }).done(function(data, textstatus, xhr) {
1775                 show_explore_hash_results(data, fen);
1776         });
1777 }
1778
1779 /** Process the JSON response from a hash probe request.
1780  * @param {!Object} data
1781  * @param {string} fen
1782  */
1783 var show_explore_hash_results = function(data, fen) {
1784         if (board_is_animating) {
1785                 // Updating while the animation is still going causes
1786                 // the animation to jerk. This is pretty crude, but it will do.
1787                 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1788                 return;
1789         }
1790         current_hash_display_timer = null;
1791         hash_refutation_lines = data['lines'];
1792         update_board();
1793 }
1794
1795 // almost all of this stuff comes from the chessboard.js example page
1796 var onDragStart = function(source, piece, position, orientation) {
1797         var pseudogame = new Chess(display_fen);
1798         if (pseudogame.game_over() === true ||
1799             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1800             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1801                 return false;
1802         }
1803
1804         recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1805         if (recommended_move) {
1806                 var squareEl = $('#board .square-' + recommended_move.to);
1807                 squareEl.addClass('highlight1-32417');
1808         }
1809         return true;
1810 }
1811
1812 var mousedownSquare = function(e) {
1813         reverse_dragging_from = null;
1814         var square = $(this).attr('data-square');
1815
1816         var pseudogame = new Chess(display_fen);
1817         if (pseudogame.game_over() === true) {
1818                 return;
1819         }
1820
1821         // If the square is empty, or has a piece of the side not to move,
1822         // we handle it. If not, normal piece dragging will take it.
1823         var position = board.position();
1824         if (!position.hasOwnProperty(square) ||
1825             (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1826             (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1827                 reverse_dragging_from = square;
1828                 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1829                 if (recommended_move) {
1830                         var squareEl = $('#board .square-' + recommended_move.from);
1831                         squareEl.addClass('highlight1-32417');
1832                         squareEl = $('#board .square-' + recommended_move.to);
1833                         squareEl.addClass('highlight1-32417');
1834                 }
1835         }
1836 }
1837
1838 var mouseupSquare = function(e) {
1839         if (reverse_dragging_from === null) {
1840                 return;
1841         }
1842         var source = $(this).attr('data-square');
1843         var target = reverse_dragging_from;
1844         reverse_dragging_from = null;
1845         if (onDrop(source, target) !== 'snapback') {
1846                 onSnapEnd(source, target);
1847         }
1848         $("#board").find('.square-55d63').removeClass('highlight1-32417');
1849 }
1850
1851 var get_best_move = function(game, source, target, invert) {
1852         var moves = game.moves({ verbose: true });
1853         if (source !== null) {
1854                 moves = moves.filter(function(move) { return move.from == source; });
1855         }
1856         if (target !== null) {
1857                 moves = moves.filter(function(move) { return move.to == target; });
1858         }
1859         if (moves.length == 0) {
1860                 return null;
1861         }
1862         if (moves.length == 1) {
1863                 return moves[0];
1864         }
1865
1866         // More than one move. Use the display lines (if we have them)
1867         // to disambiguate; otherwise, we have no information.
1868         var move_hash = {};
1869         for (var i = 0; i < moves.length; ++i) {
1870                 move_hash[moves[i].san] = moves[i];
1871         }
1872
1873         // See if we're already exploring some line.
1874         if (current_display_line &&
1875             current_display_move < current_display_line.pretty_pv.length - 1) {
1876                 var first_move = current_display_line.pretty_pv[current_display_move + 1];
1877                 if (move_hash[first_move]) {
1878                         return move_hash[first_move];
1879                 }
1880         }
1881
1882         // History and PV take priority over the display lines.
1883         for (var i = 0; i < 2; ++i) {
1884                 var line = display_lines[i];
1885                 var first_move = line.pretty_pv[line.start_display_move_num];
1886                 if (move_hash[first_move]) {
1887                         return move_hash[first_move];
1888                 }
1889         }
1890
1891         var best_move = null;
1892         var best_move_score = null;
1893
1894         for (var move in refutation_lines) {
1895                 var line = refutation_lines[move];
1896                 if (!line['score']) {
1897                         continue;
1898                 }
1899                 var first_move = line['pv_pretty'][0];
1900                 if (move_hash[first_move]) {
1901                         var score = compute_score_sort_key(line['score'], line['depth'], invert);
1902                         if (best_move_score === null || score > best_move_score) {
1903                                 best_move = move_hash[first_move];
1904                                 best_move_score = score;
1905                         }
1906                 }
1907         }
1908         return best_move;
1909 }
1910
1911 var onDrop = function(source, target) {
1912         if (source === target) {
1913                 if (recommended_move === null) {
1914                         return 'snapback';
1915                 } else {
1916                         // Accept the move. It will be changed in onSnapEnd.
1917                         return;
1918                 }
1919         } else {
1920                 // Suggestion not asked for.
1921                 recommended_move = null;
1922         }
1923
1924         // see if the move is legal
1925         var pseudogame = new Chess(display_fen);
1926         var move = pseudogame.move({
1927                 from: source,
1928                 to: target,
1929                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1930         });
1931
1932         // illegal move
1933         if (move === null) return 'snapback';
1934 }
1935
1936 var onSnapEnd = function(source, target) {
1937         if (source === target && recommended_move !== null) {
1938                 source = recommended_move.from;
1939                 target = recommended_move.to;
1940         }
1941         recommended_move = null;
1942         var pseudogame = new Chess(display_fen);
1943         var move = pseudogame.move({
1944                 from: source,
1945                 to: target,
1946                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1947         });
1948
1949         if (current_display_line &&
1950             current_display_move < current_display_line.pretty_pv.length - 1 &&
1951             current_display_line.pretty_pv[current_display_move + 1] === move.san) {
1952                 next_move();
1953                 return;
1954         }
1955
1956         // Walk down the displayed lines until we find one that starts with
1957         // this move, then select that. Note that this gives us a good priority
1958         // order (history first, then PV, then multi-PV lines).
1959         for (var i = 0; i < display_lines.length; ++i) {
1960                 var line = display_lines[i];
1961                 if (line.pretty_pv[line.start_display_move_num] === move.san) {
1962                         show_line(i, 0);
1963                         return;
1964                 }
1965         }
1966
1967         // Shouldn't really be here if we have hash probes, but there's really
1968         // nothing we can do.
1969 }
1970 // End of dragging-related code.
1971
1972 var fmt_cp = function(v) {
1973         if (v === 0) {
1974                 return "0.00";
1975         } else if (v > 0) {
1976                 return "+" + (v / 100).toFixed(2);
1977         } else {
1978                 v = -v;
1979                 return "-" + (v / 100).toFixed(2);
1980         }
1981 }
1982
1983 var format_short_score = function(score) {
1984         if (!score) {
1985                 return "???";
1986         }
1987         if (score[0] === 'm') {
1988                 if (score[2]) {  // Is a bound.
1989                         return score[2] + "\u00a0M " + score[1];
1990                 } else {
1991                         return "M " + score[1];
1992                 }
1993         } else if (score[0] === 'd') {
1994                 return "TB draw";
1995         } else if (score[0] === 'cp') {
1996                 if (score[2]) {  // Is a bound.
1997                         return score[2] + "\u00a0" + fmt_cp(score[1]);
1998                 } else {
1999                         return fmt_cp(score[1]);
2000                 }
2001         }
2002         return null;
2003 }
2004
2005 var format_long_score = function(score) {
2006         if (!score) {
2007                 return "???";
2008         }
2009         if (score[0] === 'm') {
2010                 if (score[1] > 0) {
2011                         return "White mates in " + score[1];
2012                 } else {
2013                         return "Black mates in " + (-score[1]);
2014                 }
2015         } else if (score[0] === 'd') {
2016                 return "Theoretical draw";
2017         } else if (score[0] === 'cp') {
2018                 return "Score: " + format_short_score(score);
2019         }
2020         return null;
2021 }
2022
2023 var compute_plot_score = function(score) {
2024         if (score[0] === 'm') {
2025                 if (score[1] > 0) {
2026                         return 500;
2027                 } else {
2028                         return -500;
2029                 }
2030         } else if (score[0] === 'd') {
2031                 return 0;
2032         } else if (score[0] === 'cp') {
2033                 if (score[1] > 500) {
2034                         return 500;
2035                 } else if (score[1] < -500) {
2036                         return -500;
2037                 } else {
2038                         return score[1];
2039                 }
2040         }
2041         return null;
2042 }
2043
2044 /**
2045  * @param score The score digest tuple.
2046  * @param {?number} depth Depth the move has been computed to, or null.
2047  * @param {boolean} invert Whether black is to play.
2048  * @return {number}
2049  */
2050 var compute_score_sort_key = function(score, depth, invert) {
2051         var s;
2052         if (!score) {
2053                 return -10000000;
2054         }
2055         if (score[0] === 'm') {
2056                 if (score[1] > 0) {
2057                         // White mates.
2058                         s = 99999 - score[1];
2059                 } else {
2060                         // Black mates (note the double negative for score[1]).
2061                         s = -99999 - score[1];
2062                 }
2063         } else if (score[0] === 'd') {
2064                 s = 0;
2065         } else if (score[0] === 'cp') {
2066                 s = score[1];
2067         }
2068         if (s) {
2069                 if (invert) s = -s;
2070                 return s * 200 + (depth || 0);
2071         } else {
2072                 return null;
2073         }
2074 }
2075
2076 /**
2077  * @param {string} new_backend_url
2078  */
2079 var switch_backend = function(new_backend_url, new_backend_hash_url) {
2080         // Stop looking at historic data.
2081         current_display_line = null;
2082         current_display_move = null;
2083         displayed_analysis_data = null;
2084         if (current_historic_xhr) {
2085                 current_historic_xhr.abort();
2086         }
2087
2088         // If we already have a backend response going, abort it.
2089         if (current_analysis_xhr) {
2090                 current_analysis_xhr.abort();
2091         }
2092         if (current_hash_xhr) {
2093                 current_hash_xhr.abort();
2094         }
2095
2096         // Otherwise, we should have a timer going to start a new one.
2097         // Kill that, too.
2098         if (current_analysis_request_timer) {
2099                 clearTimeout(current_analysis_request_timer);
2100                 current_analysis_request_timer = null;
2101         }
2102         if (current_hash_display_timer) {
2103                 clearTimeout(current_hash_display_timer);
2104                 current_hash_display_timer = null;
2105         }
2106
2107         // Request an immediate fetch with the new backend.
2108         backend_url = new_backend_url;
2109         backend_hash_url = new_backend_hash_url;
2110         current_analysis_data = null;
2111         ims = 0;
2112         request_update();
2113 }
2114 window['switch_backend'] = switch_backend;
2115
2116 var init = function() {
2117         unique = get_unique();
2118
2119         // Load settings from HTML5 local storage if available.
2120         if (supports_html5_storage() && localStorage['enable_sound']) {
2121                 set_sound(parseInt(localStorage['enable_sound']));
2122         } else {
2123                 set_sound(false);
2124         }
2125         if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2126                 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2127         } else {
2128                 sort_refutation_lines_by_score = true;
2129         }
2130
2131         // Create board.
2132         board = new window.ChessBoard('board', {
2133                 onMoveEnd: function() { board_is_animating = false; },
2134
2135                 draggable: true,
2136                 onDragStart: onDragStart,
2137                 onDrop: onDrop,
2138                 onSnapEnd: onSnapEnd
2139         });
2140         $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2141         $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2142
2143         request_update();
2144         $(window).resize(function() {
2145                 board.resize();
2146                 update_sparkline(displayed_analysis_data || current_analysis_data);
2147                 update_board_highlight();
2148                 redraw_arrows();
2149         });
2150         $(window).keyup(function(event) {
2151                 if (event.which == 39) {  // Left arrow.
2152                         next_move();
2153                 } else if (event.which == 37) {  // Right arrow.
2154                         prev_move();
2155                 } else if (event.which >= 49 && event.which <= 57) {  // 1-9.
2156                         var num = event.which - 49;
2157                         if (current_games && current_games.length >= num) {
2158                                 switch_backend(current_games[num]['url'], current_games[num]['hashurl']);
2159                         }
2160                 } else if (event.which == 78) {  // N.
2161                         next_game();
2162                 }
2163         });
2164         window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2165 };
2166 $(document).ready(init);
2167
2168 })();