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