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