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