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