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