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