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