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