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