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