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