0cca9fa3dbc1e58ee15718dc87f5f4b80ac2ccf1
[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 /** @type {?jQuery} @private */
92 var highlighted_move = null;
93
94 /** @type {?number} @private */
95 var unique = null;
96
97 /** @type {boolean} @private */
98 var enable_sound = false;
99
100 /**
101  * Our best estimate of how many milliseconds we need to add to 
102  * new Date() to get the true UTC time. Calibrated against the
103  * server clock.
104  *
105  * @type {?number}
106  * @private
107  */
108 var client_clock_offset_ms = null;
109
110 var clock_timer = null;
111
112 /** The current position on the board, represented as a FEN string.
113  * @type {?string}
114  * @private
115  */
116 var fen = null;
117
118 /** @typedef {{
119  *    start_fen: string,
120  *    uci_pv: Array.<string>,
121  *    pretty_pv: Array.<string>,
122  *    line_num: number
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(current_analysis_data, displayed_analysis_data);
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                 line_number: display_lines.length
574         });
575         return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
576 }
577
578 /**
579  * @param {number} line_num
580  * @param {Array.<string>} pretty_pv
581  * @param {number} move_num
582  * @param {!string} toplay
583  * @param {number=} opt_limit
584  * @param {boolean=} opt_showlast
585  */
586 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
587         var pv = '';
588         var i = 0;
589         if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
590                 // Truncate the PV at the beginning (instead of at the end).
591                 // We assume here that toplay is 'W'. We also assume that if
592                 // opt_showlast is set, then it is the history, and thus,
593                 // the UI should be to expand the history.
594                 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
595                 i = pretty_pv.length - opt_limit;
596                 if (i % 2 == 1) {
597                         ++i;
598                 }
599                 move_num += i / 2;
600         } else if (toplay == 'B' && pretty_pv.length > 0) {
601                 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
602                 pv = move_num + '. … ' + move;
603                 toplay = 'W';
604                 ++i;
605                 ++move_num;
606         }
607         for ( ; i < pretty_pv.length; ++i) {
608                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
609
610                 if (toplay == 'W') {
611                         if (i > opt_limit && !opt_showlast) {
612                                 return pv + ' (…)';
613                         }
614                         if (pv != '') {
615                                 pv += ' ';
616                         }
617                         pv += move_num + '. ' + move;
618                         ++move_num;
619                         toplay = 'B';
620                 } else {
621                         pv += ' ' + move;
622                         toplay = 'W';
623                 }
624         }
625         return pv;
626 }
627
628 var update_highlight = function() {
629         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
630         if ((current_display_line === null || current_display_line_is_history) &&
631             highlight_from !== undefined && highlight_to !== undefined) {
632                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
633                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
634         }
635 }
636
637 var update_history = function() {
638         if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
639                 $("#history").html("No history");
640         } else if (truncate_display_history) {
641                 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
642         } else {
643                 $("#history").html(
644                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
645                         print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
646         }
647 }
648
649 /**
650  * @param {!boolean} truncate_history
651  */
652 var collapse_history = function(truncate_history) {
653         truncate_display_history = truncate_history;
654         update_history();
655 }
656 window['collapse_history'] = collapse_history;
657
658 /** Update the HTML display of multi-PV from the global "refutation_lines".
659  *
660  * Also recreates the global "display_lines".
661  */
662 var update_refutation_lines = function() {
663         if (fen === null) {
664                 return;
665         }
666         if (display_lines.length > 2) {
667                 // Truncate so that only the history and PV is left.
668                 display_lines = [ display_lines[0], display_lines[1] ];
669         }
670
671         var tbl = $("#refutationlines");
672         tbl.empty();
673
674         var moves = [];
675         for (var move in refutation_lines) {
676                 moves.push(move);
677         }
678         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
679         moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
680         for (var i = 0; i < moves.length; ++i) {
681                 var line = refutation_lines[moves[i]];
682
683                 var tr = document.createElement("tr");
684
685                 var move_td = document.createElement("td");
686                 tr.appendChild(move_td);
687                 $(move_td).addClass("move");
688                 if (line['pv_pretty'].length == 0) {
689                         $(move_td).text(line['pretty_move']);
690                 } else {
691                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
692                         $(move_td).html(move);
693                 }
694
695                 var score_td = document.createElement("td");
696                 tr.appendChild(score_td);
697                 $(score_td).addClass("score");
698                 $(score_td).text(line['pretty_score']);
699
700                 var depth_td = document.createElement("td");
701                 tr.appendChild(depth_td);
702                 $(depth_td).addClass("depth");
703                 $(depth_td).text("d" + line['depth']);
704
705                 var pv_td = document.createElement("td");
706                 tr.appendChild(pv_td);
707                 $(pv_td).addClass("pv");
708                 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
709
710                 tbl.append(tr);
711         }
712
713         // Make one of the links clickable and the other nonclickable.
714         if (sort_refutation_lines_by_score) {
715                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
716                 $("#sortbyscore1").html("<strong>Score</strong>");
717         } else {
718                 $("#sortbyscore0").html("<strong>Move</strong>");
719                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
720         }
721 }
722
723 /**
724  * Create a Chess.js board object, containing the given position plus the given moves,
725  * up to the given limit.
726  *
727  * @param {?string} fen
728  * @param {Array.<string>} moves
729  * @param {number} last_move
730  */
731 var chess_from = function(fen, moves, last_move) {
732         var hiddenboard = new Chess();
733         if (fen !== null) {
734                 hiddenboard.load(fen);
735         }
736         for (var i = 0; i <= last_move; ++i) {
737                 if (moves[i] === '0-0') {
738                         hiddenboard.move('O-O');
739                 } else if (moves[i] === '0-0-0') {
740                         hiddenboard.move('O-O-O');
741                 } else {
742                         hiddenboard.move(moves[i]);
743                 }
744         }
745         return hiddenboard;
746 }
747
748 var update_game_list = function(games) {
749         $("#games").text("");
750         if (games === null) {
751                 return;
752         }
753
754         var games_div = document.getElementById('games');
755         for (var game_num = 0; game_num < games.length; ++game_num) {
756                 var game = games[game_num];
757                 var game_span = document.createElement("span");
758                 game_span.setAttribute("class", "game");
759
760                 var game_name = document.createTextNode(game['name']);
761                 if (game['url'] === backend_url) {
762                         game_span.appendChild(game_name);
763                 } else {
764                         var game_a = document.createElement("a");
765                         game_a.setAttribute("href", "#" + game['id']);
766                         game_a.appendChild(game_name);
767                         game_span.appendChild(game_a);
768                 }
769                 games_div.appendChild(game_span);
770         }
771 }
772
773 /**
774  * Try to find a running game that matches with the current hash,
775  * and switch to it if we're not already displaying it.
776  */
777 var possibly_switch_game_from_hash = function() {
778         if (current_games === null) {
779                 return;
780         }
781
782         var hash = window.location.hash.replace(/^#/,'');
783         for (var i = 0; i < current_games.length; ++i) {
784                 if (current_games[i]['id'] === hash) {
785                         if (backend_url !== current_games[i]['url']) {
786                                 switch_backend(current_games[i]['url']);
787                         }
788                         return;
789                 }
790         }
791 }
792
793 /**
794  * @param {Object} data
795  * @param {?Object} display_data
796  */
797 var update_board = function(current_data, display_data) {
798         var data = display_data || current_data;
799
800         display_lines = [];
801
802         // Print the history. This is pretty much the only thing that's
803         // unconditionally taken from current_data (we're not interested in
804         // historic history).
805         if (current_data['position']['pretty_history']) {
806                 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
807         } else {
808                 display_lines.push(null);
809         }
810         update_history();
811
812         // Games currently in progress, if any.
813         if (current_data['games']) {
814                 current_games = current_data['games'];
815                 possibly_switch_game_from_hash();
816                 update_game_list(current_data['games']);
817         } else {
818                 current_games = null;
819                 update_game_list(null);
820         }
821
822         // The headline. Names are always fetched from current_data;
823         // the rest can depend a bit.
824         var headline;
825         if (current_data &&
826             current_data['position']['player_w'] && current_data['position']['player_b']) {
827                 headline = current_data['position']['player_w'] + '–' +
828                         current_data['position']['player_b'] + ', analysis';
829         } else {
830                 headline = 'Analysis';
831         }
832
833         // Credits, where applicable. Note that we don't want the footer to change a lot
834         // when e.g. viewing history, so if any of these changed during the game,
835         // use the current one still.
836         if (current_data['using_lomonosov']) {
837                 $("#lomonosov").show();
838         } else {
839                 $("#lomonosov").hide();
840         }
841
842         // Credits: The engine name/version.
843         if (current_data['engine'] && current_data['engine']['name'] !== null) {
844                 $("#engineid").text(current_data['engine']['name']);
845         }
846
847         // Credits: The engine URL.
848         if (current_data['engine'] && current_data['engine']['url']) {
849                 $("#engineid").attr("href", current_data['engine']['url']);
850         } else {
851                 $("#engineid").removeAttr("href");
852         }
853
854         // Credits: Engine details.
855         if (current_data['engine'] && current_data['engine']['details']) {
856                 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
857         } else {
858                 $("#enginedetails").text("");
859         }
860
861         // Credits: Move source, possibly with URL.
862         if (current_data['move_source'] && current_data['move_source_url']) {
863                 $("#movesource").text("Moves provided by ");
864                 var movesource_a = document.createElement("a");
865                 movesource_a.setAttribute("href", current_data['move_source_url']);
866                 var movesource_text = document.createTextNode(current_data['move_source']);
867                 movesource_a.appendChild(movesource_text);
868                 var movesource_period = document.createTextNode(".");
869                 document.getElementById("movesource").appendChild(movesource_a);
870                 document.getElementById("movesource").appendChild(movesource_period);
871         } else if (current_data['move_source']) {
872                 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
873         } else {
874                 $("#movesource").text("");
875         }
876
877         var last_move;
878         if (display_data) {
879                 // Displaying some non-current position, pick out the last move
880                 // from the history. This will work even if the fetch failed.
881                 last_move = format_halfmove_with_number(
882                         current_display_line.pretty_pv[current_display_move],
883                         current_display_move + 1);
884                 headline += ' after ' + last_move;
885         } else if (data['position']['last_move'] !== 'none') {
886                 last_move = format_move_with_number(
887                         data['position']['last_move'],
888                         data['position']['move_num'],
889                         data['position']['toplay'] == 'W');
890                 headline += ' after ' + last_move;
891         } else {
892                 last_move = null;
893         }
894         $("#headline").text(headline);
895
896         // The <title> contains a very brief headline.
897         var title_elems = [];
898         if (data['short_score'] !== undefined && data['short_score'] !== null) {
899                 title_elems.push(data['short_score'].replace(/^ /, ""));
900         }
901         if (last_move !== null) {
902                 title_elems.push(last_move);
903         }
904
905         if (title_elems.length != 0) {
906                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
907         } else {
908                 document.title = 'analysis.sesse.net';
909         }
910
911         // The last move (shown by highlighting the from and to squares).
912         if (data['position'] && data['position']['last_move_uci']) {
913                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
914                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
915         } else if (current_display_line_is_history && current_display_move >= 0) {
916                 // We don't have historic analysis for this position, but we
917                 // can reconstruct what the last move was by just replaying
918                 // from the start.
919                 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
920                 var moves = hiddenboard.history({ verbose: true });
921                 var last_move = moves.pop();
922                 highlight_from = last_move.from;
923                 highlight_to = last_move.to;
924         } else {
925                 highlight_from = highlight_to = undefined;
926         }
927         update_highlight();
928
929         if (data['failed']) {
930                 $("#score").text("No analysis for this move");
931                 $("#pv").empty();
932                 $("#searchstats").html("&nbsp;");
933                 $("#refutationlines").empty();
934                 $("#whiteclock").empty();
935                 $("#blackclock").empty();
936                 refutation_lines = [];
937                 update_refutation_lines();
938                 clear_arrows();
939                 update_displayed_line();
940                 return;
941         }
942
943         update_clock();
944
945         // The score.
946         if (data['score'] !== null) {
947                 $("#score").text(data['score']);
948         }
949
950         // The search stats.
951         if (data['tablebase'] == 1) {
952                 $("#searchstats").text("Tablebase result");
953         } else if (data['nodes'] && data['nps'] && data['depth']) {
954                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
955                 if (data['seldepth']) {
956                         stats += ' (' + data['seldepth'] + ' selective)';
957                 }
958                 if (data['tbhits'] && data['tbhits'] > 0) {
959                         if (data['tbhits'] == 1) {
960                                 stats += ', one Syzygy hit';
961                         } else {
962                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
963                         }
964                 }
965
966                 $("#searchstats").text(stats);
967         } else {
968                 $("#searchstats").text("");
969         }
970
971         // Update the board itself.
972         fen = data['position']['fen'];
973         update_displayed_line();
974
975         // Print the PV.
976         $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
977
978         // Update the PV arrow.
979         clear_arrows();
980         if (data['pv_uci'].length >= 1) {
981                 // draw a continuation arrow as long as it's the same piece
982                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
983                         var from = data['pv_uci'][i].substr(0, 2);
984                         var to = data['pv_uci'][i].substr(2,4);
985                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
986                              interfering_arrow(from, to)) {
987                                 break;
988                         }
989                         create_arrow(from, to, '#f66', 6, 20);
990                 }
991
992                 var alt_moves = find_nonstupid_moves(data, 30);
993                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
994                         create_arrow(alt_moves[i].substr(0, 2),
995                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
996                 }
997         }
998
999         // See if all semi-reasonable moves have only one possible response.
1000         if (data['pv_uci'].length >= 2) {
1001                 var nonstupid_moves = find_nonstupid_moves(data, 300);
1002                 var response = data['pv_uci'][1];
1003                 for (var i = 0; i < nonstupid_moves.length; ++i) {
1004                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
1005                                 // ignore the PV move for refutation lines.
1006                                 continue;
1007                         }
1008                         if (!data['refutation_lines'] ||
1009                             !data['refutation_lines'][nonstupid_moves[i]] ||
1010                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1011                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1012                                 // Incomplete PV, abort.
1013                                 response = undefined;
1014                                 break;
1015                         }
1016                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1017                         if (response !== this_response) {
1018                                 // Different response depending on lines, abort.
1019                                 response = undefined;
1020                                 break;
1021                         }
1022                 }
1023
1024                 if (nonstupid_moves.length > 0 && response !== undefined) {
1025                         create_arrow(response.substr(0, 2),
1026                                      response.substr(2, 2), '#66f', 6, 20);
1027                 }
1028         }
1029
1030         // Update the refutation lines.
1031         fen = data['position']['fen'];
1032         move_num = data['position']['move_num'];
1033         toplay = data['position']['toplay'];
1034         refutation_lines = data['refutation_lines'];
1035         update_refutation_lines();
1036
1037         // Update the sparkline last, since its size depends on how everything else reflowed.
1038         update_sparkline(data);
1039 }
1040
1041 var update_sparkline = function(data) {
1042         if (data && data['score_history']) {
1043                 var first_move_num = undefined;
1044                 for (var halfmove_num in data['score_history']) {
1045                         halfmove_num = parseInt(halfmove_num);
1046                         if (first_move_num === undefined || halfmove_num < first_move_num) {
1047                                 first_move_num = halfmove_num;
1048                         }
1049                 }
1050                 if (first_move_num !== undefined) {
1051                         var last_move_num = data['position']['move_num'] * 2 - 3;
1052                         if (data['position']['toplay'] === 'B') {
1053                                 ++last_move_num;
1054                         }
1055
1056                         // Possibly truncate some moves if we don't have enough width.
1057                         // FIXME: Sometimes width() for #scorecontainer (and by extent,
1058                         // #scoresparkcontainer) on Chrome for mobile seems to start off
1059                         // at something very small, and then suddenly snap back into place.
1060                         // Figure out why.
1061                         var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1062                         if (last_move_num - first_move_num > max_moves) {
1063                                 first_move_num = last_move_num - max_moves;
1064                         }
1065
1066                         var min_score = -100;
1067                         var max_score = 100;
1068                         var last_score = null;
1069                         var scores = [];
1070                         for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1071                                 if (data['score_history'][halfmove_num]) {
1072                                         var score = data['score_history'][halfmove_num][0];
1073                                         if (score < min_score) min_score = score;
1074                                         if (score > max_score) max_score = score;
1075                                         last_score = data['score_history'][halfmove_num][0];
1076                                 }
1077                                 scores.push(last_score);
1078                         }
1079                         if (data['plot_score']) {
1080                                 scores.push(data['plot_score']);
1081                         }
1082                         // FIXME: at some widths, calling sparkline() seems to push
1083                         // #scorecontainer under the board.
1084                         $("#scorespark").sparkline(scores, {
1085                                 type: 'bar',
1086                                 zeroColor: 'gray',
1087                                 chartRangeMin: min_score,
1088                                 chartRangeMax: max_score,
1089                                 tooltipFormatter: function(sparkline, options, fields) {
1090                                         return format_tooltip(data, fields[0].offset + first_move_num);
1091                                 }
1092                         });
1093                 } else {
1094                         $("#scorespark").text("");
1095                 }
1096         } else {
1097                 $("#scorespark").text("");
1098         }
1099 }
1100
1101 /**
1102  * @param {number} num_viewers
1103  */
1104 var update_num_viewers = function(num_viewers) {
1105         if (num_viewers === null) {
1106                 $("#numviewers").text("");
1107         } else if (num_viewers == 1) {
1108                 $("#numviewers").text("You are the only current viewer");
1109         } else {
1110                 $("#numviewers").text(num_viewers + " current viewers");
1111         }
1112 }
1113
1114 var update_clock = function() {
1115         clearTimeout(clock_timer);
1116
1117         var data = displayed_analysis_data || current_analysis_data;
1118         if (data['position']) {
1119                 var result = data['position']['result'];
1120                 if (result === '1-0') {
1121                         $("#whiteclock").text("1");
1122                         $("#blackclock").text("0");
1123                         $("#whiteclock").removeClass("running-clock");
1124                         $("#blackclock").removeClass("running-clock");
1125                         return;
1126                 }
1127                 if (result === '1/2-1/2') {
1128                         $("#whiteclock").text("1/2");
1129                         $("#blackclock").text("1/2");
1130                         $("#whiteclock").removeClass("running-clock");
1131                         $("#blackclock").removeClass("running-clock");
1132                         return;
1133                 }       
1134                 if (result === '0-1') {
1135                         $("#whiteclock").text("0");
1136                         $("#blackclock").text("1");
1137                         $("#whiteclock").removeClass("running-clock");
1138                         $("#blackclock").removeClass("running-clock");
1139                         return;
1140                 }
1141         }
1142
1143         var white_clock_ms = null;
1144         var black_clock_ms = null;
1145         var show_seconds = false;
1146
1147         // Static clocks.
1148         if (data['position'] &&
1149             data['position']['white_clock'] &&
1150             data['position']['black_clock']) {
1151                 white_clock_ms = data['position']['white_clock'] * 1000;
1152                 black_clock_ms = data['position']['black_clock'] * 1000;
1153         }
1154
1155         // Dynamic clock (only one, obviously).
1156         var color;
1157         if (data['position']['white_clock_target']) {
1158                 color = "white";
1159                 $("#whiteclock").addClass("running-clock");
1160                 $("#blackclock").removeClass("running-clock");
1161         } else if (data['position']['black_clock_target']) {
1162                 color = "black";
1163                 $("#whiteclock").removeClass("running-clock");
1164                 $("#blackclock").addClass("running-clock");
1165         } else {
1166                 $("#whiteclock").removeClass("running-clock");
1167                 $("#blackclock").removeClass("running-clock");
1168         }
1169         var remaining_ms;
1170         if (color) {
1171                 var now = new Date().getTime() + client_clock_offset_ms;
1172                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1173                 if (color === "white") {
1174                         white_clock_ms = remaining_ms;
1175                 } else {
1176                         black_clock_ms = remaining_ms;
1177                 }
1178         }
1179
1180         if (white_clock_ms === null || black_clock_ms === null) {
1181                 $("#whiteclock").empty();
1182                 $("#blackclock").empty();
1183                 return;
1184         }
1185
1186         // If either player has ten minutes or less left, add the second counters.
1187         var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1188
1189         if (color) {
1190                 // See when the clock will change next, and update right after that.
1191                 var next_update_ms;
1192                 if (show_seconds) {
1193                         next_update_ms = remaining_ms % 1000 + 100;
1194                 } else {
1195                         next_update_ms = remaining_ms % 60000 + 100;
1196                 }
1197                 clock_timer = setTimeout(update_clock, next_update_ms);
1198         }
1199
1200         $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1201         $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1202 }
1203
1204 /**
1205  * @param {Number} remaining_ms
1206  * @param {boolean} show_seconds
1207  */
1208 var format_clock = function(remaining_ms, show_seconds) {
1209         if (remaining_ms <= 0) {
1210                 if (show_seconds) {
1211                         return "00:00:00";
1212                 } else {
1213                         return "00:00";
1214                 }
1215         }
1216
1217         var remaining = Math.floor(remaining_ms / 1000);
1218         var seconds = remaining % 60;
1219         remaining = (remaining - seconds) / 60;
1220         var minutes = remaining % 60;
1221         remaining = (remaining - minutes) / 60;
1222         var hours = remaining;
1223         if (show_seconds) {
1224                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1225         } else {
1226                 return format_2d(hours) + ":" + format_2d(minutes);
1227         }
1228 }
1229
1230 /**
1231  * @param {Number} x
1232  */
1233 var format_2d = function(x) {
1234         if (x >= 10) {
1235                 return x;
1236         } else {
1237                 return "0" + x;
1238         }
1239 }
1240
1241 /**
1242  * @param {string} move
1243  * @param {Number} move_num
1244  * @param {boolean} white_to_play
1245  */
1246 var format_move_with_number = function(move, move_num, white_to_play) {
1247         var ret;
1248         if (white_to_play) {
1249                 ret = (move_num - 1) + '… ';
1250         } else {
1251                 ret = move_num + '. ';
1252         }
1253         ret += move;
1254         return ret;
1255 }
1256
1257 /**
1258  * @param {string} move
1259  * @param {Number} halfmove_num
1260  */
1261 var format_halfmove_with_number = function(move, halfmove_num) {
1262         return format_move_with_number(
1263                 move,
1264                 Math.floor(halfmove_num / 2) + 1,
1265                 halfmove_num % 2 == 0);
1266 }
1267
1268 /**
1269  * @param {Object} data
1270  * @param {Number} halfmove_num
1271  */
1272 var format_tooltip = function(data, halfmove_num) {
1273         if (data['score_history'][halfmove_num] ||
1274             halfmove_num === data['position']['pretty_history'].length) {
1275                 var move;
1276                 var short_score;
1277                 if (halfmove_num === data['position']['pretty_history'].length) {
1278                         move = data['position']['last_move'];
1279                         short_score = data['short_score'];
1280                 } else {
1281                         move = data['position']['pretty_history'][halfmove_num];
1282                         short_score = data['score_history'][halfmove_num][1];
1283                 }
1284                 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1285
1286                 return "After " + move_with_number + ": " + short_score;
1287         } else {
1288                 for (var i = halfmove_num; i --> 0; ) {
1289                         if (data['score_history'][i]) {
1290                                 var move = data['position']['pretty_history'][i];
1291                                 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1292                         }
1293                 }
1294         }
1295 }
1296
1297 /**
1298  * @param {boolean} sort_by_score
1299  */
1300 var resort_refutation_lines = function(sort_by_score) {
1301         sort_refutation_lines_by_score = sort_by_score;
1302         if (supports_html5_storage()) {
1303                 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1304         }
1305         update_refutation_lines();
1306 }
1307 window['resort_refutation_lines'] = resort_refutation_lines;
1308
1309 /**
1310  * @param {boolean} truncate_history
1311  */
1312 var set_truncate_history = function(truncate_history) {
1313         truncate_display_history = truncate_history;
1314         update_refutation_lines();
1315 }
1316 window['set_truncate_history'] = set_truncate_history;
1317
1318 /**
1319  * @param {number} line_num
1320  * @param {number} move_num
1321  */
1322 var show_line = function(line_num, move_num) {
1323         if (line_num == -1) {
1324                 current_display_line = null;
1325                 current_display_move = null;
1326                 if (displayed_analysis_data) {
1327                         // TODO: Support exiting to history position if we are in an
1328                         // analysis line of a history position.
1329                         displayed_analysis_data = null;
1330                         update_board(current_analysis_data, displayed_analysis_data);
1331                 }
1332         } else {
1333                 current_display_line = display_lines[line_num];
1334                 current_display_move = move_num;
1335         }
1336         current_display_line_is_history = (line_num == 0);
1337
1338         update_historic_analysis();
1339         update_displayed_line();
1340         update_highlight();
1341         redraw_arrows();
1342 }
1343 window['show_line'] = show_line;
1344
1345 var prev_move = function() {
1346         if (current_display_move > -1) {
1347                 --current_display_move;
1348         }
1349         update_historic_analysis();
1350         update_displayed_line();
1351 }
1352 window['prev_move'] = prev_move;
1353
1354 var next_move = function() {
1355         if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1356                 ++current_display_move;
1357         }
1358         update_historic_analysis();
1359         update_displayed_line();
1360 }
1361 window['next_move'] = next_move;
1362
1363 var update_historic_analysis = function() {
1364         if (!current_display_line_is_history) {
1365                 return;
1366         }
1367         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1368                 displayed_analysis_data = null;
1369                 update_board(current_analysis_data, displayed_analysis_data);
1370         }
1371
1372         // Fetch old analysis for this line if it exists.
1373         var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1374         var filename = "/history/move" + (current_display_move + 1) + "-" +
1375                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1376
1377         current_historic_xhr = $.ajax({
1378                 url: filename
1379         }).done(function(data, textstatus, xhr) {
1380                 displayed_analysis_data = data;
1381                 update_board(current_analysis_data, displayed_analysis_data);
1382         }).fail(function(jqXHR, textStatus, errorThrown) {
1383                 if (textStatus === "abort") {
1384                         // Aborted because we are switching backends. Don't do anything;
1385                         // we will already have been cleared.
1386                 } else {
1387                         displayed_analysis_data = {'failed': true};
1388                         update_board(current_analysis_data, displayed_analysis_data);
1389                 }
1390         });
1391 }
1392
1393 /**
1394  * @param {string} fen
1395  */
1396 var update_imbalance = function(fen) {
1397         var hiddenboard = new Chess(fen);
1398         var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1399         for (var row = 0; row < 8; ++row) {
1400                 for (var col = 0; col < 8; ++col) {
1401                         var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1402                         var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1403                         var square = col_text + row_text;
1404                         var contents = hiddenboard.get(square);
1405                         if (contents !== null) {
1406                                 if (contents.color === 'w') {
1407                                         ++imbalance[contents.type];
1408                                 } else {
1409                                         --imbalance[contents.type];
1410                                 }
1411                         }
1412                 }
1413         }
1414         var white_imbalance = '';
1415         var black_imbalance = '';
1416         for (var piece in imbalance) {
1417                 for (var i = 0; i < imbalance[piece]; ++i) {
1418                         white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1419                 }
1420                 for (var i = 0; i < -imbalance[piece]; ++i) {
1421                         black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1422                 }
1423         }
1424         $('#whiteimbalance').html(white_imbalance);
1425         $('#blackimbalance').html(black_imbalance);
1426 }
1427
1428 var update_displayed_line = function() {
1429         if (highlighted_move !== null) {
1430                 highlighted_move.removeClass('highlight'); 
1431         }
1432         if (current_display_line === null) {
1433                 $("#linenav").hide();
1434                 $("#linemsg").show();
1435                 board.position(fen);
1436                 update_imbalance(fen);
1437                 return;
1438         }
1439
1440         $("#linenav").show();
1441         $("#linemsg").hide();
1442
1443         if (current_display_move <= 0) {
1444                 $("#prevmove").html("Previous");
1445         } else {
1446                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1447         }
1448         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1449                 $("#nextmove").html("Next");
1450         } else {
1451                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1452         }
1453
1454         highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1455         highlighted_move.addClass('highlight'); 
1456
1457         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1458         board.position(hiddenboard.fen());
1459         update_imbalance(hiddenboard.fen());
1460 }
1461
1462 /**
1463  * @param {boolean} param_enable_sound
1464  */
1465 var set_sound = function(param_enable_sound) {
1466         enable_sound = param_enable_sound;
1467         if (enable_sound) {
1468                 $("#soundon").html("<strong>On</strong>");
1469                 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1470
1471                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1472                 // and also preload the file since the user has selected audio.
1473                 var ding = document.getElementById('ding');
1474                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1475                         ding.src = 'ding.opus';
1476                         ding.load();
1477                 }
1478         } else {
1479                 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1480                 $("#soundoff").html("<strong>Off</strong>");
1481         }
1482         if (supports_html5_storage()) {
1483                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1484         }
1485 }
1486 window['set_sound'] = set_sound;
1487
1488 /**
1489  * @param {string} new_backend_url
1490  */
1491 var switch_backend = function(new_backend_url) {
1492         // Stop looking at historic data.
1493         current_display_line = null;
1494         current_display_move = null;
1495         displayed_analysis_data = null;
1496         if (current_historic_xhr) {
1497                 current_historic_xhr.abort();
1498         }
1499
1500         // If we already have a backend response going, abort it.
1501         if (current_analysis_xhr) {
1502                 current_analysis_xhr.abort();
1503         }
1504
1505         // Otherwise, we should have a timer going to start a new one.
1506         // Kill that, too.
1507         if (current_analysis_request_timer) {
1508                 clearTimeout(current_analysis_request_timer);
1509                 current_analysis_request_timer = null;
1510         }
1511
1512         // Request an immediate fetch with the new backend.
1513         backend_url = new_backend_url;
1514         current_analysis_data = null;
1515         ims = 0;
1516         request_update();
1517 }
1518 window['switch_backend'] = switch_backend;
1519
1520 var init = function() {
1521         unique = get_unique();
1522
1523         // Load settings from HTML5 local storage if available.
1524         if (supports_html5_storage() && localStorage['enable_sound']) {
1525                 set_sound(parseInt(localStorage['enable_sound']));
1526         } else {
1527                 set_sound(false);
1528         }
1529         if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1530                 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1531         } else {
1532                 sort_refutation_lines_by_score = true;
1533         }
1534
1535         // Create board.
1536         board = new window.ChessBoard('board', 'start');
1537
1538         request_update();
1539         $(window).resize(function() {
1540                 board.resize();
1541                 update_sparkline(displayed_analysis_data || current_analysis_data);
1542                 update_highlight();
1543                 redraw_arrows();
1544         });
1545         $(window).keyup(function(event) {
1546                 if (event.which == 39) {
1547                         next_move();
1548                 } else if (event.which == 37) {
1549                         prev_move();
1550                 }
1551         });
1552         window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
1553 };
1554 $(document).ready(init);
1555
1556 })();