4ff9d6429756fb325dd93c194392b6dc6bf46f99
[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 = 2016113007;
11
12 /**
13  * The current backend URL.
14  *
15  * @type {!string}
16  * @private
17  */
18 var backend_url = "/analysis.pl";
19 var backend_hash_url = "/hash";
20
21 /** @type {window.ChessBoard} @private */
22 var board = null;
23
24 /** @type {boolean} @private */
25 var board_is_animating = false;
26
27 /**
28  * The most recent analysis data we have from the server
29  * (about the most recent position).
30  *
31  * @type {?Object}
32  * @private */
33 var current_analysis_data = null;
34
35 /**
36  * If we are displaying previous analysis or from hash, this is non-null,
37  * and will override most of current_analysis_data.
38  *
39  * @type {?Object}
40  * @private
41  */
42 var displayed_analysis_data = null;
43
44 /**
45  * Games currently in progress, if any.
46  *
47  * @type {?Array.<{
48  *      name: string,
49  *      url: string,
50  *      hashurl: string,
51  *      id: string,
52  *      score: Object=,
53  *      result: string=,
54  * }>}
55  * @private
56  */
57 var current_games = null;
58
59 /** @type {Array.<{
60  *      from_col: number,
61  *      from_row: number,
62  *      to_col: number,
63  *      to_row: number,
64  *      line_width: number,
65  *      arrow_size: number,
66  *      fg_color: string
67  * }>}
68  * @private
69  */
70 var arrows = [];
71
72 /** @type {Array.<Array.<boolean>>} */
73 var occupied_by_arrows = [];
74
75 /** Currently displayed refutation lines (on-screen).
76  * Can either come from the current_analysis_data, displayed_analysis_data,
77  * or hash_refutation_lines.
78  */
79 var refutation_lines = [];
80
81 /** Refutation lines from current hash probe.
82  *
83  * If non-null, will override refutation lines from the base position.
84  * Note that these are relative to display_fen, not base_fen.
85  */
86 var hash_refutation_lines = null;
87
88 /** @type {!number} @private */
89 var move_num = 1;
90
91 /** @type {!string} @private */
92 var toplay = 'W';
93
94 /** @type {number} @private */
95 var ims = 0;
96
97 /** @type {boolean} @private */
98 var truncate_display_history = true;
99
100 /** @type {!string|undefined} @private */
101 var highlight_from = undefined;
102
103 /** @type {!string|undefined} @private */
104 var highlight_to = undefined;
105
106 /** The HTML object of the move currently being highlighted (in red).
107  * @type {?jQuery}
108  * @private */
109 var highlighted_move = null;
110
111 /** Currently suggested/recommended move when dragging.
112  * @type {?{from: !string, to: !string}}
113  * @private
114  */
115 var recommended_move = null;
116
117 /** If reverse-dragging (dragging from the destination square to the
118  * source square), the destination square.
119  * @type {?string}
120  * @private
121  */
122 var reverse_dragging_from = null;
123
124 /** @type {?number} @private */
125 var unique = null;
126
127 /** @type {boolean} @private */
128 var enable_sound = false;
129
130 /**
131  * Our best estimate of how many milliseconds we need to add to 
132  * new Date() to get the true UTC time. Calibrated against the
133  * server clock.
134  *
135  * @type {?number}
136  * @private
137  */
138 var client_clock_offset_ms = null;
139
140 var clock_timer = null;
141
142 /** The current position being analyzed, represented as a FEN string.
143  * Note that this is not necessarily the same as display_fen.
144  * @type {?string}
145  * @private
146  */
147 var base_fen = null;
148
149 /** The current position on the board, represented as a FEN string.
150  * Note that board.fen() does not contain e.g. who is to play.
151  * @type {?string}
152  * @private
153  */
154 var display_fen = null;
155
156 /** @typedef {{
157  *    start_fen: string,
158  *    pv: Array.<string>,
159  *    move_num: number,
160  *    toplay: string,
161  *    scores: Array<{first_move: number, score: Object}>,
162  *    start_display_move_num: number
163  * }} DisplayLine
164  *
165  * "start_display_move_num" is the (half-)move number to start displaying the PV at.
166  * "score" is also evaluated at this point.
167  */
168
169 /** All PVs that we currently know of.
170  *
171  * Element 0 is history (or null if no history).
172  * Element 1 is current main PV, or explored line if nowhere else on the screen.
173  * All remaining elements are refutation lines (multi-PV).
174  *
175  * @type {Array.<DisplayLine>}
176  * @private
177  */
178 var display_lines = [];
179
180 /** @type {?DisplayLine} @private */
181 var current_display_line = null;
182
183 /** @type {boolean} @private */
184 var current_display_line_is_history = false;
185
186 /** @type {?number} @private */
187 var current_display_move = null;
188
189 /**
190  * The current backend request to get main analysis (not history), if any,
191  * so that we can abort it.
192  *
193  * @type {?jqXHR}
194  * @private
195  */
196 var current_analysis_xhr = null;
197
198 /**
199  * The current timer to fire off a request to get main analysis (not history),
200  * if any, so that we can abort it.
201  *
202  * @type {?Number}
203  * @private
204  */
205 var current_analysis_request_timer = null;
206
207 /**
208  * The current backend request to get historic data, if any.
209  *
210  * @type {?jqXHR}
211  * @private
212  */
213 var current_historic_xhr = null;
214
215 /**
216  * The current backend request to get hash probes, if any, so that we can abort it.
217  *
218  * @type {?jqXHR}
219  * @private
220  */
221 var current_hash_xhr = null;
222
223 /**
224  * The current timer to display hash probe information (it could be waiting on the
225  * board to stop animating), if any, so that we can abort it.
226  *
227  * @type {?Number}
228  * @private
229  */
230 var current_hash_display_timer = null;
231
232 var supports_html5_storage = function() {
233         try {
234                 return 'localStorage' in window && window['localStorage'] !== null;
235         } catch (e) {
236                 return false;
237         }
238 }
239
240 // Make the unique token persistent so people refreshing the page won't count twice.
241 // Of course, you can never fully protect against people deliberately wanting to spam.
242 var get_unique = function() {
243         var use_local_storage = supports_html5_storage();
244         if (use_local_storage && localStorage['unique']) {
245                 return localStorage['unique'];
246         }
247         var unique = Math.random();
248         if (use_local_storage) {
249                 localStorage['unique'] = unique;
250         }
251         return unique;
252 }
253
254 var request_update = function() {
255         current_analysis_request_timer = null;
256
257         current_analysis_xhr = $.ajax({
258                 url: backend_url + "?ims=" + ims + "&unique=" + unique
259         }).done(function(data, textstatus, xhr) {
260                 sync_server_clock(xhr.getResponseHeader('Date'));
261                 ims = xhr.getResponseHeader('X-RGLM');
262                 var num_viewers = xhr.getResponseHeader('X-RGNV');
263                 var new_data;
264                 if (Array.isArray(data)) {
265                         new_data = JSON.parse(JSON.stringify(current_analysis_data));
266                         JSON_delta.patch(new_data, data);
267                 } else {
268                         new_data = data;
269                 }
270
271                 var minimum_version = xhr.getResponseHeader('X-RGMV');
272                 if (minimum_version && minimum_version > SCRIPT_VERSION) {
273                         // Upgrade to latest version with a force-reload.
274                         location.reload(true);
275                 }
276
277                 // Verify that the PV makes sense.
278                 var valid = true;
279                 if (new_data['pv']) {
280                         var hiddenboard = new Chess(new_data['position']['fen']);
281                         for (var i = 0; i < new_data['pv'].length; ++i) {
282                                 if (hiddenboard.move(new_data['pv'][i]) === null) {
283                                         valid = false;
284                                         break;
285                                 }
286                         }
287                 }
288
289                 var timeout = 100;
290                 if (valid) {
291                         possibly_play_sound(current_analysis_data, new_data);
292                         current_analysis_data = new_data;
293                         update_board();
294                         update_num_viewers(num_viewers);
295                 } else {
296                         console.log("Received invalid update, waiting five seconds and trying again.");
297                         location.reload(true);
298                 }
299
300                 // Next update.
301                 current_analysis_request_timer = setTimeout(function() { request_update(); }, timeout);
302         }).fail(function(jqXHR, textStatus, errorThrown) {
303                 if (textStatus === "abort") {
304                         // Aborted because we are switching backends. Abandon and don't retry,
305                         // because another one is already started for us.
306                 } else {
307                         // Backend error or similar. Wait ten seconds, then try again.
308                         current_analysis_request_timer = setTimeout(function() { request_update(); }, 10000);
309                 }
310         });
311 }
312
313 var possibly_play_sound = function(old_data, new_data) {
314         if (!enable_sound) {
315                 return;
316         }
317         if (old_data === null) {
318                 return;
319         }
320         var ding = document.getElementById('ding');
321         if (ding && ding.play) {
322                 if (old_data['position'] && old_data['position']['fen'] &&
323                     new_data['position'] && new_data['position']['fen'] &&
324                     (old_data['position']['fen'] !== new_data['position']['fen'] ||
325                      old_data['position']['move_num'] !== new_data['position']['move_num'])) {
326                         ding.play();
327                 }
328         }
329 }
330
331 /**
332  * @type {!string} server_date_string
333  */
334 var sync_server_clock = function(server_date_string) {
335         var server_time_ms = new Date(server_date_string).getTime();
336         var client_time_ms = new Date().getTime();
337         var estimated_offset_ms = server_time_ms - client_time_ms;
338
339         // In order not to let the noise move us too much back and forth
340         // (the server only has one-second resolution anyway), we only
341         // change an existing skew if we are at least five seconds off.
342         if (client_clock_offset_ms === null ||
343             Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
344                 client_clock_offset_ms = estimated_offset_ms;
345         }
346 }
347
348 var clear_arrows = function() {
349         for (var i = 0; i < arrows.length; ++i) {
350                 if (arrows[i].svg) {
351                         if (arrows[i].svg.parentElement) {
352                                 arrows[i].svg.parentElement.removeChild(arrows[i].svg);
353                         }
354                         delete arrows[i].svg;
355                 }
356         }
357         arrows = [];
358
359         occupied_by_arrows = [];
360         for (var y = 0; y < 8; ++y) {
361                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
362         }
363 }
364
365 var redraw_arrows = function() {
366         for (var i = 0; i < arrows.length; ++i) {
367                 position_arrow(arrows[i]);
368         }
369 }
370
371 /** @param {!number} x
372  * @return {!number}
373  */
374 var sign = function(x) {
375         if (x > 0) {
376                 return 1;
377         } else if (x < 0) {
378                 return -1;
379         } else {
380                 return 0;
381         }
382 }
383
384 /** See if drawing this arrow on the board would cause unduly amount of confusion.
385  * @param {!string} from The square the arrow is from (e.g. e4).
386  * @param {!string} to The square the arrow is to (e.g. e4).
387  * @return {boolean}
388  */
389 var interfering_arrow = function(from, to) {
390         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
391         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
392         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
393         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
394
395         occupied_by_arrows[from_row][from_col] = true;
396
397         // Knight move: Just check that we haven't been at the destination before.
398         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
399             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
400                 return occupied_by_arrows[to_row][to_col];
401         }
402
403         // Sliding piece: Check if anything except the from-square is seen before.
404         var dx = sign(to_col - from_col);
405         var dy = sign(to_row - from_row);
406         var x = from_col;
407         var y = from_row;
408         do {
409                 x += dx;
410                 y += dy;
411                 if (occupied_by_arrows[y][x]) {
412                         return true;
413                 }
414                 occupied_by_arrows[y][x] = true;
415         } while (x != to_col || y != to_row);
416
417         return false;
418 }
419
420 /** Find a point along the coordinate system given by the given line,
421  * <t> units forward from the start of the line, <u> units to the right of it.
422  * @param {!number} x1
423  * @param {!number} x2
424  * @param {!number} y1
425  * @param {!number} y2
426  * @param {!number} t
427  * @param {!number} u
428  * @return {!string} The point in "x y" form, suitable for SVG paths.
429  */
430 var point_from_start = function(x1, y1, x2, y2, t, u) {
431         var dx = x2 - x1;
432         var dy = y2 - y1;
433
434         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
435         dx *= norm;
436         dy *= norm;
437
438         var x = x1 + dx * t + dy * u;
439         var y = y1 + dy * t - dx * u;
440         return x + " " + y;
441 }
442
443 /** Find a point along the coordinate system given by the given line,
444  * <t> units forward from the end of the line, <u> units to the right of it.
445  * @param {!number} x1
446  * @param {!number} x2
447  * @param {!number} y1
448  * @param {!number} y2
449  * @param {!number} t
450  * @param {!number} u
451  * @return {!string} The point in "x y" form, suitable for SVG paths.
452  */
453 var point_from_end = function(x1, y1, x2, y2, t, u) {
454         var dx = x2 - x1;
455         var dy = y2 - y1;
456
457         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
458         dx *= norm;
459         dy *= norm;
460
461         var x = x2 + dx * t + dy * u;
462         var y = y2 + dy * t - dx * u;
463         return x + " " + y;
464 }
465
466 var position_arrow = function(arrow) {
467         if (arrow.svg) {
468                 if (arrow.svg.parentElement) {
469                         arrow.svg.parentElement.removeChild(arrow.svg);
470                 }
471                 delete arrow.svg;
472         }
473         if (current_display_line !== null && !current_display_line_is_history) {
474                 return;
475         }
476
477         var zoom_factor = $("#board").width() / 400.0;
478         var line_width = arrow.line_width * zoom_factor;
479         var arrow_size = arrow.arrow_size * zoom_factor;
480
481         var square_width = $(".square-a8").width();
482         var pos, from_y, to_y, from_x, to_x;
483         if (board.orientation() === 'black') {
484                 pos = $(".square-h1").position();
485                 from_y = (arrow.from_row + 0.5)*square_width;
486                 to_y = (arrow.to_row + 0.5)*square_width;
487                 from_x = (7 - arrow.from_col + 0.5)*square_width;
488                 to_x = (7 - arrow.to_col + 0.5)*square_width;
489         } else {
490                 pos = $(".square-a8").position();
491                 from_y = (7 - arrow.from_row + 0.5)*square_width;
492                 to_y = (7 - arrow.to_row + 0.5)*square_width;
493                 from_x = (arrow.from_col + 0.5)*square_width;
494                 to_x = (arrow.to_col + 0.5)*square_width;
495         }
496
497         var SVG_NS = "http://www.w3.org/2000/svg";
498         var XHTML_NS = "http://www.w3.org/1999/xhtml";
499         var svg = document.createElementNS(SVG_NS, "svg");
500         svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
501         svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
502         svg.setAttribute("style", "position: absolute");
503         svg.setAttribute("position", "absolute");
504         svg.setAttribute("version", "1.1");
505         svg.setAttribute("class", "c1");
506         svg.setAttribute("xmlns", XHTML_NS);
507
508         var x1 = from_x;
509         var y1 = from_y;
510         var x2 = to_x;
511         var y2 = to_y;
512
513         // Draw the line.
514         var outline = document.createElementNS(SVG_NS, "path");
515         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));
516         outline.setAttribute("xmlns", XHTML_NS);
517         outline.setAttribute("stroke", "#666");
518         outline.setAttribute("stroke-width", line_width + 2);
519         outline.setAttribute("fill", "none");
520         svg.appendChild(outline);
521
522         var path = document.createElementNS(SVG_NS, "path");
523         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));
524         path.setAttribute("xmlns", XHTML_NS);
525         path.setAttribute("stroke", arrow.fg_color);
526         path.setAttribute("stroke-width", line_width);
527         path.setAttribute("fill", "none");
528         svg.appendChild(path);
529
530         // Then the arrow head.
531         var head = document.createElementNS(SVG_NS, "path");
532         head.setAttribute("d",
533                 "M " +  point_from_end(x1, y1, x2, y2, 0, 0) +
534                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
535                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
536                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
537                 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
538         head.setAttribute("xmlns", XHTML_NS);
539         head.setAttribute("stroke", "#000");
540         head.setAttribute("stroke-width", "1");
541         head.setAttribute("fill", arrow.fg_color);
542         svg.appendChild(head);
543
544         $(svg).css({ top: pos.top, left: pos.left, 'pointer-events': 'none' });
545         document.body.appendChild(svg);
546         arrow.svg = svg;
547 }
548
549 /**
550  * @param {!string} from_square
551  * @param {!string} to_square
552  * @param {!string} fg_color
553  * @param {number} line_width
554  * @param {number} arrow_size
555  */
556 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
557         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
558         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
559         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
560         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
561
562         // Create arrow.
563         var arrow = {
564                 from_col: from_col,
565                 from_row: from_row,
566                 to_col: to_col,
567                 to_row: to_row,
568                 line_width: line_width,
569                 arrow_size: arrow_size,
570                 fg_color: fg_color
571         };
572
573         position_arrow(arrow);
574         arrows.push(arrow);
575 }
576
577 var compare_by_score = function(refutation_lines, invert, a, b) {
578         var sa = compute_score_sort_key(refutation_lines[b]['score'], refutation_lines[b]['depth'], invert);
579         var sb = compute_score_sort_key(refutation_lines[a]['score'], refutation_lines[a]['depth'], invert);
580         return sa - sb;
581 }
582
583 /**
584  * Fake multi-PV using the refutation lines. Find all “relevant” moves,
585  * sorted by quality, descending.
586  *
587  * @param {!Object} data
588  * @param {number} margin The maximum number of centipawns worse than the
589  *     best move can be and still be included.
590  * @param {boolean} invert Whether black is to play.
591  * @return {Array.<string>} The FEN representation (e.g. Ne4) of all
592  *     moves, in score order.
593  */
594 var find_nonstupid_moves = function(data, margin, invert) {
595         // First of all, if there are any moves that are more than 0.5 ahead of
596         // the primary move, the refutation lines are probably bunk, so just
597         // kill them all. 
598         var best_score = undefined;
599         var pv_score = undefined;
600         for (var move in data['refutation_lines']) {
601                 var line = data['refutation_lines'][move];
602                 var score = compute_score_sort_key(line['score'], line['depth'], invert, false);
603                 if (move == data['pv'][0]) {
604                         pv_score = score;
605                 }
606                 if (best_score === undefined || score > best_score) {
607                         best_score = score;
608                 }
609                 if (line['depth'] < 8) {
610                         return [];
611                 }
612         }
613
614         if (best_score - pv_score > 50) {
615                 return [];
616         }
617
618         // Now find all moves that are within “margin” of the best score.
619         // The PV move will always be first.
620         var moves = [];
621         for (var move in data['refutation_lines']) {
622                 var line = data['refutation_lines'][move];
623                 var score = compute_score_sort_key(line['score'], line['depth'], invert);
624                 if (move != data['pv'][0] && best_score - score <= margin) {
625                         moves.push(move);
626                 }
627         }
628         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], data['position']['toplay'] === 'B', a, b) });
629         moves.unshift(data['pv'][0]);
630
631         return moves;
632 }
633
634 /**
635  * @param {number} x
636  * @return {!string}
637  */
638 var thousands = function(x) {
639         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
640 }
641
642 /**
643  * @param {!string} start_fen
644  * @param {Array.<string>} pv
645  * @param {number} move_num
646  * @param {!string} toplay
647  * @param {Array<{ first_move: integer, score: Object }>} scores
648  * @param {number} start_display_move_num
649  * @param {number=} opt_limit
650  * @param {boolean=} opt_showlast
651  */
652 var add_pv = function(start_fen, pv, move_num, toplay, scores, start_display_move_num, opt_limit, opt_showlast) {
653         display_lines.push({
654                 start_fen: start_fen,
655                 pv: pv,
656                 move_num: parseInt(move_num),
657                 toplay: toplay,
658                 scores: scores,
659                 start_display_move_num: start_display_move_num
660         });
661         return print_pv(display_lines.length - 1, opt_limit, opt_showlast);
662 }
663
664 /**
665  * @param {number} line_num
666  * @param {number=} opt_limit If set, show at most this number of moves.
667  * @param {boolean=} opt_showlast If limit is set, show the last moves instead of the first ones.
668  */
669 var print_pv = function(line_num, opt_limit, opt_showlast) {
670         var display_line = display_lines[line_num];
671         var pv = display_line.pv;
672         var move_num = display_line.move_num;
673         var toplay = display_line.toplay;
674
675         // Truncate PV at the start if needed.
676         var start_display_move_num = display_line.start_display_move_num;
677         if (start_display_move_num > 0) {
678                 pv = pv.slice(start_display_move_num);
679                 var to_add = start_display_move_num;
680                 if (toplay === 'B') {
681                         ++move_num;
682                         toplay = 'W';
683                         --to_add;
684                 }
685                 if (to_add % 2 == 1) {
686                         toplay = 'B';
687                         --to_add;
688                 }
689                 move_num += to_add / 2;
690         }
691
692         var ret = '';
693         var i = 0;
694         if (opt_limit && opt_showlast && pv.length > opt_limit) {
695                 // Truncate the PV at the beginning (instead of at the end).
696                 // We assume here that toplay is 'W'. We also assume that if
697                 // opt_showlast is set, then it is the history, and thus,
698                 // the UI should be to expand the history.
699                 ret = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
700                 i = pv.length - opt_limit;
701                 if (i % 2 == 1) {
702                         ++i;
703                 }
704                 move_num += i / 2;
705         } else if (toplay == 'B' && pv.length > 0) {
706                 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pv[0] + "</a>";
707                 ret = move_num + '. … ' + move;
708                 toplay = 'W';
709                 ++i;
710                 ++move_num;
711         }
712         for ( ; i < pv.length; ++i) {
713                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pv[i] + "</a>";
714
715                 if (toplay == 'W') {
716                         if (i > opt_limit && !opt_showlast) {
717                                 return ret + ' (…)';
718                         }
719                         if (ret != '') {
720                                 ret += ' ';
721                         }
722                         ret += move_num + '. ' + move;
723                         ++move_num;
724                         toplay = 'B';
725                 } else {
726                         ret += ' ' + move;
727                         toplay = 'W';
728                 }
729         }
730         return ret;
731 }
732
733 /** Update the highlighted to/from squares on the board.
734  * Based on the global "highlight_from" and "highlight_to" variables.
735  */
736 var update_board_highlight = function() {
737         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
738         if ((current_display_line === null || current_display_line_is_history) &&
739             highlight_from !== undefined && highlight_to !== undefined) {
740                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
741                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
742         }
743 }
744
745 var update_history = function() {
746         if (display_lines[0] === null || display_lines[0].pv.length == 0) {
747                 $("#history").html("No history");
748         } else if (truncate_display_history) {
749                 $("#history").html(print_pv(0, 8, true));
750         } else {
751                 $("#history").html(
752                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
753                         print_pv(0));
754         }
755 }
756
757 /**
758  * @param {!boolean} truncate_history
759  */
760 var collapse_history = function(truncate_history) {
761         truncate_display_history = truncate_history;
762         update_history();
763 }
764 window['collapse_history'] = collapse_history;
765
766 /** Update the HTML display of multi-PV from the global "refutation_lines".
767  *
768  * Also recreates the global "display_lines".
769  */
770 var update_refutation_lines = function() {
771         if (base_fen === null) {
772                 return;
773         }
774         if (display_lines.length > 2) {
775                 // Truncate so that only the history and PV is left.
776                 display_lines = [ display_lines[0], display_lines[1] ];
777         }
778         var tbl = $("#refutationlines");
779         tbl.empty();
780
781         // Find out where the lines start from.
782         var base_line = [];
783         var base_scores = display_lines[1].scores;
784         var start_display_move_num = 0;
785         if (hash_refutation_lines) {
786                 base_line = current_display_line.pv.slice(0, current_display_move + 1);
787                 base_scores = current_display_line.scores;
788                 start_display_move_num = base_line.length;
789         }
790
791         var moves = [];
792         for (var move in refutation_lines) {
793                 moves.push(move);
794         }
795
796         var invert = (toplay === 'B');
797         if (current_display_line && current_display_move % 2 == 0) {
798                 invert = !invert;
799         }
800         moves = moves.sort(function(a, b) { return compare_by_score(refutation_lines, invert, a, b) });
801         for (var i = 0; i < moves.length; ++i) {
802                 var line = refutation_lines[moves[i]];
803
804                 var tr = document.createElement("tr");
805
806                 var move_td = document.createElement("td");
807                 tr.appendChild(move_td);
808                 $(move_td).addClass("move");
809
810                 var scores = base_scores.concat([{ first_move: start_display_move_num, score: line['score'] }]);
811
812                 if (line['pv'].length == 0) {
813                         // Not found, so just make a one-move PV.
814                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
815                         $(move_td).html(move);
816                         var score_td = document.createElement("td");
817
818                         $(score_td).addClass("score");
819                         $(score_td).text("—");
820                         tr.appendChild(score_td);
821
822                         var depth_td = document.createElement("td");
823                         tr.appendChild(depth_td);
824                         $(depth_td).addClass("depth");
825                         $(depth_td).text("—");
826
827                         var pv_td = document.createElement("td");
828                         tr.appendChild(pv_td);
829                         $(pv_td).addClass("pv");
830                         $(pv_td).html(add_pv(base_fen, base_line.concat([ line['move'] ]), move_num, toplay, scores, start_display_move_num));
831
832                         tbl.append(tr);
833                         continue;
834                 }
835
836                 var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['move'] + "</a>";
837                 $(move_td).html(move);
838
839                 var score_td = document.createElement("td");
840                 tr.appendChild(score_td);
841                 $(score_td).addClass("score");
842                 $(score_td).text(format_short_score(line['score']));
843
844                 var depth_td = document.createElement("td");
845                 tr.appendChild(depth_td);
846                 $(depth_td).addClass("depth");
847                 if (line['depth'] && line['depth'] >= 0) {
848                         $(depth_td).text("d" + line['depth']);
849                 } else {
850                         $(depth_td).text("—");
851                 }
852
853                 var pv_td = document.createElement("td");
854                 tr.appendChild(pv_td);
855                 $(pv_td).addClass("pv");
856                 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv']), move_num, toplay, scores, start_display_move_num, 10));
857
858                 tbl.append(tr);
859         }
860
861         // Update the move highlight, as we've rewritten all the HTML.
862         update_move_highlight();
863 }
864
865 /**
866  * Create a Chess.js board object, containing the given position plus the given moves,
867  * up to the given limit.
868  *
869  * @param {?string} fen
870  * @param {Array.<string>} moves
871  * @param {number} last_move
872  */
873 var chess_from = function(fen, moves, last_move) {
874         var hiddenboard = new Chess();
875         if (fen !== null && fen !== undefined) {
876                 hiddenboard.load(fen);
877         }
878         for (var i = 0; i <= last_move; ++i) {
879                 if (moves[i] === '0-0') {
880                         hiddenboard.move('O-O');
881                 } else if (moves[i] === '0-0-0') {
882                         hiddenboard.move('O-O-O');
883                 } else {
884                         hiddenboard.move(moves[i]);
885                 }
886         }
887         return hiddenboard;
888 }
889
890 var update_game_list = function(games) {
891         $("#games").text("");
892         if (games === null) {
893                 return;
894         }
895
896         var games_div = document.getElementById('games');
897         for (var game_num = 0; game_num < games.length; ++game_num) {
898                 var game = games[game_num];
899                 var game_span = document.createElement("span");
900                 game_span.setAttribute("class", "game");
901
902                 var game_name = document.createTextNode(game['name']);
903                 if (game['url'] === backend_url) {
904                         // This game.
905                         game_span.appendChild(game_name);
906
907                         if (current_analysis_data && current_analysis_data['position']) {
908                                 var score;
909                                 if (current_analysis_data['position']['result']) {
910                                         score = " (" + current_analysis_data['position']['result'] + ")";
911                                 } else {
912                                         score = " (" + format_short_score(current_analysis_data['score']) + ")";
913                                 }
914                                 game_span.appendChild(document.createTextNode(score));
915                         }
916                 } else {
917                         // Some other game.
918                         var game_a = document.createElement("a");
919                         game_a.setAttribute("href", "#" + game['id']);
920                         game_a.appendChild(game_name);
921                         game_span.appendChild(game_a);
922
923                         var score;
924                         if (game['result']) {
925                                 score = " (" + game['result'] + ")";
926                         } else {
927                                 score = " (" + format_short_score(game['score']) + ")";
928                         }
929                         game_span.appendChild(document.createTextNode(score));
930                 }
931
932                 games_div.appendChild(game_span);
933         }
934 }
935
936 /**
937  * Try to find a running game that matches with the current hash,
938  * and switch to it if we're not already displaying it.
939  */
940 var possibly_switch_game_from_hash = function() {
941         if (current_games === null) {
942                 return;
943         }
944
945         var hash = window.location.hash.replace(/^#/,'');
946         for (var i = 0; i < current_games.length; ++i) {
947                 if (current_games[i]['id'] === hash) {
948                         if (backend_url !== current_games[i]['url']) {
949                                 switch_backend(current_games[i]);
950                         }
951                         return;
952                 }
953         }
954 }
955
956 /**
957  * If this is a Chess960 castling which doesn't move the king,
958  * move the rook instead.
959 */
960 var patch_move = function(move) {
961         if (move === null) return null;
962         if (move.from !== move.to) return move;
963
964         var f = move.rook_sq & 15;
965         var r = move.rook_sq >> 4;
966         var from = ('abcdefgh'.substring(f,f+1) + '87654321'.substring(r,r+1));
967         var to = move.to;
968
969         if (move.to === 'g1') {
970                 to = 'f1';
971         } else if (move.to === 'g8') {
972                 to = 'f8';
973         } else if (move.to === 'b1') {
974                 to = 'c1';
975         } else if (move.to === 'b8') {
976                 to = 'c8';
977         }
978
979         return { from: from, to: to };
980 }
981
982 /** Update all the HTML on the page, based on current global state.
983  */
984 var update_board = function() {
985         var data = displayed_analysis_data || current_analysis_data;
986         var current_data = current_analysis_data;  // Convenience alias.
987
988         display_lines = [];
989
990         // Print the history. This is pretty much the only thing that's
991         // unconditionally taken from current_data (we're not interested in
992         // historic history).
993         if (current_data['position']['history']) {
994                 var start = (current_data['position'] && current_data['position']['start_fen']) ? current_data['position']['start_fen'] : 'start';
995                 add_pv(start, current_data['position']['history'], 1, 'W', null, 0, 8, true);
996         } else {
997                 display_lines.push(null);
998         }
999         update_history();
1000
1001         // Games currently in progress, if any.
1002         if (current_data['games']) {
1003                 current_games = current_data['games'];
1004                 possibly_switch_game_from_hash();
1005         } else {
1006                 current_games = null;
1007         }
1008         update_game_list(current_games);
1009
1010         // The headline. Names are always fetched from current_data;
1011         // the rest can depend a bit.
1012         var headline;
1013         if (current_data &&
1014             current_data['position']['player_w'] && current_data['position']['player_b']) {
1015                 headline = current_data['position']['player_w'] + '–' +
1016                         current_data['position']['player_b'] + ', analysis';
1017         } else {
1018                 headline = 'Analysis';
1019         }
1020
1021         // Credits, where applicable. Note that we don't want the footer to change a lot
1022         // when e.g. viewing history, so if any of these changed during the game,
1023         // use the current one still.
1024         if (current_data['using_lomonosov']) {
1025                 $("#lomonosov").show();
1026         } else {
1027                 $("#lomonosov").hide();
1028         }
1029
1030         // Credits: The engine name/version.
1031         if (current_data['engine'] && current_data['engine']['name'] !== null) {
1032                 $("#engineid").text(current_data['engine']['name']);
1033         }
1034
1035         // Credits: The engine URL.
1036         if (current_data['engine'] && current_data['engine']['url']) {
1037                 $("#engineid").attr("href", current_data['engine']['url']);
1038         } else {
1039                 $("#engineid").removeAttr("href");
1040         }
1041
1042         // Credits: Engine details.
1043         if (current_data['engine'] && current_data['engine']['details']) {
1044                 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
1045         } else {
1046                 $("#enginedetails").text("");
1047         }
1048
1049         // Credits: Move source, possibly with URL.
1050         if (current_data['move_source'] && current_data['move_source_url']) {
1051                 $("#movesource").text("Moves provided by ");
1052                 var movesource_a = document.createElement("a");
1053                 movesource_a.setAttribute("href", current_data['move_source_url']);
1054                 var movesource_text = document.createTextNode(current_data['move_source']);
1055                 movesource_a.appendChild(movesource_text);
1056                 var movesource_period = document.createTextNode(".");
1057                 document.getElementById("movesource").appendChild(movesource_a);
1058                 document.getElementById("movesource").appendChild(movesource_period);
1059         } else if (current_data['move_source']) {
1060                 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
1061         } else {
1062                 $("#movesource").text("");
1063         }
1064
1065         var last_move;
1066         if (displayed_analysis_data) {
1067                 // Displaying some non-current position, pick out the last move
1068                 // from the history. This will work even if the fetch failed.
1069                 if (current_display_move !== -1) {
1070                         last_move = format_halfmove_with_number(
1071                                 current_display_line.pv[current_display_move],
1072                                 current_display_move);
1073                         headline += ' after ' + last_move;
1074                 }
1075         } else if (data['position']['last_move'] !== 'none') {
1076                 // Find the previous move.
1077                 var previous_move_num, previous_toplay;
1078                 if (data['position']['toplay'] == 'B') {
1079                         previous_move_num = data['position']['move_num'];
1080                         previous_toplay = 'W';
1081                 } else {
1082                         previous_move_num = data['position']['move_num'] - 1;
1083                         previous_toplay = 'B';
1084                 }
1085
1086                 last_move = format_move_with_number(
1087                         data['position']['last_move'],
1088                         previous_move_num,
1089                         previous_toplay == 'W');
1090                 headline += ' after ' + last_move;
1091         } else {
1092                 last_move = null;
1093         }
1094         $("#headline").text(headline);
1095
1096         // The <title> contains a very brief headline.
1097         var title_elems = [];
1098         if (data['position'] && data['position']['result']) {
1099                 title_elems.push(data['position']['result']);
1100         } else if (data['score']) {
1101                 title_elems.push(format_short_score(data['score']));
1102         }
1103         if (last_move !== null) {
1104                 title_elems.push(last_move);
1105         }
1106
1107         if (title_elems.length != 0) {
1108                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1109         } else {
1110                 document.title = 'analysis.sesse.net';
1111         }
1112
1113         // The last move (shown by highlighting the from and to squares).
1114         if (data['position'] && data['position']['last_move_uci']) {
1115                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1116                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1117         } else if (current_display_line_is_history && current_display_line && current_display_move >= 0) {
1118                 // We don't have historic analysis for this position, but we
1119                 // can reconstruct what the last move was by just replaying
1120                 // from the start.
1121                 var position = (data['position'] && data['position']['start_fen']) ? data['position']['start_fen'] : null;
1122                 var hiddenboard = chess_from(position, current_display_line.pv, current_display_move);
1123                 var moves = hiddenboard.history({ verbose: true });
1124                 last_move = moves.pop();
1125                 highlight_from = last_move.from;
1126                 highlight_to = last_move.to;
1127         } else {
1128                 highlight_from = highlight_to = undefined;
1129         }
1130         update_board_highlight();
1131
1132         if (data['failed']) {
1133                 $("#score").text("No analysis for this move");
1134                 $("#pvtitle").text("PV:");
1135                 $("#pv").empty();
1136                 $("#searchstats").html("&nbsp;");
1137                 $("#refutationlines").empty();
1138                 $("#whiteclock").empty();
1139                 $("#blackclock").empty();
1140                 refutation_lines = [];
1141                 update_refutation_lines();
1142                 clear_arrows();
1143                 update_displayed_line();
1144                 update_move_highlight();
1145                 return;
1146         }
1147
1148         update_clock();
1149
1150         // The score.
1151         if (current_display_line && !current_display_line_is_history) {
1152                 var score;
1153                 if (current_display_line.scores && current_display_line.scores.length > 0) {
1154                         for (var i = 0; i < current_display_line.scores.length; ++i) {
1155                                 if (current_display_move < current_display_line.scores[i].first_move) {
1156                                         break;
1157                                 }
1158                                 score = current_display_line.scores[i].score;
1159                         }
1160                 }
1161                 if (score) {
1162                         $("#score").text(format_long_score(score));
1163                 } else {
1164                         $("#score").text("No score for this line");
1165                 }
1166         } else if (data['score']) {
1167                 $("#score").text(format_long_score(data['score']));
1168         }
1169
1170         // The search stats.
1171         if (data['searchstats']) {
1172                 $("#searchstats").html(data['searchstats']);
1173         } else if (data['tablebase'] == 1) {
1174                 $("#searchstats").text("Tablebase result");
1175         } else if (data['nodes'] && data['nps'] && data['depth']) {
1176                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1177                 if (data['seldepth']) {
1178                         stats += ' (' + data['seldepth'] + ' selective)';
1179                 }
1180                 if (data['tbhits'] && data['tbhits'] > 0) {
1181                         if (data['tbhits'] == 1) {
1182                                 stats += ', one Syzygy hit';
1183                         } else {
1184                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1185                         }
1186                 }
1187
1188                 $("#searchstats").text(stats);
1189         } else {
1190                 $("#searchstats").text("");
1191         }
1192
1193         // Update the board itself.
1194         base_fen = data['position']['fen'];
1195         update_displayed_line();
1196
1197         // Print the PV.
1198         $("#pvtitle").text("PV:");
1199
1200         var scores = [{ first_move: -1, score: data['score'] }];
1201         $("#pv").html(add_pv(data['position']['fen'], data['pv'], data['position']['move_num'], data['position']['toplay'], scores, 0));
1202
1203         // Update the PV arrow.
1204         clear_arrows();
1205         if (data['pv'].length >= 1) {
1206                 var hiddenboard = new Chess(base_fen);
1207
1208                 // draw a continuation arrow as long as it's the same piece
1209                 var last_to;
1210                 for (var i = 0; i < data['pv'].length; i += 2) {
1211                         var move = patch_move(hiddenboard.move(data['pv'][i]));
1212
1213                         if ((i >= 2 && move.from != last_to) ||
1214                              interfering_arrow(move.from, move.to)) {
1215                                 break;
1216                         }
1217                         create_arrow(move.from, move.to, '#f66', 6, 20);
1218                         last_to = move.to;
1219                         hiddenboard.move(data['pv'][i + 1]);  // To keep continuity.
1220                 }
1221
1222                 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1223                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1224                         hiddenboard = new Chess(base_fen);
1225                         var move = patch_move(hiddenboard.move(alt_moves[i]));
1226                         if (move !== null) {
1227                                 create_arrow(move.from, move.to, '#f66', 1, 10);
1228                         }
1229                 }
1230         }
1231
1232         // See if all semi-reasonable moves have only one possible response.
1233         if (data['pv'].length >= 2) {
1234                 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1235                 var response;
1236                 {
1237                         var hiddenboard = new Chess(base_fen);
1238                         hiddenboard.move(data['pv'][0]);
1239                         response = hiddenboard.move(data['pv'][1]);
1240                 }
1241                 for (var i = 0; i < nonstupid_moves.length; ++i) {
1242                         if (nonstupid_moves[i] == data['pv'][0]) {
1243                                 // ignore the PV move for refutation lines.
1244                                 continue;
1245                         }
1246                         if (!data['refutation_lines'] ||
1247                             !data['refutation_lines'][nonstupid_moves[i]] ||
1248                             !data['refutation_lines'][nonstupid_moves[i]]['pv'] ||
1249                             data['refutation_lines'][nonstupid_moves[i]]['pv'].length < 1) {
1250                                 // Incomplete PV, abort.
1251                                 response = undefined;
1252                                 break;
1253                         }
1254                         var line = data['refutation_lines'][nonstupid_moves[i]];
1255                         hiddenboard = new Chess(base_fen);
1256                         hiddenboard.move(line['pv'][0]);
1257                         var this_response = hiddenboard.move(line['pv'][1]);
1258                         if (response.from !== this_response.from || response.to !== this_response.to) {
1259                                 // Different response depending on lines, abort.
1260                                 response = undefined;
1261                                 break;
1262                         }
1263                 }
1264
1265                 if (nonstupid_moves.length > 0 && response !== undefined) {
1266                         create_arrow(response.from, response.to, '#66f', 6, 20);
1267                 }
1268         }
1269
1270         // Update the refutation lines.
1271         base_fen = data['position']['fen'];
1272         move_num = parseInt(data['position']['move_num']);
1273         toplay = data['position']['toplay'];
1274         refutation_lines = hash_refutation_lines || data['refutation_lines'];
1275         update_refutation_lines();
1276
1277         // Update the sparkline last, since its size depends on how everything else reflowed.
1278         update_sparkline(data);
1279 }
1280
1281 var update_sparkline = function(data) {
1282         if (data && data['score_history']) {
1283                 var first_move_num = undefined;
1284                 for (var halfmove_num in data['score_history']) {
1285                         halfmove_num = parseInt(halfmove_num);
1286                         if (first_move_num === undefined || halfmove_num < first_move_num) {
1287                                 first_move_num = halfmove_num;
1288                         }
1289                 }
1290                 if (first_move_num !== undefined) {
1291                         var last_move_num = data['position']['move_num'] * 2 - 3;
1292                         if (data['position']['toplay'] === 'B') {
1293                                 ++last_move_num;
1294                         }
1295
1296                         // Possibly truncate some moves if we don't have enough width.
1297                         // FIXME: Sometimes width() for #scorecontainer (and by extent,
1298                         // #scoresparkcontainer) on Chrome for mobile seems to start off
1299                         // at something very small, and then suddenly snap back into place.
1300                         // Figure out why.
1301                         var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1302                         if (last_move_num - first_move_num > max_moves) {
1303                                 first_move_num = last_move_num - max_moves;
1304                         }
1305
1306                         var min_score = -100;
1307                         var max_score = 100;
1308                         var last_score = null;
1309                         var scores = [];
1310                         for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1311                                 if (data['score_history'][halfmove_num]) {
1312                                         var score = compute_plot_score(data['score_history'][halfmove_num]);
1313                                         last_score = score;
1314                                         if (score < min_score) min_score = score;
1315                                         if (score > max_score) max_score = score;
1316                                 }
1317                                 scores.push(last_score);
1318                         }
1319                         if (data['score']) {
1320                                 scores.push(compute_plot_score(data['score']));
1321                         }
1322                         // FIXME: at some widths, calling sparkline() seems to push
1323                         // #scorecontainer under the board.
1324                         $("#scorespark").sparkline(scores, {
1325                                 type: 'bar',
1326                                 zeroColor: 'gray',
1327                                 chartRangeMin: min_score,
1328                                 chartRangeMax: max_score,
1329                                 tooltipFormatter: function(sparkline, options, fields) {
1330                                         // score_history contains the Nth _position_, but format_tooltip
1331                                         // wants to format the Nth _move_; thus the -1.
1332                                         return format_tooltip(data, fields[0].offset + first_move_num - 1);
1333                                 }
1334                         });
1335                         $('#scorespark').bind('sparklineClick', function(event) {
1336                                 var sparkline = event.sparklines[0];
1337                                 var region = sparkline.getCurrentRegionFields();
1338                                 if (region[0].offset !== undefined) {
1339                                         show_line(0, first_move_num + region[0].offset - 1);
1340                                 }
1341                         });
1342                 } else {
1343                         $("#scorespark").text("");
1344                 }
1345         } else {
1346                 $("#scorespark").text("");
1347         }
1348 }
1349
1350 /**
1351  * @param {number} num_viewers
1352  */
1353 var update_num_viewers = function(num_viewers) {
1354         if (num_viewers === null) {
1355                 $("#numviewers").text("");
1356         } else if (num_viewers == 1) {
1357                 $("#numviewers").text("You are the only current viewer");
1358         } else {
1359                 $("#numviewers").text(num_viewers + " current viewers");
1360         }
1361 }
1362
1363 var update_clock = function() {
1364         clearTimeout(clock_timer);
1365
1366         var data = displayed_analysis_data || current_analysis_data;
1367         if (!data) return;
1368
1369         if (data['position']) {
1370                 var result = data['position']['result'];
1371                 if (result === '1-0') {
1372                         $("#whiteclock").text("1");
1373                         $("#blackclock").text("0");
1374                         $("#whiteclock").removeClass("running-clock");
1375                         $("#blackclock").removeClass("running-clock");
1376                         return;
1377                 }
1378                 if (result === '1/2-1/2') {
1379                         $("#whiteclock").text("1/2");
1380                         $("#blackclock").text("1/2");
1381                         $("#whiteclock").removeClass("running-clock");
1382                         $("#blackclock").removeClass("running-clock");
1383                         return;
1384                 }       
1385                 if (result === '0-1') {
1386                         $("#whiteclock").text("0");
1387                         $("#blackclock").text("1");
1388                         $("#whiteclock").removeClass("running-clock");
1389                         $("#blackclock").removeClass("running-clock");
1390                         return;
1391                 }
1392         }
1393
1394         var white_clock_ms = null;
1395         var black_clock_ms = null;
1396
1397         // Static clocks.
1398         if (data['position'] &&
1399             data['position']['white_clock'] &&
1400             data['position']['black_clock']) {
1401                 white_clock_ms = data['position']['white_clock'] * 1000;
1402                 black_clock_ms = data['position']['black_clock'] * 1000;
1403         }
1404
1405         // Dynamic clock (only one, obviously).
1406         var color;
1407         if (data['position']['white_clock_target']) {
1408                 color = "white";
1409                 $("#whiteclock").addClass("running-clock");
1410                 $("#blackclock").removeClass("running-clock");
1411         } else if (data['position']['black_clock_target']) {
1412                 color = "black";
1413                 $("#whiteclock").removeClass("running-clock");
1414                 $("#blackclock").addClass("running-clock");
1415         } else {
1416                 $("#whiteclock").removeClass("running-clock");
1417                 $("#blackclock").removeClass("running-clock");
1418         }
1419         var remaining_ms;
1420         if (color) {
1421                 var now = new Date().getTime() + client_clock_offset_ms;
1422                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1423                 if (color === "white") {
1424                         white_clock_ms = remaining_ms;
1425                 } else {
1426                         black_clock_ms = remaining_ms;
1427                 }
1428         }
1429
1430         if (white_clock_ms === null || black_clock_ms === null) {
1431                 $("#whiteclock").empty();
1432                 $("#blackclock").empty();
1433                 return;
1434         }
1435
1436         // If either player has twenty minutes or less left, add the second counters.
1437         // This matches what DGT clocks do.
1438         var show_seconds = (white_clock_ms < 60 * 20 * 1000 || black_clock_ms < 60 * 20 * 1000);
1439
1440         if (color) {
1441                 // See when the clock will change next, and update right after that.
1442                 var next_update_ms;
1443                 if (show_seconds) {
1444                         next_update_ms = remaining_ms % 1000 + 100;
1445                 } else {
1446                         next_update_ms = remaining_ms % 60000 + 100;
1447                 }
1448                 clock_timer = setTimeout(update_clock, next_update_ms);
1449         }
1450
1451         $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1452         $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1453 }
1454
1455 /**
1456  * @param {Number} remaining_ms
1457  * @param {boolean} show_seconds
1458  */
1459 var format_clock = function(remaining_ms, show_seconds) {
1460         if (remaining_ms <= 0) {
1461                 if (show_seconds) {
1462                         return "00:00:00";
1463                 } else {
1464                         return "00:00";
1465                 }
1466         }
1467
1468         var remaining = Math.floor(remaining_ms / 1000);
1469         var seconds = remaining % 60;
1470         remaining = (remaining - seconds) / 60;
1471         var minutes = remaining % 60;
1472         remaining = (remaining - minutes) / 60;
1473         var hours = remaining;
1474         if (show_seconds) {
1475                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1476         } else {
1477                 return format_2d(hours) + ":" + format_2d(minutes);
1478         }
1479 }
1480
1481 /**
1482  * @param {Number} x
1483  */
1484 var format_2d = function(x) {
1485         if (x >= 10) {
1486                 return x;
1487         } else {
1488                 return "0" + x;
1489         }
1490 }
1491
1492 /**
1493  * @param {string} move
1494  * @param {Number} move_num Move number of this move.
1495  * @param {boolean} white_to_play Whether white is to play this move.
1496  */
1497 var format_move_with_number = function(move, move_num, white_to_play) {
1498         var ret;
1499         if (white_to_play) {
1500                 ret = move_num + '. ';
1501         } else {
1502                 ret = move_num + '… ';
1503         }
1504         ret += move;
1505         return ret;
1506 }
1507
1508 /**
1509  * @param {string} move
1510  * @param {Number} halfmove_num Half-move number that is to be played,
1511  *   starting from 0.
1512  */
1513 var format_halfmove_with_number = function(move, halfmove_num) {
1514         return format_move_with_number(
1515                 move,
1516                 Math.floor(halfmove_num / 2) + 1,
1517                 halfmove_num % 2 == 0);
1518 }
1519
1520 /**
1521  * @param {Object} data
1522  * @param {Number} halfmove_num
1523  */
1524 var format_tooltip = function(data, halfmove_num) {
1525         if (data['score_history'][halfmove_num + 1] ||
1526             (halfmove_num + 1) === data['position']['history'].length) {
1527                 // Position is in the history, or it is the current position
1528                 // (which is implicitly tacked onto the history).
1529                 var move;
1530                 var short_score;
1531                 if ((halfmove_num + 1) === data['position']['history'].length) {
1532                         move = data['position']['last_move'];
1533                         short_score = format_short_score(data['score']);
1534                 } else {
1535                         move = data['position']['history'][halfmove_num];
1536                         short_score = format_short_score(data['score_history'][halfmove_num + 1]);
1537                 }
1538                 if (halfmove_num === -1) {
1539                         return "Start position: " + short_score;
1540                 } else {
1541                         var move_with_number = format_halfmove_with_number(move, halfmove_num);
1542                         return "After " + move_with_number + ": " + short_score;
1543                 }
1544         } else {
1545                 for (var i = halfmove_num; i --> -1; ) {
1546                         if (data['score_history'][i]) {
1547                                 var move = data['position']['history'][i];
1548                                 if (i === -1) {
1549                                         return "[Analysis kept from start position]";
1550                                 } else {
1551                                         return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1552                                 }
1553                         }
1554                 }
1555         }
1556 }
1557
1558 /**
1559  * @param {boolean} truncate_history
1560  */
1561 var set_truncate_history = function(truncate_history) {
1562         truncate_display_history = truncate_history;
1563         update_refutation_lines();
1564 }
1565 window['set_truncate_history'] = set_truncate_history;
1566
1567 /**
1568  * @param {number} line_num
1569  * @param {number} move_num
1570  */
1571 var show_line = function(line_num, move_num) {
1572         if (line_num == -1) {
1573                 current_display_line = null;
1574                 current_display_move = null;
1575                 hash_refutation_lines = null;
1576                 if (displayed_analysis_data) {
1577                         // TODO: Support exiting to history position if we are in an
1578                         // analysis line of a history position.
1579                         displayed_analysis_data = null;
1580                 }
1581                 update_board();
1582                 return;
1583         } else {
1584                 current_display_line = jQuery.extend({}, display_lines[line_num]);  // Shallow clone.
1585                 current_display_move = move_num + current_display_line.start_display_move_num;
1586         }
1587         current_display_line_is_history = (line_num == 0);
1588
1589         update_historic_analysis();
1590         update_displayed_line();
1591         update_board_highlight();
1592         update_move_highlight();
1593         redraw_arrows();
1594 }
1595 window['show_line'] = show_line;
1596
1597 var prev_move = function() {
1598         if (current_display_line &&
1599             current_display_move >= current_display_line.start_display_move_num) {
1600                 --current_display_move;
1601         }
1602         update_historic_analysis();
1603         update_displayed_line();
1604         update_move_highlight();
1605 }
1606 window['prev_move'] = prev_move;
1607
1608 var next_move = function() {
1609         if (current_display_line &&
1610             current_display_move < current_display_line.pv.length - 1) {
1611                 ++current_display_move;
1612         }
1613         update_historic_analysis();
1614         update_displayed_line();
1615         update_move_highlight();
1616 }
1617 window['next_move'] = next_move;
1618
1619 var next_game = function() {
1620         if (current_games === null) {
1621                 return;
1622         }
1623
1624         // Try to find the game we are currently looking at.
1625         for (var game_num = 0; game_num < current_games.length; ++game_num) {
1626                 var game = current_games[game_num];
1627                 if (game['url'] === backend_url) {
1628                         var next_game_num = (game_num + 1) % current_games.length;
1629                         switch_backend(current_games[next_game_num]);
1630                         return;
1631                 }
1632         }
1633
1634         // Couldn't find it; give up.
1635 }
1636
1637 var update_historic_analysis = function() {
1638         if (!current_display_line_is_history) {
1639                 return;
1640         }
1641         if (current_display_move == current_display_line.pv.length - 1) {
1642                 displayed_analysis_data = null;
1643                 update_board();
1644         }
1645
1646         // Fetch old analysis for this line if it exists.
1647         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1648         var filename = "/history/move" + (current_display_move + 1) + "-" +
1649                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1650
1651         current_historic_xhr = $.ajax({
1652                 url: filename
1653         }).done(function(data, textstatus, xhr) {
1654                 displayed_analysis_data = data;
1655                 update_board();
1656         }).fail(function(jqXHR, textStatus, errorThrown) {
1657                 if (textStatus === "abort") {
1658                         // Aborted because we are switching backends. Don't do anything;
1659                         // we will already have been cleared.
1660                 } else {
1661                         displayed_analysis_data = {'failed': true};
1662                         update_board();
1663                 }
1664         });
1665 }
1666
1667 /**
1668  * @param {string} fen
1669  */
1670 var update_imbalance = function(fen) {
1671         var hiddenboard = new Chess(fen);
1672         var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1673         for (var row = 0; row < 8; ++row) {
1674                 for (var col = 0; col < 8; ++col) {
1675                         var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1676                         var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1677                         var square = col_text + row_text;
1678                         var contents = hiddenboard.get(square);
1679                         if (contents !== null) {
1680                                 if (contents.color === 'w') {
1681                                         ++imbalance[contents.type];
1682                                 } else {
1683                                         --imbalance[contents.type];
1684                                 }
1685                         }
1686                 }
1687         }
1688         var white_imbalance = '';
1689         var black_imbalance = '';
1690         for (var piece in imbalance) {
1691                 for (var i = 0; i < imbalance[piece]; ++i) {
1692                         white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1693                 }
1694                 for (var i = 0; i < -imbalance[piece]; ++i) {
1695                         black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1696                 }
1697         }
1698         $('#whiteimbalance').html(white_imbalance);
1699         $('#blackimbalance').html(black_imbalance);
1700 }
1701
1702 /** Mark the currently selected move in red.
1703  * Also replaces the PV with the current displayed line if it's not shown
1704  * anywhere else on the screen.
1705  */
1706 var update_move_highlight = function() {
1707         if (highlighted_move !== null) {
1708                 highlighted_move.removeClass('highlight'); 
1709         }
1710         if (current_display_line) {
1711                 var display_line_num = find_display_line_matching_num();
1712                 if (display_line_num === null) {
1713                         // Replace the PV with the (complete) line.
1714                         $("#pvtitle").text("Exploring:");
1715                         current_display_line.start_display_move_num = 0;
1716                         display_lines.push(current_display_line);
1717                         $("#pv").html(print_pv(display_lines.length - 1));
1718                         display_line_num = display_lines.length - 1;
1719
1720                         // Clear out the PV, so it's not selected by anything later.
1721                         display_lines[1].pv = [];
1722                 }
1723
1724                 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1725                 highlighted_move.addClass('highlight');
1726         }
1727 }
1728
1729 /**
1730  * See if the current displayed line is identical to any of the ones
1731  * we have on screen. (It might not be if e.g. the analysis reloaded
1732  * since we started looking.)
1733  *
1734  * @return {?number}
1735  */
1736 var find_display_line_matching_num = function() {
1737         for (var i = 0; i < display_lines.length; ++i) {
1738                 var line = display_lines[i];
1739                 if (line.start_display_move_num > 0) continue;
1740                 if (current_display_line.start_fen !== line.start_fen) continue;
1741                 if (current_display_line.pv.length !== line.pv.length) continue;
1742                 var ok = true;
1743                 for (var j = 0; j < line.pv.length; ++j) {
1744                         if (current_display_line.pv[j] !== line.pv[j]) {
1745                                 ok = false;
1746                                 break;
1747                         }
1748                 }
1749                 if (ok) {
1750                         return i;
1751                 }
1752         }
1753         return null;
1754 }
1755
1756 /** Update the board based on the currently displayed line.
1757  * 
1758  * TODO: This should really be called only whenever something changes,
1759  * instead of all the time.
1760  */
1761 var update_displayed_line = function() {
1762         if (current_display_line === null) {
1763                 $("#linenav").hide();
1764                 $("#linemsg").show();
1765                 display_fen = base_fen;
1766                 set_board_position(base_fen);
1767                 update_imbalance(base_fen);
1768                 return;
1769         }
1770
1771         $("#linenav").show();
1772         $("#linemsg").hide();
1773
1774         if (current_display_move <= 0) {
1775                 $("#prevmove").html("Previous");
1776         } else {
1777                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1778         }
1779         if (current_display_move == current_display_line.pv.length - 1) {
1780                 $("#nextmove").html("Next");
1781         } else {
1782                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1783         }
1784
1785         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pv, current_display_move);
1786         set_board_position(hiddenboard.fen());
1787         if (display_fen !== hiddenboard.fen() && !current_display_line_is_history) {
1788                 // Fire off a hash request, since we're now off the main position
1789                 // and it just changed.
1790                 explore_hash(hiddenboard.fen());
1791         }
1792         display_fen = hiddenboard.fen();
1793         update_imbalance(hiddenboard.fen());
1794 }
1795
1796 var set_board_position = function(new_fen) {
1797         board_is_animating = true;
1798         var old_fen = board.fen();
1799         board.position(new_fen);
1800         if (board.fen() === old_fen) {
1801                 board_is_animating = false;
1802         }
1803 }
1804
1805 /**
1806  * @param {boolean} param_enable_sound
1807  */
1808 var set_sound = function(param_enable_sound) {
1809         enable_sound = param_enable_sound;
1810         if (enable_sound) {
1811                 $("#soundon").html("<strong>On</strong>");
1812                 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1813
1814                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1815                 // and also preload the file since the user has selected audio.
1816                 var ding = document.getElementById('ding');
1817                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1818                         ding.src = 'ding.opus';
1819                         ding.load();
1820                 }
1821         } else {
1822                 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1823                 $("#soundoff").html("<strong>Off</strong>");
1824         }
1825         if (supports_html5_storage()) {
1826                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1827         }
1828 }
1829 window['set_sound'] = set_sound;
1830
1831 /** Send off a hash probe request to the backend.
1832  * @param {string} fen
1833  */
1834 var explore_hash = function(fen) {
1835         // If we already have a backend response going, abort it.
1836         if (current_hash_xhr) {
1837                 current_hash_xhr.abort();
1838         }
1839         if (current_hash_display_timer) {
1840                 clearTimeout(current_hash_display_timer);
1841                 current_hash_display_timer = null;
1842         }
1843         $("#refutationlines").empty();
1844         current_hash_xhr = $.ajax({
1845                 url: backend_hash_url + "?fen=" + fen
1846         }).done(function(data, textstatus, xhr) {
1847                 show_explore_hash_results(data, fen);
1848         });
1849 }
1850
1851 /** Process the JSON response from a hash probe request.
1852  * @param {!Object} data
1853  * @param {string} fen
1854  */
1855 var show_explore_hash_results = function(data, fen) {
1856         if (board_is_animating) {
1857                 // Updating while the animation is still going causes
1858                 // the animation to jerk. This is pretty crude, but it will do.
1859                 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1860                 return;
1861         }
1862         current_hash_display_timer = null;
1863         hash_refutation_lines = data['lines'];
1864         update_board();
1865 }
1866
1867 // almost all of this stuff comes from the chessboard.js example page
1868 var onDragStart = function(source, piece, position, orientation) {
1869         var pseudogame = new Chess(display_fen);
1870         if (pseudogame.game_over() === true ||
1871             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1872             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1873                 return false;
1874         }
1875
1876         recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1877         if (recommended_move) {
1878                 var squareEl = $('#board .square-' + recommended_move.to);
1879                 squareEl.addClass('highlight1-32417');
1880         }
1881         return true;
1882 }
1883
1884 var mousedownSquare = function(e) {
1885         reverse_dragging_from = null;
1886         var square = $(this).attr('data-square');
1887
1888         var pseudogame = new Chess(display_fen);
1889         if (pseudogame.game_over() === true) {
1890                 return;
1891         }
1892
1893         // If the square is empty, or has a piece of the side not to move,
1894         // we handle it. If not, normal piece dragging will take it.
1895         var position = board.position();
1896         if (!position.hasOwnProperty(square) ||
1897             (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1898             (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1899                 reverse_dragging_from = square;
1900                 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1901                 if (recommended_move) {
1902                         var squareEl = $('#board .square-' + recommended_move.from);
1903                         squareEl.addClass('highlight1-32417');
1904                         squareEl = $('#board .square-' + recommended_move.to);
1905                         squareEl.addClass('highlight1-32417');
1906                 }
1907         }
1908 }
1909
1910 var mouseupSquare = function(e) {
1911         if (reverse_dragging_from === null) {
1912                 return;
1913         }
1914         var source = $(this).attr('data-square');
1915         var target = reverse_dragging_from;
1916         reverse_dragging_from = null;
1917         if (onDrop(source, target) !== 'snapback') {
1918                 onSnapEnd(source, target);
1919         }
1920         $("#board").find('.square-55d63').removeClass('highlight1-32417');
1921 }
1922
1923 var get_best_move = function(game, source, target, invert) {
1924         var moves = game.moves({ verbose: true });
1925         if (source !== null) {
1926                 moves = moves.filter(function(move) { return move.from == source; });
1927         }
1928         if (target !== null) {
1929                 moves = moves.filter(function(move) { return move.to == target; });
1930         }
1931         if (moves.length == 0) {
1932                 return null;
1933         }
1934         if (moves.length == 1) {
1935                 return moves[0];
1936         }
1937
1938         // More than one move. Use the display lines (if we have them)
1939         // to disambiguate; otherwise, we have no information.
1940         var move_hash = {};
1941         for (var i = 0; i < moves.length; ++i) {
1942                 move_hash[moves[i].san] = moves[i];
1943         }
1944
1945         // See if we're already exploring some line.
1946         if (current_display_line &&
1947             current_display_move < current_display_line.pv.length - 1) {
1948                 var first_move = current_display_line.pv[current_display_move + 1];
1949                 if (move_hash[first_move]) {
1950                         return move_hash[first_move];
1951                 }
1952         }
1953
1954         // History and PV take priority over the display lines.
1955         for (var i = 0; i < 2; ++i) {
1956                 var line = display_lines[i];
1957                 var first_move = line.pv[line.start_display_move_num];
1958                 if (move_hash[first_move]) {
1959                         return move_hash[first_move];
1960                 }
1961         }
1962
1963         var best_move = null;
1964         var best_move_score = null;
1965
1966         for (var move in refutation_lines) {
1967                 var line = refutation_lines[move];
1968                 if (!line['score']) {
1969                         continue;
1970                 }
1971                 var first_move = line['pv'][0];
1972                 if (move_hash[first_move]) {
1973                         var score = compute_score_sort_key(line['score'], line['depth'], invert);
1974                         if (best_move_score === null || score > best_move_score) {
1975                                 best_move = move_hash[first_move];
1976                                 best_move_score = score;
1977                         }
1978                 }
1979         }
1980         return best_move;
1981 }
1982
1983 var onDrop = function(source, target) {
1984         if (source === target) {
1985                 if (recommended_move === null) {
1986                         return 'snapback';
1987                 } else {
1988                         // Accept the move. It will be changed in onSnapEnd.
1989                         return;
1990                 }
1991         } else {
1992                 // Suggestion not asked for.
1993                 recommended_move = null;
1994         }
1995
1996         // see if the move is legal
1997         var pseudogame = new Chess(display_fen);
1998         var move = pseudogame.move({
1999                 from: source,
2000                 to: target,
2001                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2002         });
2003
2004         // illegal move
2005         if (move === null) return 'snapback';
2006 }
2007
2008 var onSnapEnd = function(source, target) {
2009         if (source === target && recommended_move !== null) {
2010                 source = recommended_move.from;
2011                 target = recommended_move.to;
2012         }
2013         recommended_move = null;
2014         var pseudogame = new Chess(display_fen);
2015         var move = pseudogame.move({
2016                 from: source,
2017                 to: target,
2018                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
2019         });
2020
2021         if (current_display_line &&
2022             current_display_move < current_display_line.pv.length - 1 &&
2023             current_display_line.pv[current_display_move + 1] === move.san) {
2024                 next_move();
2025                 return;
2026         }
2027
2028         // Walk down the displayed lines until we find one that starts with
2029         // this move, then select that. Note that this gives us a good priority
2030         // order (history first, then PV, then multi-PV lines).
2031         for (var i = 0; i < display_lines.length; ++i) {
2032                 if (i == 1 && current_display_line) {
2033                         // Do not choose PV if not on it.
2034                         continue;
2035                 }
2036                 var line = display_lines[i];
2037                 if (line.pv[line.start_display_move_num] === move.san) {
2038                         show_line(i, 0);
2039                         return;
2040                 }
2041         }
2042
2043         // Shouldn't really be here if we have hash probes, but there's really
2044         // nothing we can do.
2045 }
2046 // End of dragging-related code.
2047
2048 var fmt_cp = function(v) {
2049         if (v === 0) {
2050                 return "0.00";
2051         } else if (v > 0) {
2052                 return "+" + (v / 100).toFixed(2);
2053         } else {
2054                 v = -v;
2055                 return "-" + (v / 100).toFixed(2);
2056         }
2057 }
2058
2059 var format_short_score = function(score) {
2060         if (!score) {
2061                 return "???";
2062         }
2063         if (score[0] === 'm') {
2064                 if (score[2]) {  // Is a bound.
2065                         return score[2] + "\u00a0M " + score[1];
2066                 } else {
2067                         return "M " + score[1];
2068                 }
2069         } else if (score[0] === 'd') {
2070                 return "TB draw";
2071         } else if (score[0] === 'cp') {
2072                 if (score[2]) {  // Is a bound.
2073                         return score[2] + "\u00a0" + fmt_cp(score[1]);
2074                 } else {
2075                         return fmt_cp(score[1]);
2076                 }
2077         }
2078         return null;
2079 }
2080
2081 var format_long_score = function(score) {
2082         if (!score) {
2083                 return "???";
2084         }
2085         if (score[0] === 'm') {
2086                 if (score[1] > 0) {
2087                         return "White mates in " + score[1];
2088                 } else {
2089                         return "Black mates in " + (-score[1]);
2090                 }
2091         } else if (score[0] === 'd') {
2092                 return "Theoretical draw";
2093         } else if (score[0] === 'cp') {
2094                 return "Score: " + format_short_score(score);
2095         }
2096         return null;
2097 }
2098
2099 var compute_plot_score = function(score) {
2100         if (score[0] === 'm') {
2101                 if (score[1] > 0) {
2102                         return 500;
2103                 } else {
2104                         return -500;
2105                 }
2106         } else if (score[0] === 'd') {
2107                 return 0;
2108         } else if (score[0] === 'cp') {
2109                 if (score[1] > 500) {
2110                         return 500;
2111                 } else if (score[1] < -500) {
2112                         return -500;
2113                 } else {
2114                         return score[1];
2115                 }
2116         }
2117         return null;
2118 }
2119
2120 /**
2121  * @param score The score digest tuple.
2122  * @param {?number} depth Depth the move has been computed to, or null.
2123  * @param {boolean} invert Whether black is to play.
2124  * @param {boolean=} depth_secondary_key
2125  * @return {number}
2126  */
2127 var compute_score_sort_key = function(score, depth, invert, depth_secondary_key) {
2128         var s;
2129         if (!score) {
2130                 return -10000000;
2131         }
2132         if (score[0] === 'm') {
2133                 if (score[1] > 0) {
2134                         // White mates.
2135                         s = 99999 - score[1];
2136                 } else {
2137                         // Black mates (note the double negative for score[1]).
2138                         s = -99999 - score[1];
2139                 }
2140         } else if (score[0] === 'd') {
2141                 s = 0;
2142         } else if (score[0] === 'cp') {
2143                 s = score[1];
2144         }
2145         if (s) {
2146                 if (invert) s = -s;
2147                 if (depth_secondary_key) {
2148                         return s * 200 + (depth || 0);
2149                 } else {
2150                         return s;
2151                 }
2152         } else {
2153                 return null;
2154         }
2155 }
2156
2157 /**
2158  * @param {Object} game
2159  */
2160 var switch_backend = function(game) {
2161         // Stop looking at historic data.
2162         current_display_line = null;
2163         current_display_move = null;
2164         displayed_analysis_data = null;
2165         if (current_historic_xhr) {
2166                 current_historic_xhr.abort();
2167         }
2168
2169         // If we already have a backend response going, abort it.
2170         if (current_analysis_xhr) {
2171                 current_analysis_xhr.abort();
2172         }
2173         if (current_hash_xhr) {
2174                 current_hash_xhr.abort();
2175         }
2176
2177         // Otherwise, we should have a timer going to start a new one.
2178         // Kill that, too.
2179         if (current_analysis_request_timer) {
2180                 clearTimeout(current_analysis_request_timer);
2181                 current_analysis_request_timer = null;
2182         }
2183         if (current_hash_display_timer) {
2184                 clearTimeout(current_hash_display_timer);
2185                 current_hash_display_timer = null;
2186         }
2187
2188         // Request an immediate fetch with the new backend.
2189         backend_url = game['url'];
2190         backend_hash_url = game['hashurl'];
2191         window.location.hash = '#' + game['id'];
2192         current_analysis_data = null;
2193         ims = 0;
2194         request_update();
2195 }
2196 window['switch_backend'] = switch_backend;
2197
2198 window['flip'] = function() { board.flip(); redraw_arrows(); };
2199
2200 var init = function() {
2201         unique = get_unique();
2202
2203         // Load settings from HTML5 local storage if available.
2204         if (supports_html5_storage() && localStorage['enable_sound']) {
2205                 set_sound(parseInt(localStorage['enable_sound']));
2206         } else {
2207                 set_sound(false);
2208         }
2209
2210         // Create board.
2211         board = new window.ChessBoard('board', {
2212                 onMoveEnd: function() { board_is_animating = false; },
2213
2214                 draggable: true,
2215                 onDragStart: onDragStart,
2216                 onDrop: onDrop,
2217                 onSnapEnd: onSnapEnd
2218         });
2219         $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2220         $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2221
2222         request_update();
2223         $(window).resize(function() {
2224                 board.resize();
2225                 update_sparkline(displayed_analysis_data || current_analysis_data);
2226                 update_board_highlight();
2227                 redraw_arrows();
2228         });
2229         $(window).keyup(function(event) {
2230                 if (event.which == 39) {  // Left arrow.
2231                         next_move();
2232                 } else if (event.which == 37) {  // Right arrow.
2233                         prev_move();
2234                 } else if (event.which >= 49 && event.which <= 57) {  // 1-9.
2235                         var num = event.which - 49;
2236                         if (current_games && current_games.length >= num) {
2237                                 switch_backend(current_games[num]);
2238                         }
2239                 } else if (event.which == 78) {  // N.
2240                         next_game();
2241                 }
2242         });
2243         window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2244 };
2245 $(document).ready(init);
2246
2247 })();