]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
33ae193cbe42ccc51696060d666e6c5da8b8dd9a
[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                 update_move_highlight();
946                 return;
947         }
948
949         update_clock();
950
951         // The score.
952         if (data['score'] !== null) {
953                 $("#score").text(data['score']);
954         }
955
956         // The search stats.
957         if (data['tablebase'] == 1) {
958                 $("#searchstats").text("Tablebase result");
959         } else if (data['nodes'] && data['nps'] && data['depth']) {
960                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
961                 if (data['seldepth']) {
962                         stats += ' (' + data['seldepth'] + ' selective)';
963                 }
964                 if (data['tbhits'] && data['tbhits'] > 0) {
965                         if (data['tbhits'] == 1) {
966                                 stats += ', one Syzygy hit';
967                         } else {
968                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
969                         }
970                 }
971
972                 $("#searchstats").text(stats);
973         } else {
974                 $("#searchstats").text("");
975         }
976
977         // Update the board itself.
978         fen = data['position']['fen'];
979         update_displayed_line();
980         update_move_highlight();
981
982         // Print the PV.
983         $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
984
985         // Update the PV arrow.
986         clear_arrows();
987         if (data['pv_uci'].length >= 1) {
988                 // draw a continuation arrow as long as it's the same piece
989                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
990                         var from = data['pv_uci'][i].substr(0, 2);
991                         var to = data['pv_uci'][i].substr(2,4);
992                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
993                              interfering_arrow(from, to)) {
994                                 break;
995                         }
996                         create_arrow(from, to, '#f66', 6, 20);
997                 }
998
999                 var alt_moves = find_nonstupid_moves(data, 30);
1000                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1001                         create_arrow(alt_moves[i].substr(0, 2),
1002                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
1003                 }
1004         }
1005
1006         // See if all semi-reasonable moves have only one possible response.
1007         if (data['pv_uci'].length >= 2) {
1008                 var nonstupid_moves = find_nonstupid_moves(data, 300);
1009                 var response = data['pv_uci'][1];
1010                 for (var i = 0; i < nonstupid_moves.length; ++i) {
1011                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
1012                                 // ignore the PV move for refutation lines.
1013                                 continue;
1014                         }
1015                         if (!data['refutation_lines'] ||
1016                             !data['refutation_lines'][nonstupid_moves[i]] ||
1017                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1018                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1019                                 // Incomplete PV, abort.
1020                                 response = undefined;
1021                                 break;
1022                         }
1023                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1024                         if (response !== this_response) {
1025                                 // Different response depending on lines, abort.
1026                                 response = undefined;
1027                                 break;
1028                         }
1029                 }
1030
1031                 if (nonstupid_moves.length > 0 && response !== undefined) {
1032                         create_arrow(response.substr(0, 2),
1033                                      response.substr(2, 2), '#66f', 6, 20);
1034                 }
1035         }
1036
1037         // Update the refutation lines.
1038         fen = data['position']['fen'];
1039         move_num = data['position']['move_num'];
1040         toplay = data['position']['toplay'];
1041         refutation_lines = data['refutation_lines'];
1042         update_refutation_lines();
1043
1044         // Update the sparkline last, since its size depends on how everything else reflowed.
1045         update_sparkline(data);
1046 }
1047
1048 var update_sparkline = function(data) {
1049         if (data && data['score_history']) {
1050                 var first_move_num = undefined;
1051                 for (var halfmove_num in data['score_history']) {
1052                         halfmove_num = parseInt(halfmove_num);
1053                         if (first_move_num === undefined || halfmove_num < first_move_num) {
1054                                 first_move_num = halfmove_num;
1055                         }
1056                 }
1057                 if (first_move_num !== undefined) {
1058                         var last_move_num = data['position']['move_num'] * 2 - 3;
1059                         if (data['position']['toplay'] === 'B') {
1060                                 ++last_move_num;
1061                         }
1062
1063                         // Possibly truncate some moves if we don't have enough width.
1064                         // FIXME: Sometimes width() for #scorecontainer (and by extent,
1065                         // #scoresparkcontainer) on Chrome for mobile seems to start off
1066                         // at something very small, and then suddenly snap back into place.
1067                         // Figure out why.
1068                         var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1069                         if (last_move_num - first_move_num > max_moves) {
1070                                 first_move_num = last_move_num - max_moves;
1071                         }
1072
1073                         var min_score = -100;
1074                         var max_score = 100;
1075                         var last_score = null;
1076                         var scores = [];
1077                         for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1078                                 if (data['score_history'][halfmove_num]) {
1079                                         var score = data['score_history'][halfmove_num][0];
1080                                         if (score < min_score) min_score = score;
1081                                         if (score > max_score) max_score = score;
1082                                         last_score = data['score_history'][halfmove_num][0];
1083                                 }
1084                                 scores.push(last_score);
1085                         }
1086                         if (data['plot_score']) {
1087                                 scores.push(data['plot_score']);
1088                         }
1089                         // FIXME: at some widths, calling sparkline() seems to push
1090                         // #scorecontainer under the board.
1091                         $("#scorespark").sparkline(scores, {
1092                                 type: 'bar',
1093                                 zeroColor: 'gray',
1094                                 chartRangeMin: min_score,
1095                                 chartRangeMax: max_score,
1096                                 tooltipFormatter: function(sparkline, options, fields) {
1097                                         return format_tooltip(data, fields[0].offset + first_move_num);
1098                                 }
1099                         });
1100                 } else {
1101                         $("#scorespark").text("");
1102                 }
1103         } else {
1104                 $("#scorespark").text("");
1105         }
1106 }
1107
1108 /**
1109  * @param {number} num_viewers
1110  */
1111 var update_num_viewers = function(num_viewers) {
1112         if (num_viewers === null) {
1113                 $("#numviewers").text("");
1114         } else if (num_viewers == 1) {
1115                 $("#numviewers").text("You are the only current viewer");
1116         } else {
1117                 $("#numviewers").text(num_viewers + " current viewers");
1118         }
1119 }
1120
1121 var update_clock = function() {
1122         clearTimeout(clock_timer);
1123
1124         var data = displayed_analysis_data || current_analysis_data;
1125         if (data['position']) {
1126                 var result = data['position']['result'];
1127                 if (result === '1-0') {
1128                         $("#whiteclock").text("1");
1129                         $("#blackclock").text("0");
1130                         $("#whiteclock").removeClass("running-clock");
1131                         $("#blackclock").removeClass("running-clock");
1132                         return;
1133                 }
1134                 if (result === '1/2-1/2') {
1135                         $("#whiteclock").text("1/2");
1136                         $("#blackclock").text("1/2");
1137                         $("#whiteclock").removeClass("running-clock");
1138                         $("#blackclock").removeClass("running-clock");
1139                         return;
1140                 }       
1141                 if (result === '0-1') {
1142                         $("#whiteclock").text("0");
1143                         $("#blackclock").text("1");
1144                         $("#whiteclock").removeClass("running-clock");
1145                         $("#blackclock").removeClass("running-clock");
1146                         return;
1147                 }
1148         }
1149
1150         var white_clock_ms = null;
1151         var black_clock_ms = null;
1152         var show_seconds = false;
1153
1154         // Static clocks.
1155         if (data['position'] &&
1156             data['position']['white_clock'] &&
1157             data['position']['black_clock']) {
1158                 white_clock_ms = data['position']['white_clock'] * 1000;
1159                 black_clock_ms = data['position']['black_clock'] * 1000;
1160         }
1161
1162         // Dynamic clock (only one, obviously).
1163         var color;
1164         if (data['position']['white_clock_target']) {
1165                 color = "white";
1166                 $("#whiteclock").addClass("running-clock");
1167                 $("#blackclock").removeClass("running-clock");
1168         } else if (data['position']['black_clock_target']) {
1169                 color = "black";
1170                 $("#whiteclock").removeClass("running-clock");
1171                 $("#blackclock").addClass("running-clock");
1172         } else {
1173                 $("#whiteclock").removeClass("running-clock");
1174                 $("#blackclock").removeClass("running-clock");
1175         }
1176         var remaining_ms;
1177         if (color) {
1178                 var now = new Date().getTime() + client_clock_offset_ms;
1179                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1180                 if (color === "white") {
1181                         white_clock_ms = remaining_ms;
1182                 } else {
1183                         black_clock_ms = remaining_ms;
1184                 }
1185         }
1186
1187         if (white_clock_ms === null || black_clock_ms === null) {
1188                 $("#whiteclock").empty();
1189                 $("#blackclock").empty();
1190                 return;
1191         }
1192
1193         // If either player has ten minutes or less left, add the second counters.
1194         var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1195
1196         if (color) {
1197                 // See when the clock will change next, and update right after that.
1198                 var next_update_ms;
1199                 if (show_seconds) {
1200                         next_update_ms = remaining_ms % 1000 + 100;
1201                 } else {
1202                         next_update_ms = remaining_ms % 60000 + 100;
1203                 }
1204                 clock_timer = setTimeout(update_clock, next_update_ms);
1205         }
1206
1207         $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1208         $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1209 }
1210
1211 /**
1212  * @param {Number} remaining_ms
1213  * @param {boolean} show_seconds
1214  */
1215 var format_clock = function(remaining_ms, show_seconds) {
1216         if (remaining_ms <= 0) {
1217                 if (show_seconds) {
1218                         return "00:00:00";
1219                 } else {
1220                         return "00:00";
1221                 }
1222         }
1223
1224         var remaining = Math.floor(remaining_ms / 1000);
1225         var seconds = remaining % 60;
1226         remaining = (remaining - seconds) / 60;
1227         var minutes = remaining % 60;
1228         remaining = (remaining - minutes) / 60;
1229         var hours = remaining;
1230         if (show_seconds) {
1231                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1232         } else {
1233                 return format_2d(hours) + ":" + format_2d(minutes);
1234         }
1235 }
1236
1237 /**
1238  * @param {Number} x
1239  */
1240 var format_2d = function(x) {
1241         if (x >= 10) {
1242                 return x;
1243         } else {
1244                 return "0" + x;
1245         }
1246 }
1247
1248 /**
1249  * @param {string} move
1250  * @param {Number} move_num
1251  * @param {boolean} white_to_play
1252  */
1253 var format_move_with_number = function(move, move_num, white_to_play) {
1254         var ret;
1255         if (white_to_play) {
1256                 ret = (move_num - 1) + '… ';
1257         } else {
1258                 ret = move_num + '. ';
1259         }
1260         ret += move;
1261         return ret;
1262 }
1263
1264 /**
1265  * @param {string} move
1266  * @param {Number} halfmove_num
1267  */
1268 var format_halfmove_with_number = function(move, halfmove_num) {
1269         return format_move_with_number(
1270                 move,
1271                 Math.floor(halfmove_num / 2) + 1,
1272                 halfmove_num % 2 == 0);
1273 }
1274
1275 /**
1276  * @param {Object} data
1277  * @param {Number} halfmove_num
1278  */
1279 var format_tooltip = function(data, halfmove_num) {
1280         if (data['score_history'][halfmove_num] ||
1281             halfmove_num === data['position']['pretty_history'].length) {
1282                 var move;
1283                 var short_score;
1284                 if (halfmove_num === data['position']['pretty_history'].length) {
1285                         move = data['position']['last_move'];
1286                         short_score = data['short_score'];
1287                 } else {
1288                         move = data['position']['pretty_history'][halfmove_num];
1289                         short_score = data['score_history'][halfmove_num][1];
1290                 }
1291                 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1292
1293                 return "After " + move_with_number + ": " + short_score;
1294         } else {
1295                 for (var i = halfmove_num; i --> 0; ) {
1296                         if (data['score_history'][i]) {
1297                                 var move = data['position']['pretty_history'][i];
1298                                 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1299                         }
1300                 }
1301         }
1302 }
1303
1304 /**
1305  * @param {boolean} sort_by_score
1306  */
1307 var resort_refutation_lines = function(sort_by_score) {
1308         sort_refutation_lines_by_score = sort_by_score;
1309         if (supports_html5_storage()) {
1310                 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1311         }
1312         update_refutation_lines();
1313 }
1314 window['resort_refutation_lines'] = resort_refutation_lines;
1315
1316 /**
1317  * @param {boolean} truncate_history
1318  */
1319 var set_truncate_history = function(truncate_history) {
1320         truncate_display_history = truncate_history;
1321         update_refutation_lines();
1322 }
1323 window['set_truncate_history'] = set_truncate_history;
1324
1325 /**
1326  * @param {number} line_num
1327  * @param {number} move_num
1328  */
1329 var show_line = function(line_num, move_num) {
1330         if (line_num == -1) {
1331                 current_display_line = null;
1332                 current_display_move = null;
1333                 if (displayed_analysis_data) {
1334                         // TODO: Support exiting to history position if we are in an
1335                         // analysis line of a history position.
1336                         displayed_analysis_data = null;
1337                         update_board(current_analysis_data, displayed_analysis_data);
1338                 }
1339         } else {
1340                 current_display_line = display_lines[line_num];
1341                 current_display_move = move_num;
1342         }
1343         current_display_line_is_history = (line_num == 0);
1344
1345         update_historic_analysis();
1346         update_displayed_line();
1347         update_board_highlight();
1348         redraw_arrows();
1349 }
1350 window['show_line'] = show_line;
1351
1352 var prev_move = function() {
1353         if (current_display_move > -1) {
1354                 --current_display_move;
1355         }
1356         update_historic_analysis();
1357         update_displayed_line();
1358         update_move_highlight();
1359 }
1360 window['prev_move'] = prev_move;
1361
1362 var next_move = function() {
1363         if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1364                 ++current_display_move;
1365         }
1366         update_historic_analysis();
1367         update_displayed_line();
1368         update_move_highlight();
1369 }
1370 window['next_move'] = next_move;
1371
1372 var update_historic_analysis = function() {
1373         if (!current_display_line_is_history) {
1374                 return;
1375         }
1376         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1377                 displayed_analysis_data = null;
1378                 update_board(current_analysis_data, displayed_analysis_data);
1379         }
1380
1381         // Fetch old analysis for this line if it exists.
1382         var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1383         var filename = "/history/move" + (current_display_move + 1) + "-" +
1384                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1385
1386         current_historic_xhr = $.ajax({
1387                 url: filename
1388         }).done(function(data, textstatus, xhr) {
1389                 displayed_analysis_data = data;
1390                 update_board(current_analysis_data, displayed_analysis_data);
1391         }).fail(function(jqXHR, textStatus, errorThrown) {
1392                 if (textStatus === "abort") {
1393                         // Aborted because we are switching backends. Don't do anything;
1394                         // we will already have been cleared.
1395                 } else {
1396                         displayed_analysis_data = {'failed': true};
1397                         update_board(current_analysis_data, displayed_analysis_data);
1398                 }
1399         });
1400 }
1401
1402 /**
1403  * @param {string} fen
1404  */
1405 var update_imbalance = function(fen) {
1406         var hiddenboard = new Chess(fen);
1407         var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1408         for (var row = 0; row < 8; ++row) {
1409                 for (var col = 0; col < 8; ++col) {
1410                         var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1411                         var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1412                         var square = col_text + row_text;
1413                         var contents = hiddenboard.get(square);
1414                         if (contents !== null) {
1415                                 if (contents.color === 'w') {
1416                                         ++imbalance[contents.type];
1417                                 } else {
1418                                         --imbalance[contents.type];
1419                                 }
1420                         }
1421                 }
1422         }
1423         var white_imbalance = '';
1424         var black_imbalance = '';
1425         for (var piece in imbalance) {
1426                 for (var i = 0; i < imbalance[piece]; ++i) {
1427                         white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1428                 }
1429                 for (var i = 0; i < -imbalance[piece]; ++i) {
1430                         black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1431                 }
1432         }
1433         $('#whiteimbalance').html(white_imbalance);
1434         $('#blackimbalance').html(black_imbalance);
1435 }
1436
1437 /** Mark the currently selected move in red.
1438  */
1439 var update_move_highlight = function() {
1440         if (highlighted_move !== null) {
1441                 highlighted_move.removeClass('highlight'); 
1442         }
1443         if (current_display_line !== null) {
1444                 highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1445                 highlighted_move.addClass('highlight'); 
1446         }
1447 }
1448
1449 var update_displayed_line = function() {
1450         if (current_display_line === null) {
1451                 $("#linenav").hide();
1452                 $("#linemsg").show();
1453                 board.position(fen);
1454                 update_imbalance(fen);
1455                 return;
1456         }
1457
1458         $("#linenav").show();
1459         $("#linemsg").hide();
1460
1461         if (current_display_move <= 0) {
1462                 $("#prevmove").html("Previous");
1463         } else {
1464                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1465         }
1466         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1467                 $("#nextmove").html("Next");
1468         } else {
1469                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1470         }
1471
1472         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1473         board.position(hiddenboard.fen());
1474         update_imbalance(hiddenboard.fen());
1475 }
1476
1477 /**
1478  * @param {boolean} param_enable_sound
1479  */
1480 var set_sound = function(param_enable_sound) {
1481         enable_sound = param_enable_sound;
1482         if (enable_sound) {
1483                 $("#soundon").html("<strong>On</strong>");
1484                 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1485
1486                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1487                 // and also preload the file since the user has selected audio.
1488                 var ding = document.getElementById('ding');
1489                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1490                         ding.src = 'ding.opus';
1491                         ding.load();
1492                 }
1493         } else {
1494                 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1495                 $("#soundoff").html("<strong>Off</strong>");
1496         }
1497         if (supports_html5_storage()) {
1498                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1499         }
1500 }
1501 window['set_sound'] = set_sound;
1502
1503 /**
1504  * @param {string} new_backend_url
1505  */
1506 var switch_backend = function(new_backend_url) {
1507         // Stop looking at historic data.
1508         current_display_line = null;
1509         current_display_move = null;
1510         displayed_analysis_data = null;
1511         if (current_historic_xhr) {
1512                 current_historic_xhr.abort();
1513         }
1514
1515         // If we already have a backend response going, abort it.
1516         if (current_analysis_xhr) {
1517                 current_analysis_xhr.abort();
1518         }
1519
1520         // Otherwise, we should have a timer going to start a new one.
1521         // Kill that, too.
1522         if (current_analysis_request_timer) {
1523                 clearTimeout(current_analysis_request_timer);
1524                 current_analysis_request_timer = null;
1525         }
1526
1527         // Request an immediate fetch with the new backend.
1528         backend_url = new_backend_url;
1529         current_analysis_data = null;
1530         ims = 0;
1531         request_update();
1532 }
1533 window['switch_backend'] = switch_backend;
1534
1535 var init = function() {
1536         unique = get_unique();
1537
1538         // Load settings from HTML5 local storage if available.
1539         if (supports_html5_storage() && localStorage['enable_sound']) {
1540                 set_sound(parseInt(localStorage['enable_sound']));
1541         } else {
1542                 set_sound(false);
1543         }
1544         if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1545                 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1546         } else {
1547                 sort_refutation_lines_by_score = true;
1548         }
1549
1550         // Create board.
1551         board = new window.ChessBoard('board', 'start');
1552
1553         request_update();
1554         $(window).resize(function() {
1555                 board.resize();
1556                 update_sparkline(displayed_analysis_data || current_analysis_data);
1557                 update_board_highlight();
1558                 redraw_arrows();
1559         });
1560         $(window).keyup(function(event) {
1561                 if (event.which == 39) {
1562                         next_move();
1563                 } else if (event.which == 37) {
1564                         prev_move();
1565                 }
1566         });
1567         window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
1568 };
1569 $(document).ready(init);
1570
1571 })();