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