]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
Make move highlighting more robust.
[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 = 2015062104;
11
12 /**
13  * The current backend URL.
14  *
15  * @type {!string}
16  * @private
17  */
18 var backend_url = "/analysis.pl";
19
20 /** @type {window.ChessBoard} @private */
21 var board = null;
22
23 /**
24  * The most recent analysis data we have from the server
25  * (about the most recent position).
26  *
27  * @type {?Object}
28  * @private */
29 var current_analysis_data = null;
30
31 /**
32  * If we are displaying previous analysis, this is non-null,
33  * and will override most of current_analysis_data.
34  *
35  * @type {?Object}
36  * @private
37  */
38 var displayed_analysis_data = null;
39
40 /**
41  * Games currently in progress, if any.
42  *
43  * @type {?Array.<{
44  *      name: string,
45  *      url: string,
46  *      id: string,
47  * }>}
48  * @private
49  */
50 var current_games = null;
51
52 /** @type {Array.<{
53  *      from_col: number,
54  *      from_row: number,
55  *      to_col: number,
56  *      to_row: number,
57  *      line_width: number,
58  *      arrow_size: number,
59  *      fg_color: string
60  * }>}
61  * @private
62  */
63 var arrows = [];
64
65 /** @type {Array.<Array.<boolean>>} */
66 var occupied_by_arrows = [];
67
68 var refutation_lines = [];
69
70 /** @type {!number} @private */
71 var move_num = 1;
72
73 /** @type {!string} @private */
74 var toplay = 'W';
75
76 /** @type {number} @private */
77 var ims = 0;
78
79 /** @type {boolean} @private */
80 var sort_refutation_lines_by_score = true;
81
82 /** @type {boolean} @private */
83 var truncate_display_history = true;
84
85 /** @type {!string|undefined} @private */
86 var highlight_from = undefined;
87
88 /** @type {!string|undefined} @private */
89 var highlight_to = undefined;
90
91 /** The HTML object of the move currently being highlighted (in red).
92  * @type {?jQuery}
93  * @private */
94 var highlighted_move = null;
95
96 /** @type {?number} @private */
97 var unique = null;
98
99 /** @type {boolean} @private */
100 var enable_sound = false;
101
102 /**
103  * Our best estimate of how many milliseconds we need to add to 
104  * new Date() to get the true UTC time. Calibrated against the
105  * server clock.
106  *
107  * @type {?number}
108  * @private
109  */
110 var client_clock_offset_ms = null;
111
112 var clock_timer = null;
113
114 /** The current position on the board, represented as a FEN string.
115  * @type {?string}
116  * @private
117  */
118 var fen = null;
119
120 /** @typedef {{
121  *    start_fen: string,
122  *    pretty_pv: Array.<string>,
123  * }} DisplayLine
124  */
125
126 /** All PVs that we currently know of.
127  *
128  * Element 0 is history (or null if no history).
129  * Element 1 is current main PV.
130  * All remaining elements are refutation lines (multi-PV).
131  *
132  * @type {Array.<DisplayLine>}
133  * @private
134  */
135 var display_lines = [];
136
137 /** @type {?DisplayLine} @private */
138 var current_display_line = null;
139
140 /** @type {boolean} @private */
141 var current_display_line_is_history = false;
142
143 /** @type {?number} @private */
144 var current_display_move = null;
145
146 /**
147  * The current backend request to get main analysis (not history), if any,
148  * so that we can abort it.
149  *
150  * @type {?jqXHR}
151  * @private
152  */
153 var current_analysis_xhr = null;
154
155 /**
156  * The current timer to fire off a request to get main analysis (not history),
157  * if any, so that we can abort it.
158  *
159  * @type {?Number}
160  * @private
161  */
162 var current_analysis_request_timer = null;
163
164 /**
165  * The current backend request to get historic data, if any.
166  *
167  * @type {?jqXHR}
168  * @private
169  */
170 var current_historic_xhr = null;
171
172 var supports_html5_storage = function() {
173         try {
174                 return 'localStorage' in window && window['localStorage'] !== null;
175         } catch (e) {
176                 return false;
177         }
178 }
179
180 // Make the unique token persistent so people refreshing the page won't count twice.
181 // Of course, you can never fully protect against people deliberately wanting to spam.
182 var get_unique = function() {
183         var use_local_storage = supports_html5_storage();
184         if (use_local_storage && localStorage['unique']) {
185                 return localStorage['unique'];
186         }
187         var unique = Math.random();
188         if (use_local_storage) {
189                 localStorage['unique'] = unique;
190         }
191         return unique;
192 }
193
194 var request_update = function() {
195         current_analysis_request_timer = null;
196
197         current_analysis_xhr = $.ajax({
198                 url: backend_url + "?ims=" + ims + "&unique=" + unique
199         }).done(function(data, textstatus, xhr) {
200                 sync_server_clock(xhr.getResponseHeader('Date'));
201                 ims = xhr.getResponseHeader('X-RGLM');
202                 var num_viewers = xhr.getResponseHeader('X-RGNV');
203                 var new_data;
204                 if (Array.isArray(data)) {
205                         new_data = JSON.parse(JSON.stringify(current_analysis_data));
206                         JSON_delta.patch(new_data, data);
207                 } else {
208                         new_data = data;
209                 }
210
211                 var minimum_version = xhr.getResponseHeader('X-RGMV');
212                 if (minimum_version && minimum_version > SCRIPT_VERSION) {
213                         // Upgrade to latest version with a force-reload.
214                         location.reload(true);
215                 }
216
217                 possibly_play_sound(current_analysis_data, new_data);
218                 current_analysis_data = new_data;
219                 update_board();
220                 update_num_viewers(num_viewers);
221
222                 // Next update.
223                 current_analysis_request_timer = setTimeout(function() { request_update(); }, 100);
224         }).fail(function(jqXHR, textStatus, errorThrown) {
225                 if (textStatus === "abort") {
226                         // Aborted because we are switching backends. Abandon and don't retry,
227                         // because another one is already started for us.
228                 } else {
229                         // Backend error or similar. Wait ten seconds, then try again.
230                         current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
231                 }
232         });
233 }
234
235 var possibly_play_sound = function(old_data, new_data) {
236         if (!enable_sound) {
237                 return;
238         }
239         if (old_data === null) {
240                 return;
241         }
242         var ding = document.getElementById('ding');
243         if (ding && ding.play) {
244                 if (old_data['position'] && old_data['position']['fen'] &&
245                     new_data['position'] && new_data['position']['fen'] &&
246                     (old_data['position']['fen'] !== new_data['position']['fen'] ||
247                      old_data['position']['move_num'] !== new_data['position']['move_num'])) {
248                         ding.play();
249                 }
250         }
251 }
252
253 /**
254  * @type {!string} server_date_string
255  */
256 var sync_server_clock = function(server_date_string) {
257         var server_time_ms = new Date(server_date_string).getTime();
258         var client_time_ms = new Date().getTime();
259         var estimated_offset_ms = server_time_ms - client_time_ms;
260
261         // In order not to let the noise move us too much back and forth
262         // (the server only has one-second resolution anyway), we only
263         // change an existing skew if we are at least five seconds off.
264         if (client_clock_offset_ms === null ||
265             Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
266                 client_clock_offset_ms = estimated_offset_ms;
267         }
268 }
269
270 var clear_arrows = function() {
271         for (var i = 0; i < arrows.length; ++i) {
272                 if (arrows[i].svg) {
273                         if (arrows[i].svg.parentElement) {
274                                 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
275                         }
276                         delete arrows[i].svg;
277                 }
278         }
279         arrows = [];
280
281         occupied_by_arrows = [];
282         for (var y = 0; y < 8; ++y) {
283                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
284         }
285 }
286
287 var redraw_arrows = function() {
288         for (var i = 0; i < arrows.length; ++i) {
289                 position_arrow(arrows[i]);
290         }
291 }
292
293 /** @param {!number} x
294  * @return {!number}
295  */
296 var sign = function(x) {
297         if (x > 0) {
298                 return 1;
299         } else if (x < 0) {
300                 return -1;
301         } else {
302                 return 0;
303         }
304 }
305
306 /** See if drawing this arrow on the board would cause unduly amount of confusion.
307  * @param {!string} from The square the arrow is from (e.g. e4).
308  * @param {!string} to The square the arrow is to (e.g. e4).
309  * @return {boolean}
310  */
311 var interfering_arrow = function(from, to) {
312         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
313         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
314         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
315         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
316
317         occupied_by_arrows[from_row][from_col] = true;
318
319         // Knight move: Just check that we haven't been at the destination before.
320         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
321             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
322                 return occupied_by_arrows[to_row][to_col];
323         }
324
325         // Sliding piece: Check if anything except the from-square is seen before.
326         var dx = sign(to_col - from_col);
327         var dy = sign(to_row - from_row);
328         var x = from_col;
329         var y = from_row;
330         do {
331                 x += dx;
332                 y += dy;
333                 if (occupied_by_arrows[y][x]) {
334                         return true;
335                 }
336                 occupied_by_arrows[y][x] = true;
337         } while (x != to_col || y != to_row);
338
339         return false;
340 }
341
342 /** Find a point along the coordinate system given by the given line,
343  * <t> units forward from the start of the line, <u> units to the right of it.
344  * @param {!number} x1
345  * @param {!number} x2
346  * @param {!number} y1
347  * @param {!number} y2
348  * @param {!number} t
349  * @param {!number} u
350  * @return {!string} The point in "x y" form, suitable for SVG paths.
351  */
352 var point_from_start = function(x1, y1, x2, y2, t, u) {
353         var dx = x2 - x1;
354         var dy = y2 - y1;
355
356         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
357         dx *= norm;
358         dy *= norm;
359
360         var x = x1 + dx * t + dy * u;
361         var y = y1 + dy * t - dx * u;
362         return x + " " + y;
363 }
364
365 /** Find a point along the coordinate system given by the given line,
366  * <t> units forward from the end of the line, <u> units to the right of it.
367  * @param {!number} x1
368  * @param {!number} x2
369  * @param {!number} y1
370  * @param {!number} y2
371  * @param {!number} t
372  * @param {!number} u
373  * @return {!string} The point in "x y" form, suitable for SVG paths.
374  */
375 var point_from_end = function(x1, y1, x2, y2, t, u) {
376         var dx = x2 - x1;
377         var dy = y2 - y1;
378
379         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
380         dx *= norm;
381         dy *= norm;
382
383         var x = x2 + dx * t + dy * u;
384         var y = y2 + dy * t - dx * u;
385         return x + " " + y;
386 }
387
388 var position_arrow = function(arrow) {
389         if (arrow.svg) {
390                 if (arrow.svg.parentElement) {
391                         arrow.svg.parentElement.removeChild(arrow.svg);
392                 }
393                 delete arrow.svg;
394         }
395         if (current_display_line !== null && !current_display_line_is_history) {
396                 return;
397         }
398
399         var pos = $(".square-a8").position();
400
401         var zoom_factor = $("#board").width() / 400.0;
402         var line_width = arrow.line_width * zoom_factor;
403         var arrow_size = arrow.arrow_size * zoom_factor;
404
405         var square_width = $(".square-a8").width();
406         var from_y = (7 - arrow.from_row + 0.5)*square_width;
407         var to_y = (7 - arrow.to_row + 0.5)*square_width;
408         var from_x = (arrow.from_col + 0.5)*square_width;
409         var to_x = (arrow.to_col + 0.5)*square_width;
410
411         var SVG_NS = "http://www.w3.org/2000/svg";
412         var XHTML_NS = "http://www.w3.org/1999/xhtml";
413         var svg = document.createElementNS(SVG_NS, "svg");
414         svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
415         svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
416         svg.setAttribute("style", "position: absolute");
417         svg.setAttribute("position", "absolute");
418         svg.setAttribute("version", "1.1");
419         svg.setAttribute("class", "c1");
420         svg.setAttribute("xmlns", XHTML_NS);
421
422         var x1 = from_x;
423         var y1 = from_y;
424         var x2 = to_x;
425         var y2 = to_y;
426
427         // Draw the line.
428         var outline = document.createElementNS(SVG_NS, "path");
429         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));
430         outline.setAttribute("xmlns", XHTML_NS);
431         outline.setAttribute("stroke", "#666");
432         outline.setAttribute("stroke-width", line_width + 2);
433         outline.setAttribute("fill", "none");
434         svg.appendChild(outline);
435
436         var path = document.createElementNS(SVG_NS, "path");
437         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));
438         path.setAttribute("xmlns", XHTML_NS);
439         path.setAttribute("stroke", arrow.fg_color);
440         path.setAttribute("stroke-width", line_width);
441         path.setAttribute("fill", "none");
442         svg.appendChild(path);
443
444         // Then the arrow head.
445         var head = document.createElementNS(SVG_NS, "path");
446         head.setAttribute("d",
447                 "M " +  point_from_end(x1, y1, x2, y2, 0, 0) +
448                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
449                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
450                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
451                 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
452         head.setAttribute("xmlns", XHTML_NS);
453         head.setAttribute("stroke", "#000");
454         head.setAttribute("stroke-width", "1");
455         head.setAttribute("fill", arrow.fg_color);
456         svg.appendChild(head);
457
458         $(svg).css({ top: pos.top, left: pos.left });
459         document.body.appendChild(svg);
460         arrow.svg = svg;
461 }
462
463 /**
464  * @param {!string} from_square
465  * @param {!string} to_square
466  * @param {!string} fg_color
467  * @param {number} line_width
468  * @param {number} arrow_size
469  */
470 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
471         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
472         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
473         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
474         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
475
476         // Create arrow.
477         var arrow = {
478                 from_col: from_col,
479                 from_row: from_row,
480                 to_col: to_col,
481                 to_row: to_row,
482                 line_width: line_width,
483                 arrow_size: arrow_size,
484                 fg_color: fg_color
485         };
486
487         position_arrow(arrow);
488         arrows.push(arrow);
489 }
490
491 var compare_by_sort_key = function(refutation_lines, a, b) {
492         var ska = refutation_lines[a]['sort_key'];
493         var skb = refutation_lines[b]['sort_key'];
494         if (ska < skb) return -1;
495         if (ska > skb) return 1;
496         return 0;
497 };
498
499 var compare_by_score = function(refutation_lines, a, b) {
500         var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
501         var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
502         return sa - sb;
503 }
504
505 /**
506  * Fake multi-PV using the refutation lines. Find all “relevant” moves,
507  * sorted by quality, descending.
508  *
509  * @param {!Object} data
510  * @param {number} margin The maximum number of centipawns worse than the
511  *     best move can be and still be included.
512  * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
513  *     moves, in score order.
514  */
515 var find_nonstupid_moves = function(data, margin) {
516         // First of all, if there are any moves that are more than 0.5 ahead of
517         // the primary move, the refutation lines are probably bunk, so just
518         // kill them all. 
519         var best_score = undefined;
520         var pv_score = undefined;
521         for (var move in data['refutation_lines']) {
522                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
523                 if (move == data['pv_uci'][0]) {
524                         pv_score = score;
525                 }
526                 if (best_score === undefined || score > best_score) {
527                         best_score = score;
528                 }
529                 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
530                         return [];
531                 }
532         }
533
534         if (best_score - pv_score > 50) {
535                 return [];
536         }
537
538         // Now find all moves that are within “margin” of the best score.
539         // The PV move will always be first.
540         var moves = [];
541         for (var move in data['refutation_lines']) {
542                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
543                 if (move != data['pv_uci'][0] && best_score - score <= margin) {
544                         moves.push(move);
545                 }
546         }
547         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
548         moves.unshift(data['pv_uci'][0]);
549
550         return moves;
551 }
552
553 /**
554  * @param {number} x
555  * @return {!string}
556  */
557 var thousands = function(x) {
558         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
559 }
560
561 /**
562  * @param {!string} fen
563  * @param {Array.<string>} pretty_pv
564  * @param {number} move_num
565  * @param {!string} toplay
566  * @param {number=} opt_limit
567  * @param {boolean=} opt_showlast
568  */
569 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
570         display_lines.push({
571                 start_fen: fen,
572                 pretty_pv: pretty_pv,
573         });
574         return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
575 }
576
577 /**
578  * @param {number} line_num
579  * @param {Array.<string>} pretty_pv
580  * @param {number} move_num
581  * @param {!string} toplay
582  * @param {number=} opt_limit
583  * @param {boolean=} opt_showlast
584  */
585 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
586         var pv = '';
587         var i = 0;
588         if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
589                 // Truncate the PV at the beginning (instead of at the end).
590                 // We assume here that toplay is 'W'. We also assume that if
591                 // opt_showlast is set, then it is the history, and thus,
592                 // the UI should be to expand the history.
593                 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
594                 i = pretty_pv.length - opt_limit;
595                 if (i % 2 == 1) {
596                         ++i;
597                 }
598                 move_num += i / 2;
599         } else if (toplay == 'B' && pretty_pv.length > 0) {
600                 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
601                 pv = move_num + '. … ' + move;
602                 toplay = 'W';
603                 ++i;
604                 ++move_num;
605         }
606         for ( ; i < pretty_pv.length; ++i) {
607                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
608
609                 if (toplay == 'W') {
610                         if (i > opt_limit && !opt_showlast) {
611                                 return pv + ' (…)';
612                         }
613                         if (pv != '') {
614                                 pv += ' ';
615                         }
616                         pv += move_num + '. ' + move;
617                         ++move_num;
618                         toplay = 'B';
619                 } else {
620                         pv += ' ' + move;
621                         toplay = 'W';
622                 }
623         }
624         return pv;
625 }
626
627 /** Update the highlighted to/from squares on the board.
628  * Based on the global "highlight_from" and "highlight_to" variables.
629  */
630 var update_board_highlight = function() {
631         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
632         if ((current_display_line === null || current_display_line_is_history) &&
633             highlight_from !== undefined && highlight_to !== undefined) {
634                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
635                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
636         }
637 }
638
639 var update_history = function() {
640         if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
641                 $("#history").html("No history");
642         } else if (truncate_display_history) {
643                 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
644         } else {
645                 $("#history").html(
646                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
647                         print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
648         }
649 }
650
651 /**
652  * @param {!boolean} truncate_history
653  */
654 var collapse_history = function(truncate_history) {
655         truncate_display_history = truncate_history;
656         update_history();
657 }
658 window['collapse_history'] = collapse_history;
659
660 /** Update the HTML display of multi-PV from the global "refutation_lines".
661  *
662  * Also recreates the global "display_lines".
663  */
664 var update_refutation_lines = function() {
665         if (fen === null) {
666                 return;
667         }
668         if (display_lines.length > 2) {
669                 // Truncate so that only the history and PV is left.
670                 display_lines = [ display_lines[0], display_lines[1] ];
671         }
672
673         var tbl = $("#refutationlines");
674         tbl.empty();
675
676         var moves = [];
677         for (var move in refutation_lines) {
678                 moves.push(move);
679         }
680         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
681         moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
682         for (var i = 0; i < moves.length; ++i) {
683                 var line = refutation_lines[moves[i]];
684
685                 var tr = document.createElement("tr");
686
687                 var move_td = document.createElement("td");
688                 tr.appendChild(move_td);
689                 $(move_td).addClass("move");
690                 if (line['pv_pretty'].length == 0) {
691                         $(move_td).text(line['pretty_move']);
692                 } else {
693                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
694                         $(move_td).html(move);
695                 }
696
697                 var score_td = document.createElement("td");
698                 tr.appendChild(score_td);
699                 $(score_td).addClass("score");
700                 $(score_td).text(line['pretty_score']);
701
702                 var depth_td = document.createElement("td");
703                 tr.appendChild(depth_td);
704                 $(depth_td).addClass("depth");
705                 $(depth_td).text("d" + line['depth']);
706
707                 var pv_td = document.createElement("td");
708                 tr.appendChild(pv_td);
709                 $(pv_td).addClass("pv");
710                 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
711
712                 tbl.append(tr);
713         }
714
715         // Make one of the links clickable and the other nonclickable.
716         if (sort_refutation_lines_by_score) {
717                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
718                 $("#sortbyscore1").html("<strong>Score</strong>");
719         } else {
720                 $("#sortbyscore0").html("<strong>Move</strong>");
721                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
722         }
723
724         // Update the move highlight, as we've rewritten all the HTML.
725         update_move_highlight();
726 }
727
728 /**
729  * Create a Chess.js board object, containing the given position plus the given moves,
730  * up to the given limit.
731  *
732  * @param {?string} fen
733  * @param {Array.<string>} moves
734  * @param {number} last_move
735  */
736 var chess_from = function(fen, moves, last_move) {
737         var hiddenboard = new Chess();
738         if (fen !== null) {
739                 hiddenboard.load(fen);
740         }
741         for (var i = 0; i <= last_move; ++i) {
742                 if (moves[i] === '0-0') {
743                         hiddenboard.move('O-O');
744                 } else if (moves[i] === '0-0-0') {
745                         hiddenboard.move('O-O-O');
746                 } else {
747                         hiddenboard.move(moves[i]);
748                 }
749         }
750         return hiddenboard;
751 }
752
753 var update_game_list = function(games) {
754         $("#games").text("");
755         if (games === null) {
756                 return;
757         }
758
759         var games_div = document.getElementById('games');
760         for (var game_num = 0; game_num < games.length; ++game_num) {
761                 var game = games[game_num];
762                 var game_span = document.createElement("span");
763                 game_span.setAttribute("class", "game");
764
765                 var game_name = document.createTextNode(game['name']);
766                 if (game['url'] === backend_url) {
767                         game_span.appendChild(game_name);
768                 } else {
769                         var game_a = document.createElement("a");
770                         game_a.setAttribute("href", "#" + game['id']);
771                         game_a.appendChild(game_name);
772                         game_span.appendChild(game_a);
773                 }
774                 games_div.appendChild(game_span);
775         }
776 }
777
778 /**
779  * Try to find a running game that matches with the current hash,
780  * and switch to it if we're not already displaying it.
781  */
782 var possibly_switch_game_from_hash = function() {
783         if (current_games === null) {
784                 return;
785         }
786
787         var hash = window.location.hash.replace(/^#/,'');
788         for (var i = 0; i < current_games.length; ++i) {
789                 if (current_games[i]['id'] === hash) {
790                         if (backend_url !== current_games[i]['url']) {
791                                 switch_backend(current_games[i]['url']);
792                         }
793                         return;
794                 }
795         }
796 }
797
798 /** Update all the HTML on the page, based on current global state.
799  */
800 var update_board = function() {
801         var data = displayed_analysis_data || current_analysis_data;
802         var current_data = current_analysis_data;  // Convenience alias.
803
804         display_lines = [];
805
806         // Print the history. This is pretty much the only thing that's
807         // unconditionally taken from current_data (we're not interested in
808         // historic history).
809         if (current_data['position']['pretty_history']) {
810                 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
811         } else {
812                 display_lines.push(null);
813         }
814         update_history();
815
816         // Games currently in progress, if any.
817         if (current_data['games']) {
818                 current_games = current_data['games'];
819                 possibly_switch_game_from_hash();
820                 update_game_list(current_data['games']);
821         } else {
822                 current_games = null;
823                 update_game_list(null);
824         }
825
826         // The headline. Names are always fetched from current_data;
827         // the rest can depend a bit.
828         var headline;
829         if (current_data &&
830             current_data['position']['player_w'] && current_data['position']['player_b']) {
831                 headline = current_data['position']['player_w'] + '–' +
832                         current_data['position']['player_b'] + ', analysis';
833         } else {
834                 headline = 'Analysis';
835         }
836
837         // Credits, where applicable. Note that we don't want the footer to change a lot
838         // when e.g. viewing history, so if any of these changed during the game,
839         // use the current one still.
840         if (current_data['using_lomonosov']) {
841                 $("#lomonosov").show();
842         } else {
843                 $("#lomonosov").hide();
844         }
845
846         // Credits: The engine name/version.
847         if (current_data['engine'] && current_data['engine']['name'] !== null) {
848                 $("#engineid").text(current_data['engine']['name']);
849         }
850
851         // Credits: The engine URL.
852         if (current_data['engine'] && current_data['engine']['url']) {
853                 $("#engineid").attr("href", current_data['engine']['url']);
854         } else {
855                 $("#engineid").removeAttr("href");
856         }
857
858         // Credits: Engine details.
859         if (current_data['engine'] && current_data['engine']['details']) {
860                 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
861         } else {
862                 $("#enginedetails").text("");
863         }
864
865         // Credits: Move source, possibly with URL.
866         if (current_data['move_source'] && current_data['move_source_url']) {
867                 $("#movesource").text("Moves provided by ");
868                 var movesource_a = document.createElement("a");
869                 movesource_a.setAttribute("href", current_data['move_source_url']);
870                 var movesource_text = document.createTextNode(current_data['move_source']);
871                 movesource_a.appendChild(movesource_text);
872                 var movesource_period = document.createTextNode(".");
873                 document.getElementById("movesource").appendChild(movesource_a);
874                 document.getElementById("movesource").appendChild(movesource_period);
875         } else if (current_data['move_source']) {
876                 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
877         } else {
878                 $("#movesource").text("");
879         }
880
881         var last_move;
882         if (displayed_analysis_data) {
883                 // Displaying some non-current position, pick out the last move
884                 // from the history. This will work even if the fetch failed.
885                 last_move = format_halfmove_with_number(
886                         current_display_line.pretty_pv[current_display_move],
887                         current_display_move + 1);
888                 headline += ' after ' + last_move;
889         } else if (data['position']['last_move'] !== 'none') {
890                 last_move = format_move_with_number(
891                         data['position']['last_move'],
892                         data['position']['move_num'],
893                         data['position']['toplay'] == 'W');
894                 headline += ' after ' + last_move;
895         } else {
896                 last_move = null;
897         }
898         $("#headline").text(headline);
899
900         // The <title> contains a very brief headline.
901         var title_elems = [];
902         if (data['short_score'] !== undefined && data['short_score'] !== null) {
903                 title_elems.push(data['short_score'].replace(/^ /, ""));
904         }
905         if (last_move !== null) {
906                 title_elems.push(last_move);
907         }
908
909         if (title_elems.length != 0) {
910                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
911         } else {
912                 document.title = 'analysis.sesse.net';
913         }
914
915         // The last move (shown by highlighting the from and to squares).
916         if (data['position'] && data['position']['last_move_uci']) {
917                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
918                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
919         } else if (current_display_line_is_history && current_display_move >= 0) {
920                 // We don't have historic analysis for this position, but we
921                 // can reconstruct what the last move was by just replaying
922                 // from the start.
923                 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
924                 var moves = hiddenboard.history({ verbose: true });
925                 var last_move = moves.pop();
926                 highlight_from = last_move.from;
927                 highlight_to = last_move.to;
928         } else {
929                 highlight_from = highlight_to = undefined;
930         }
931         update_board_highlight();
932
933         if (data['failed']) {
934                 $("#score").text("No analysis for this move");
935                 $("#pvtitle").text("PV:");
936                 $("#pv").empty();
937                 $("#searchstats").html("&nbsp;");
938                 $("#refutationlines").empty();
939                 $("#whiteclock").empty();
940                 $("#blackclock").empty();
941                 refutation_lines = [];
942                 update_refutation_lines();
943                 clear_arrows();
944                 update_displayed_line();
945                 update_move_highlight();
946                 return;
947         }
948
949         update_clock();
950
951         // The score.
952         if (data['score'] !== null) {
953                 $("#score").text(data['score']);
954         }
955
956         // The search stats.
957         if (data['tablebase'] == 1) {
958                 $("#searchstats").text("Tablebase result");
959         } else if (data['nodes'] && data['nps'] && data['depth']) {
960                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
961                 if (data['seldepth']) {
962                         stats += ' (' + data['seldepth'] + ' selective)';
963                 }
964                 if (data['tbhits'] && data['tbhits'] > 0) {
965                         if (data['tbhits'] == 1) {
966                                 stats += ', one Syzygy hit';
967                         } else {
968                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
969                         }
970                 }
971
972                 $("#searchstats").text(stats);
973         } else {
974                 $("#searchstats").text("");
975         }
976
977         // Update the board itself.
978         fen = data['position']['fen'];
979         update_displayed_line();
980
981         // Print the PV.
982         $("#pvtitle").text("PV:");
983         $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
984
985         // Update the PV arrow.
986         clear_arrows();
987         if (data['pv_uci'].length >= 1) {
988                 // draw a continuation arrow as long as it's the same piece
989                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
990                         var from = data['pv_uci'][i].substr(0, 2);
991                         var to = data['pv_uci'][i].substr(2,4);
992                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
993                              interfering_arrow(from, to)) {
994                                 break;
995                         }
996                         create_arrow(from, to, '#f66', 6, 20);
997                 }
998
999                 var alt_moves = find_nonstupid_moves(data, 30);
1000                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1001                         create_arrow(alt_moves[i].substr(0, 2),
1002                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
1003                 }
1004         }
1005
1006         // See if all semi-reasonable moves have only one possible response.
1007         if (data['pv_uci'].length >= 2) {
1008                 var nonstupid_moves = find_nonstupid_moves(data, 300);
1009                 var response = data['pv_uci'][1];
1010                 for (var i = 0; i < nonstupid_moves.length; ++i) {
1011                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
1012                                 // ignore the PV move for refutation lines.
1013                                 continue;
1014                         }
1015                         if (!data['refutation_lines'] ||
1016                             !data['refutation_lines'][nonstupid_moves[i]] ||
1017                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1018                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1019                                 // Incomplete PV, abort.
1020                                 response = undefined;
1021                                 break;
1022                         }
1023                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1024                         if (response !== this_response) {
1025                                 // Different response depending on lines, abort.
1026                                 response = undefined;
1027                                 break;
1028                         }
1029                 }
1030
1031                 if (nonstupid_moves.length > 0 && response !== undefined) {
1032                         create_arrow(response.substr(0, 2),
1033                                      response.substr(2, 2), '#66f', 6, 20);
1034                 }
1035         }
1036
1037         // Update the refutation lines.
1038         fen = data['position']['fen'];
1039         move_num = data['position']['move_num'];
1040         toplay = data['position']['toplay'];
1041         refutation_lines = data['refutation_lines'];
1042         update_refutation_lines();
1043
1044         // Update the sparkline last, since its size depends on how everything else reflowed.
1045         update_sparkline(data);
1046 }
1047
1048 var update_sparkline = function(data) {
1049         if (data && data['score_history']) {
1050                 var first_move_num = undefined;
1051                 for (var halfmove_num in data['score_history']) {
1052                         halfmove_num = parseInt(halfmove_num);
1053                         if (first_move_num === undefined || halfmove_num < first_move_num) {
1054                                 first_move_num = halfmove_num;
1055                         }
1056                 }
1057                 if (first_move_num !== undefined) {
1058                         var last_move_num = data['position']['move_num'] * 2 - 3;
1059                         if (data['position']['toplay'] === 'B') {
1060                                 ++last_move_num;
1061                         }
1062
1063                         // Possibly truncate some moves if we don't have enough width.
1064                         // FIXME: Sometimes width() for #scorecontainer (and by extent,
1065                         // #scoresparkcontainer) on Chrome for mobile seems to start off
1066                         // at something very small, and then suddenly snap back into place.
1067                         // Figure out why.
1068                         var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1069                         if (last_move_num - first_move_num > max_moves) {
1070                                 first_move_num = last_move_num - max_moves;
1071                         }
1072
1073                         var min_score = -100;
1074                         var max_score = 100;
1075                         var last_score = null;
1076                         var scores = [];
1077                         for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1078                                 if (data['score_history'][halfmove_num]) {
1079                                         var score = data['score_history'][halfmove_num][0];
1080                                         if (score < min_score) min_score = score;
1081                                         if (score > max_score) max_score = score;
1082                                         last_score = data['score_history'][halfmove_num][0];
1083                                 }
1084                                 scores.push(last_score);
1085                         }
1086                         if (data['plot_score']) {
1087                                 scores.push(data['plot_score']);
1088                         }
1089                         // FIXME: at some widths, calling sparkline() seems to push
1090                         // #scorecontainer under the board.
1091                         $("#scorespark").sparkline(scores, {
1092                                 type: 'bar',
1093                                 zeroColor: 'gray',
1094                                 chartRangeMin: min_score,
1095                                 chartRangeMax: max_score,
1096                                 tooltipFormatter: function(sparkline, options, fields) {
1097                                         return format_tooltip(data, fields[0].offset + first_move_num);
1098                                 }
1099                         });
1100                 } else {
1101                         $("#scorespark").text("");
1102                 }
1103         } else {
1104                 $("#scorespark").text("");
1105         }
1106 }
1107
1108 /**
1109  * @param {number} num_viewers
1110  */
1111 var update_num_viewers = function(num_viewers) {
1112         if (num_viewers === null) {
1113                 $("#numviewers").text("");
1114         } else if (num_viewers == 1) {
1115                 $("#numviewers").text("You are the only current viewer");
1116         } else {
1117                 $("#numviewers").text(num_viewers + " current viewers");
1118         }
1119 }
1120
1121 var update_clock = function() {
1122         clearTimeout(clock_timer);
1123
1124         var data = displayed_analysis_data || current_analysis_data;
1125         if (data['position']) {
1126                 var result = data['position']['result'];
1127                 if (result === '1-0') {
1128                         $("#whiteclock").text("1");
1129                         $("#blackclock").text("0");
1130                         $("#whiteclock").removeClass("running-clock");
1131                         $("#blackclock").removeClass("running-clock");
1132                         return;
1133                 }
1134                 if (result === '1/2-1/2') {
1135                         $("#whiteclock").text("1/2");
1136                         $("#blackclock").text("1/2");
1137                         $("#whiteclock").removeClass("running-clock");
1138                         $("#blackclock").removeClass("running-clock");
1139                         return;
1140                 }       
1141                 if (result === '0-1') {
1142                         $("#whiteclock").text("0");
1143                         $("#blackclock").text("1");
1144                         $("#whiteclock").removeClass("running-clock");
1145                         $("#blackclock").removeClass("running-clock");
1146                         return;
1147                 }
1148         }
1149
1150         var white_clock_ms = null;
1151         var black_clock_ms = null;
1152         var show_seconds = false;
1153
1154         // Static clocks.
1155         if (data['position'] &&
1156             data['position']['white_clock'] &&
1157             data['position']['black_clock']) {
1158                 white_clock_ms = data['position']['white_clock'] * 1000;
1159                 black_clock_ms = data['position']['black_clock'] * 1000;
1160         }
1161
1162         // Dynamic clock (only one, obviously).
1163         var color;
1164         if (data['position']['white_clock_target']) {
1165                 color = "white";
1166                 $("#whiteclock").addClass("running-clock");
1167                 $("#blackclock").removeClass("running-clock");
1168         } else if (data['position']['black_clock_target']) {
1169                 color = "black";
1170                 $("#whiteclock").removeClass("running-clock");
1171                 $("#blackclock").addClass("running-clock");
1172         } else {
1173                 $("#whiteclock").removeClass("running-clock");
1174                 $("#blackclock").removeClass("running-clock");
1175         }
1176         var remaining_ms;
1177         if (color) {
1178                 var now = new Date().getTime() + client_clock_offset_ms;
1179                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1180                 if (color === "white") {
1181                         white_clock_ms = remaining_ms;
1182                 } else {
1183                         black_clock_ms = remaining_ms;
1184                 }
1185         }
1186
1187         if (white_clock_ms === null || black_clock_ms === null) {
1188                 $("#whiteclock").empty();
1189                 $("#blackclock").empty();
1190                 return;
1191         }
1192
1193         // If either player has ten minutes or less left, add the second counters.
1194         var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1195
1196         if (color) {
1197                 // See when the clock will change next, and update right after that.
1198                 var next_update_ms;
1199                 if (show_seconds) {
1200                         next_update_ms = remaining_ms % 1000 + 100;
1201                 } else {
1202                         next_update_ms = remaining_ms % 60000 + 100;
1203                 }
1204                 clock_timer = setTimeout(update_clock, next_update_ms);
1205         }
1206
1207         $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1208         $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1209 }
1210
1211 /**
1212  * @param {Number} remaining_ms
1213  * @param {boolean} show_seconds
1214  */
1215 var format_clock = function(remaining_ms, show_seconds) {
1216         if (remaining_ms <= 0) {
1217                 if (show_seconds) {
1218                         return "00:00:00";
1219                 } else {
1220                         return "00:00";
1221                 }
1222         }
1223
1224         var remaining = Math.floor(remaining_ms / 1000);
1225         var seconds = remaining % 60;
1226         remaining = (remaining - seconds) / 60;
1227         var minutes = remaining % 60;
1228         remaining = (remaining - minutes) / 60;
1229         var hours = remaining;
1230         if (show_seconds) {
1231                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1232         } else {
1233                 return format_2d(hours) + ":" + format_2d(minutes);
1234         }
1235 }
1236
1237 /**
1238  * @param {Number} x
1239  */
1240 var format_2d = function(x) {
1241         if (x >= 10) {
1242                 return x;
1243         } else {
1244                 return "0" + x;
1245         }
1246 }
1247
1248 /**
1249  * @param {string} move
1250  * @param {Number} move_num
1251  * @param {boolean} white_to_play
1252  */
1253 var format_move_with_number = function(move, move_num, white_to_play) {
1254         var ret;
1255         if (white_to_play) {
1256                 ret = (move_num - 1) + '… ';
1257         } else {
1258                 ret = move_num + '. ';
1259         }
1260         ret += move;
1261         return ret;
1262 }
1263
1264 /**
1265  * @param {string} move
1266  * @param {Number} halfmove_num
1267  */
1268 var format_halfmove_with_number = function(move, halfmove_num) {
1269         return format_move_with_number(
1270                 move,
1271                 Math.floor(halfmove_num / 2) + 1,
1272                 halfmove_num % 2 == 0);
1273 }
1274
1275 /**
1276  * @param {Object} data
1277  * @param {Number} halfmove_num
1278  */
1279 var format_tooltip = function(data, halfmove_num) {
1280         if (data['score_history'][halfmove_num] ||
1281             halfmove_num === data['position']['pretty_history'].length) {
1282                 var move;
1283                 var short_score;
1284                 if (halfmove_num === data['position']['pretty_history'].length) {
1285                         move = data['position']['last_move'];
1286                         short_score = data['short_score'];
1287                 } else {
1288                         move = data['position']['pretty_history'][halfmove_num];
1289                         short_score = data['score_history'][halfmove_num][1];
1290                 }
1291                 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1292
1293                 return "After " + move_with_number + ": " + short_score;
1294         } else {
1295                 for (var i = halfmove_num; i --> 0; ) {
1296                         if (data['score_history'][i]) {
1297                                 var move = data['position']['pretty_history'][i];
1298                                 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1299                         }
1300                 }
1301         }
1302 }
1303
1304 /**
1305  * @param {boolean} sort_by_score
1306  */
1307 var resort_refutation_lines = function(sort_by_score) {
1308         sort_refutation_lines_by_score = sort_by_score;
1309         if (supports_html5_storage()) {
1310                 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1311         }
1312         update_refutation_lines();
1313 }
1314 window['resort_refutation_lines'] = resort_refutation_lines;
1315
1316 /**
1317  * @param {boolean} truncate_history
1318  */
1319 var set_truncate_history = function(truncate_history) {
1320         truncate_display_history = truncate_history;
1321         update_refutation_lines();
1322 }
1323 window['set_truncate_history'] = set_truncate_history;
1324
1325 /**
1326  * @param {number} line_num
1327  * @param {number} move_num
1328  */
1329 var show_line = function(line_num, move_num) {
1330         if (line_num == -1) {
1331                 current_display_line = null;
1332                 current_display_move = null;
1333                 if (displayed_analysis_data) {
1334                         // TODO: Support exiting to history position if we are in an
1335                         // analysis line of a history position.
1336                         displayed_analysis_data = null;
1337                         update_board();
1338                 }
1339         } else {
1340                 current_display_line = jQuery.extend({}, display_lines[line_num]);  // Shallow clone.
1341                 current_display_move = move_num;
1342         }
1343         current_display_line_is_history = (line_num == 0);
1344
1345         update_historic_analysis();
1346         update_displayed_line();
1347         update_board_highlight();
1348         update_move_highlight();
1349         redraw_arrows();
1350 }
1351 window['show_line'] = show_line;
1352
1353 var prev_move = function() {
1354         if (current_display_move > -1) {
1355                 --current_display_move;
1356         }
1357         update_historic_analysis();
1358         update_displayed_line();
1359         update_move_highlight();
1360 }
1361 window['prev_move'] = prev_move;
1362
1363 var next_move = function() {
1364         if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1365                 ++current_display_move;
1366         }
1367         update_historic_analysis();
1368         update_displayed_line();
1369         update_move_highlight();
1370 }
1371 window['next_move'] = next_move;
1372
1373 var update_historic_analysis = function() {
1374         if (!current_display_line_is_history) {
1375                 return;
1376         }
1377         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1378                 displayed_analysis_data = null;
1379                 update_board();
1380         }
1381
1382         // Fetch old analysis for this line if it exists.
1383         var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1384         var filename = "/history/move" + (current_display_move + 1) + "-" +
1385                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1386
1387         current_historic_xhr = $.ajax({
1388                 url: filename
1389         }).done(function(data, textstatus, xhr) {
1390                 displayed_analysis_data = data;
1391                 update_board();
1392         }).fail(function(jqXHR, textStatus, errorThrown) {
1393                 if (textStatus === "abort") {
1394                         // Aborted because we are switching backends. Don't do anything;
1395                         // we will already have been cleared.
1396                 } else {
1397                         displayed_analysis_data = {'failed': true};
1398                         update_board();
1399                 }
1400         });
1401 }
1402
1403 /**
1404  * @param {string} fen
1405  */
1406 var update_imbalance = function(fen) {
1407         var hiddenboard = new Chess(fen);
1408         var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1409         for (var row = 0; row < 8; ++row) {
1410                 for (var col = 0; col < 8; ++col) {
1411                         var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1412                         var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1413                         var square = col_text + row_text;
1414                         var contents = hiddenboard.get(square);
1415                         if (contents !== null) {
1416                                 if (contents.color === 'w') {
1417                                         ++imbalance[contents.type];
1418                                 } else {
1419                                         --imbalance[contents.type];
1420                                 }
1421                         }
1422                 }
1423         }
1424         var white_imbalance = '';
1425         var black_imbalance = '';
1426         for (var piece in imbalance) {
1427                 for (var i = 0; i < imbalance[piece]; ++i) {
1428                         white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1429                 }
1430                 for (var i = 0; i < -imbalance[piece]; ++i) {
1431                         black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1432                 }
1433         }
1434         $('#whiteimbalance').html(white_imbalance);
1435         $('#blackimbalance').html(black_imbalance);
1436 }
1437
1438 /** Mark the currently selected move in red.
1439  */
1440 var update_move_highlight = function() {
1441         if (highlighted_move !== null) {
1442                 highlighted_move.removeClass('highlight'); 
1443         }
1444         if (current_display_line) {
1445                 // See if the current displayed line is identical to any of the ones
1446                 // we have on screen. (It might not be if e.g. the analysis reloaded
1447                 // since we started looking.)
1448                 for (var i = 0; i < display_lines.length; ++i) {
1449                         var line = display_lines[i];
1450                         if (current_display_line.start_fen !== line.start_fen) continue;
1451                         if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1452                         var ok = true;
1453                         for (var j = 0; j < line.pretty_pv.length; ++j) {
1454                                 if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1455                                         ok = false;
1456                                         break;
1457                                 }
1458                         }
1459                         if (ok) {
1460                                 highlighted_move = $("#automove" + i + "-" + current_display_move);
1461                                 highlighted_move.addClass('highlight');
1462                                 break;
1463                         }
1464                 }
1465         }
1466 }
1467
1468 var update_displayed_line = function() {
1469         if (current_display_line === null) {
1470                 $("#linenav").hide();
1471                 $("#linemsg").show();
1472                 board.position(fen);
1473                 update_imbalance(fen);
1474                 return;
1475         }
1476
1477         $("#linenav").show();
1478         $("#linemsg").hide();
1479
1480         if (current_display_move <= 0) {
1481                 $("#prevmove").html("Previous");
1482         } else {
1483                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1484         }
1485         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1486                 $("#nextmove").html("Next");
1487         } else {
1488                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1489         }
1490
1491         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1492         board.position(hiddenboard.fen());
1493         update_imbalance(hiddenboard.fen());
1494 }
1495
1496 /**
1497  * @param {boolean} param_enable_sound
1498  */
1499 var set_sound = function(param_enable_sound) {
1500         enable_sound = param_enable_sound;
1501         if (enable_sound) {
1502                 $("#soundon").html("<strong>On</strong>");
1503                 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1504
1505                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1506                 // and also preload the file since the user has selected audio.
1507                 var ding = document.getElementById('ding');
1508                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1509                         ding.src = 'ding.opus';
1510                         ding.load();
1511                 }
1512         } else {
1513                 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1514                 $("#soundoff").html("<strong>Off</strong>");
1515         }
1516         if (supports_html5_storage()) {
1517                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1518         }
1519 }
1520 window['set_sound'] = set_sound;
1521
1522 /**
1523  * @param {string} new_backend_url
1524  */
1525 var switch_backend = function(new_backend_url) {
1526         // Stop looking at historic data.
1527         current_display_line = null;
1528         current_display_move = null;
1529         displayed_analysis_data = null;
1530         if (current_historic_xhr) {
1531                 current_historic_xhr.abort();
1532         }
1533
1534         // If we already have a backend response going, abort it.
1535         if (current_analysis_xhr) {
1536                 current_analysis_xhr.abort();
1537         }
1538
1539         // Otherwise, we should have a timer going to start a new one.
1540         // Kill that, too.
1541         if (current_analysis_request_timer) {
1542                 clearTimeout(current_analysis_request_timer);
1543                 current_analysis_request_timer = null;
1544         }
1545
1546         // Request an immediate fetch with the new backend.
1547         backend_url = new_backend_url;
1548         current_analysis_data = null;
1549         ims = 0;
1550         request_update();
1551 }
1552 window['switch_backend'] = switch_backend;
1553
1554 var init = function() {
1555         unique = get_unique();
1556
1557         // Load settings from HTML5 local storage if available.
1558         if (supports_html5_storage() && localStorage['enable_sound']) {
1559                 set_sound(parseInt(localStorage['enable_sound']));
1560         } else {
1561                 set_sound(false);
1562         }
1563         if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1564                 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1565         } else {
1566                 sort_refutation_lines_by_score = true;
1567         }
1568
1569         // Create board.
1570         board = new window.ChessBoard('board', 'start');
1571
1572         request_update();
1573         $(window).resize(function() {
1574                 board.resize();
1575                 update_sparkline(displayed_analysis_data || current_analysis_data);
1576                 update_board_highlight();
1577                 redraw_arrows();
1578         });
1579         $(window).keyup(function(event) {
1580                 if (event.which == 39) {
1581                         next_move();
1582                 } else if (event.which == 37) {
1583                         prev_move();
1584                 }
1585         });
1586         window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
1587 };
1588 $(document).ready(init);
1589
1590 })();