]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
Add a temporary safeguard.
[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                 $(depth_td).text("d" + line['depth']);
826
827                 var pv_td = document.createElement("td");
828                 tr.appendChild(pv_td);
829                 $(pv_td).addClass("pv");
830                 $(pv_td).html(add_pv(base_fen, base_line.concat(line['pv_pretty']), move_num, toplay, line['score'], start_display_move_num, 10));
831
832                 tbl.append(tr);
833         }
834
835         // Make one of the links clickable and the other nonclickable.
836         if (sort_refutation_lines_by_score) {
837                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
838                 $("#sortbyscore1").html("<strong>Score</strong>");
839         } else {
840                 $("#sortbyscore0").html("<strong>Move</strong>");
841                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
842         }
843
844         // Update the move highlight, as we've rewritten all the HTML.
845         update_move_highlight();
846 }
847
848 /**
849  * Create a Chess.js board object, containing the given position plus the given moves,
850  * up to the given limit.
851  *
852  * @param {?string} fen
853  * @param {Array.<string>} moves
854  * @param {number} last_move
855  */
856 var chess_from = function(fen, moves, last_move) {
857         var hiddenboard = new Chess();
858         if (fen !== null) {
859                 hiddenboard.load(fen);
860         }
861         for (var i = 0; i <= last_move; ++i) {
862                 if (moves[i] === '0-0') {
863                         hiddenboard.move('O-O');
864                 } else if (moves[i] === '0-0-0') {
865                         hiddenboard.move('O-O-O');
866                 } else {
867                         hiddenboard.move(moves[i]);
868                 }
869         }
870         return hiddenboard;
871 }
872
873 var update_game_list = function(games) {
874         $("#games").text("");
875         if (games === null) {
876                 return;
877         }
878
879         var games_div = document.getElementById('games');
880         for (var game_num = 0; game_num < games.length; ++game_num) {
881                 var game = games[game_num];
882                 var game_span = document.createElement("span");
883                 game_span.setAttribute("class", "game");
884
885                 var game_name = document.createTextNode(game['name']);
886                 if (game['url'] === backend_url) {
887                         game_span.appendChild(game_name);
888                 } else {
889                         var game_a = document.createElement("a");
890                         game_a.setAttribute("href", "#" + game['id']);
891                         game_a.appendChild(game_name);
892                         game_span.appendChild(game_a);
893                 }
894                 games_div.appendChild(game_span);
895         }
896 }
897
898 /**
899  * Try to find a running game that matches with the current hash,
900  * and switch to it if we're not already displaying it.
901  */
902 var possibly_switch_game_from_hash = function() {
903         if (current_games === null) {
904                 return;
905         }
906
907         var hash = window.location.hash.replace(/^#/,'');
908         for (var i = 0; i < current_games.length; ++i) {
909                 if (current_games[i]['id'] === hash) {
910                         if (backend_url !== current_games[i]['url']) {
911                                 switch_backend(current_games[i]['url']);
912                         }
913                         return;
914                 }
915         }
916 }
917
918 /** Update all the HTML on the page, based on current global state.
919  */
920 var update_board = function() {
921         var data = displayed_analysis_data || current_analysis_data;
922         var current_data = current_analysis_data;  // Convenience alias.
923
924         display_lines = [];
925
926         // Print the history. This is pretty much the only thing that's
927         // unconditionally taken from current_data (we're not interested in
928         // historic history).
929         if (current_data['position']['pretty_history']) {
930                 add_pv('start', current_data['position']['pretty_history'], 1, 'W', null, 0, 8, true);
931         } else {
932                 display_lines.push(null);
933         }
934         update_history();
935
936         // Games currently in progress, if any.
937         if (current_data['games']) {
938                 current_games = current_data['games'];
939                 possibly_switch_game_from_hash();
940                 update_game_list(current_data['games']);
941         } else {
942                 current_games = null;
943                 update_game_list(null);
944         }
945
946         // The headline. Names are always fetched from current_data;
947         // the rest can depend a bit.
948         var headline;
949         if (current_data &&
950             current_data['position']['player_w'] && current_data['position']['player_b']) {
951                 headline = current_data['position']['player_w'] + '–' +
952                         current_data['position']['player_b'] + ', analysis';
953         } else {
954                 headline = 'Analysis';
955         }
956
957         // Credits, where applicable. Note that we don't want the footer to change a lot
958         // when e.g. viewing history, so if any of these changed during the game,
959         // use the current one still.
960         if (current_data['using_lomonosov']) {
961                 $("#lomonosov").show();
962         } else {
963                 $("#lomonosov").hide();
964         }
965
966         // Credits: The engine name/version.
967         if (current_data['engine'] && current_data['engine']['name'] !== null) {
968                 $("#engineid").text(current_data['engine']['name']);
969         }
970
971         // Credits: The engine URL.
972         if (current_data['engine'] && current_data['engine']['url']) {
973                 $("#engineid").attr("href", current_data['engine']['url']);
974         } else {
975                 $("#engineid").removeAttr("href");
976         }
977
978         // Credits: Engine details.
979         if (current_data['engine'] && current_data['engine']['details']) {
980                 $("#enginedetails").text(" (" + current_data['engine']['details'] + ")");
981         } else {
982                 $("#enginedetails").text("");
983         }
984
985         // Credits: Move source, possibly with URL.
986         if (current_data['move_source'] && current_data['move_source_url']) {
987                 $("#movesource").text("Moves provided by ");
988                 var movesource_a = document.createElement("a");
989                 movesource_a.setAttribute("href", current_data['move_source_url']);
990                 var movesource_text = document.createTextNode(current_data['move_source']);
991                 movesource_a.appendChild(movesource_text);
992                 var movesource_period = document.createTextNode(".");
993                 document.getElementById("movesource").appendChild(movesource_a);
994                 document.getElementById("movesource").appendChild(movesource_period);
995         } else if (current_data['move_source']) {
996                 $("#movesource").text("Moves provided by " + current_data['move_source'] + ".");
997         } else {
998                 $("#movesource").text("");
999         }
1000
1001         var last_move;
1002         if (displayed_analysis_data) {
1003                 // Displaying some non-current position, pick out the last move
1004                 // from the history. This will work even if the fetch failed.
1005                 last_move = format_halfmove_with_number(
1006                         current_display_line.pretty_pv[current_display_move],
1007                         current_display_move + 1);
1008                 headline += ' after ' + last_move;
1009         } else if (data['position']['last_move'] !== 'none') {
1010                 last_move = format_move_with_number(
1011                         data['position']['last_move'],
1012                         data['position']['move_num'],
1013                         data['position']['toplay'] == 'W');
1014                 headline += ' after ' + last_move;
1015         } else {
1016                 last_move = null;
1017         }
1018         $("#headline").text(headline);
1019
1020         // The <title> contains a very brief headline.
1021         var title_elems = [];
1022         if (data['score']) {
1023                 title_elems.push(format_short_score(data['score']).replace(/^ /, ""));
1024         }
1025         if (last_move !== null) {
1026                 title_elems.push(last_move);
1027         }
1028
1029         if (title_elems.length != 0) {
1030                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
1031         } else {
1032                 document.title = 'analysis.sesse.net';
1033         }
1034
1035         // The last move (shown by highlighting the from and to squares).
1036         if (data['position'] && data['position']['last_move_uci']) {
1037                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
1038                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
1039         } else if (current_display_line_is_history && current_display_move >= 0) {
1040                 // We don't have historic analysis for this position, but we
1041                 // can reconstruct what the last move was by just replaying
1042                 // from the start.
1043                 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1044                 var moves = hiddenboard.history({ verbose: true });
1045                 var last_move = moves.pop();
1046                 highlight_from = last_move.from;
1047                 highlight_to = last_move.to;
1048         } else {
1049                 highlight_from = highlight_to = undefined;
1050         }
1051         update_board_highlight();
1052
1053         if (data['failed']) {
1054                 $("#score").text("No analysis for this move");
1055                 $("#pvtitle").text("PV:");
1056                 $("#pv").empty();
1057                 $("#searchstats").html("&nbsp;");
1058                 $("#refutationlines").empty();
1059                 $("#whiteclock").empty();
1060                 $("#blackclock").empty();
1061                 refutation_lines = [];
1062                 update_refutation_lines();
1063                 clear_arrows();
1064                 update_displayed_line();
1065                 update_move_highlight();
1066                 return;
1067         }
1068
1069         update_clock();
1070
1071         // The score.
1072         if (current_display_line) {
1073                 if (current_display_line.score) {
1074                         $("#score").text(format_long_score(current_display_line.score));
1075                 } else {
1076                         $("#score").text("No score for this move");
1077                 }
1078         } else if (data['score']) {
1079                 $("#score").text(format_long_score(data['score']));
1080         }
1081
1082         // The search stats.
1083         if (data['searchstats']) {
1084                 $("#searchstats").html(data['searchstats']);
1085         } else if (data['tablebase'] == 1) {
1086                 $("#searchstats").text("Tablebase result");
1087         } else if (data['nodes'] && data['nps'] && data['depth']) {
1088                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
1089                 if (data['seldepth']) {
1090                         stats += ' (' + data['seldepth'] + ' selective)';
1091                 }
1092                 if (data['tbhits'] && data['tbhits'] > 0) {
1093                         if (data['tbhits'] == 1) {
1094                                 stats += ', one Syzygy hit';
1095                         } else {
1096                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
1097                         }
1098                 }
1099
1100                 $("#searchstats").text(stats);
1101         } else {
1102                 $("#searchstats").text("");
1103         }
1104
1105         // Update the board itself.
1106         base_fen = data['position']['fen'];
1107         update_displayed_line();
1108
1109         // Print the PV.
1110         $("#pvtitle").text("PV:");
1111         $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay'], data['score'], 0));
1112
1113         // Update the PV arrow.
1114         clear_arrows();
1115         if (data['pv_uci'].length >= 1) {
1116                 // draw a continuation arrow as long as it's the same piece
1117                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
1118                         var from = data['pv_uci'][i].substr(0, 2);
1119                         var to = data['pv_uci'][i].substr(2,4);
1120                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
1121                              interfering_arrow(from, to)) {
1122                                 break;
1123                         }
1124                         create_arrow(from, to, '#f66', 6, 20);
1125                 }
1126
1127                 var alt_moves = find_nonstupid_moves(data, 30, data['position']['toplay'] === 'B');
1128                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
1129                         create_arrow(alt_moves[i].substr(0, 2),
1130                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
1131                 }
1132         }
1133
1134         // See if all semi-reasonable moves have only one possible response.
1135         if (data['pv_uci'].length >= 2) {
1136                 var nonstupid_moves = find_nonstupid_moves(data, 300, data['position']['toplay'] === 'B');
1137                 var response = data['pv_uci'][1];
1138                 for (var i = 0; i < nonstupid_moves.length; ++i) {
1139                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
1140                                 // ignore the PV move for refutation lines.
1141                                 continue;
1142                         }
1143                         if (!data['refutation_lines'] ||
1144                             !data['refutation_lines'][nonstupid_moves[i]] ||
1145                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
1146                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
1147                                 // Incomplete PV, abort.
1148                                 response = undefined;
1149                                 break;
1150                         }
1151                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
1152                         if (response !== this_response) {
1153                                 // Different response depending on lines, abort.
1154                                 response = undefined;
1155                                 break;
1156                         }
1157                 }
1158
1159                 if (nonstupid_moves.length > 0 && response !== undefined) {
1160                         create_arrow(response.substr(0, 2),
1161                                      response.substr(2, 2), '#66f', 6, 20);
1162                 }
1163         }
1164
1165         // Update the refutation lines.
1166         base_fen = data['position']['fen'];
1167         move_num = parseInt(data['position']['move_num']);
1168         toplay = data['position']['toplay'];
1169         refutation_lines = hash_refutation_lines || data['refutation_lines'];
1170         update_refutation_lines();
1171
1172         // Update the sparkline last, since its size depends on how everything else reflowed.
1173         update_sparkline(data);
1174 }
1175
1176 var update_sparkline = function(data) {
1177         if (data && data['score_history']) {
1178                 var first_move_num = undefined;
1179                 for (var halfmove_num in data['score_history']) {
1180                         halfmove_num = parseInt(halfmove_num);
1181                         if (first_move_num === undefined || halfmove_num < first_move_num) {
1182                                 first_move_num = halfmove_num;
1183                         }
1184                 }
1185                 if (first_move_num !== undefined) {
1186                         var last_move_num = data['position']['move_num'] * 2 - 3;
1187                         if (data['position']['toplay'] === 'B') {
1188                                 ++last_move_num;
1189                         }
1190
1191                         // Possibly truncate some moves if we don't have enough width.
1192                         // FIXME: Sometimes width() for #scorecontainer (and by extent,
1193                         // #scoresparkcontainer) on Chrome for mobile seems to start off
1194                         // at something very small, and then suddenly snap back into place.
1195                         // Figure out why.
1196                         var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
1197                         if (last_move_num - first_move_num > max_moves) {
1198                                 first_move_num = last_move_num - max_moves;
1199                         }
1200
1201                         var min_score = -100;
1202                         var max_score = 100;
1203                         var last_score = null;
1204                         var scores = [];
1205                         for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
1206                                 if (data['score_history'][halfmove_num]) {
1207                                         var score = compute_plot_score(data['score_history'][halfmove_num]);
1208                                         last_score = score;
1209                                         if (score < min_score) min_score = score;
1210                                         if (score > max_score) max_score = score;
1211                                 }
1212                                 scores.push(last_score);
1213                         }
1214                         if (data['score']) {
1215                                 scores.push(compute_plot_score(data['score']));
1216                         }
1217                         // FIXME: at some widths, calling sparkline() seems to push
1218                         // #scorecontainer under the board.
1219                         $("#scorespark").sparkline(scores, {
1220                                 type: 'bar',
1221                                 zeroColor: 'gray',
1222                                 chartRangeMin: min_score,
1223                                 chartRangeMax: max_score,
1224                                 tooltipFormatter: function(sparkline, options, fields) {
1225                                         return format_tooltip(data, fields[0].offset + first_move_num);
1226                                 }
1227                         });
1228                 } else {
1229                         $("#scorespark").text("");
1230                 }
1231         } else {
1232                 $("#scorespark").text("");
1233         }
1234 }
1235
1236 /**
1237  * @param {number} num_viewers
1238  */
1239 var update_num_viewers = function(num_viewers) {
1240         if (num_viewers === null) {
1241                 $("#numviewers").text("");
1242         } else if (num_viewers == 1) {
1243                 $("#numviewers").text("You are the only current viewer");
1244         } else {
1245                 $("#numviewers").text(num_viewers + " current viewers");
1246         }
1247 }
1248
1249 var update_clock = function() {
1250         clearTimeout(clock_timer);
1251
1252         var data = displayed_analysis_data || current_analysis_data;
1253         if (data['position']) {
1254                 var result = data['position']['result'];
1255                 if (result === '1-0') {
1256                         $("#whiteclock").text("1");
1257                         $("#blackclock").text("0");
1258                         $("#whiteclock").removeClass("running-clock");
1259                         $("#blackclock").removeClass("running-clock");
1260                         return;
1261                 }
1262                 if (result === '1/2-1/2') {
1263                         $("#whiteclock").text("1/2");
1264                         $("#blackclock").text("1/2");
1265                         $("#whiteclock").removeClass("running-clock");
1266                         $("#blackclock").removeClass("running-clock");
1267                         return;
1268                 }       
1269                 if (result === '0-1') {
1270                         $("#whiteclock").text("0");
1271                         $("#blackclock").text("1");
1272                         $("#whiteclock").removeClass("running-clock");
1273                         $("#blackclock").removeClass("running-clock");
1274                         return;
1275                 }
1276         }
1277
1278         var white_clock_ms = null;
1279         var black_clock_ms = null;
1280         var show_seconds = false;
1281
1282         // Static clocks.
1283         if (data['position'] &&
1284             data['position']['white_clock'] &&
1285             data['position']['black_clock']) {
1286                 white_clock_ms = data['position']['white_clock'] * 1000;
1287                 black_clock_ms = data['position']['black_clock'] * 1000;
1288         }
1289
1290         // Dynamic clock (only one, obviously).
1291         var color;
1292         if (data['position']['white_clock_target']) {
1293                 color = "white";
1294                 $("#whiteclock").addClass("running-clock");
1295                 $("#blackclock").removeClass("running-clock");
1296         } else if (data['position']['black_clock_target']) {
1297                 color = "black";
1298                 $("#whiteclock").removeClass("running-clock");
1299                 $("#blackclock").addClass("running-clock");
1300         } else {
1301                 $("#whiteclock").removeClass("running-clock");
1302                 $("#blackclock").removeClass("running-clock");
1303         }
1304         var remaining_ms;
1305         if (color) {
1306                 var now = new Date().getTime() + client_clock_offset_ms;
1307                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
1308                 if (color === "white") {
1309                         white_clock_ms = remaining_ms;
1310                 } else {
1311                         black_clock_ms = remaining_ms;
1312                 }
1313         }
1314
1315         if (white_clock_ms === null || black_clock_ms === null) {
1316                 $("#whiteclock").empty();
1317                 $("#blackclock").empty();
1318                 return;
1319         }
1320
1321         // If either player has ten minutes or less left, add the second counters.
1322         var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1323
1324         if (color) {
1325                 // See when the clock will change next, and update right after that.
1326                 var next_update_ms;
1327                 if (show_seconds) {
1328                         next_update_ms = remaining_ms % 1000 + 100;
1329                 } else {
1330                         next_update_ms = remaining_ms % 60000 + 100;
1331                 }
1332                 clock_timer = setTimeout(update_clock, next_update_ms);
1333         }
1334
1335         $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1336         $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1337 }
1338
1339 /**
1340  * @param {Number} remaining_ms
1341  * @param {boolean} show_seconds
1342  */
1343 var format_clock = function(remaining_ms, show_seconds) {
1344         if (remaining_ms <= 0) {
1345                 if (show_seconds) {
1346                         return "00:00:00";
1347                 } else {
1348                         return "00:00";
1349                 }
1350         }
1351
1352         var remaining = Math.floor(remaining_ms / 1000);
1353         var seconds = remaining % 60;
1354         remaining = (remaining - seconds) / 60;
1355         var minutes = remaining % 60;
1356         remaining = (remaining - minutes) / 60;
1357         var hours = remaining;
1358         if (show_seconds) {
1359                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1360         } else {
1361                 return format_2d(hours) + ":" + format_2d(minutes);
1362         }
1363 }
1364
1365 /**
1366  * @param {Number} x
1367  */
1368 var format_2d = function(x) {
1369         if (x >= 10) {
1370                 return x;
1371         } else {
1372                 return "0" + x;
1373         }
1374 }
1375
1376 /**
1377  * @param {string} move
1378  * @param {Number} move_num
1379  * @param {boolean} white_to_play
1380  */
1381 var format_move_with_number = function(move, move_num, white_to_play) {
1382         var ret;
1383         if (white_to_play) {
1384                 ret = (move_num - 1) + '… ';
1385         } else {
1386                 ret = move_num + '. ';
1387         }
1388         ret += move;
1389         return ret;
1390 }
1391
1392 /**
1393  * @param {string} move
1394  * @param {Number} halfmove_num
1395  */
1396 var format_halfmove_with_number = function(move, halfmove_num) {
1397         return format_move_with_number(
1398                 move,
1399                 Math.floor(halfmove_num / 2) + 1,
1400                 halfmove_num % 2 == 0);
1401 }
1402
1403 /**
1404  * @param {Object} data
1405  * @param {Number} halfmove_num
1406  */
1407 var format_tooltip = function(data, halfmove_num) {
1408         if (data['score_history'][halfmove_num] ||
1409             halfmove_num === data['position']['pretty_history'].length) {
1410                 var move;
1411                 var short_score;
1412                 if (halfmove_num === data['position']['pretty_history'].length) {
1413                         move = data['position']['last_move'];
1414                         short_score = format_short_score(data['score']);
1415                 } else {
1416                         move = data['position']['pretty_history'][halfmove_num];
1417                         short_score = format_short_score(data['score_history'][halfmove_num]);
1418                 }
1419                 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1420
1421                 return "After " + move_with_number + ": " + short_score;
1422         } else {
1423                 for (var i = halfmove_num; i --> 0; ) {
1424                         if (data['score_history'][i]) {
1425                                 var move = data['position']['pretty_history'][i];
1426                                 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1427                         }
1428                 }
1429         }
1430 }
1431
1432 /**
1433  * @param {boolean} sort_by_score
1434  */
1435 var resort_refutation_lines = function(sort_by_score) {
1436         sort_refutation_lines_by_score = sort_by_score;
1437         if (supports_html5_storage()) {
1438                 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1439         }
1440         update_refutation_lines();
1441 }
1442 window['resort_refutation_lines'] = resort_refutation_lines;
1443
1444 /**
1445  * @param {boolean} truncate_history
1446  */
1447 var set_truncate_history = function(truncate_history) {
1448         truncate_display_history = truncate_history;
1449         update_refutation_lines();
1450 }
1451 window['set_truncate_history'] = set_truncate_history;
1452
1453 /**
1454  * @param {number} line_num
1455  * @param {number} move_num
1456  */
1457 var show_line = function(line_num, move_num) {
1458         if (line_num == -1) {
1459                 current_display_line = null;
1460                 current_display_move = null;
1461                 hash_refutation_lines = null;
1462                 if (displayed_analysis_data) {
1463                         // TODO: Support exiting to history position if we are in an
1464                         // analysis line of a history position.
1465                         displayed_analysis_data = null;
1466                 }
1467                 update_board();
1468                 return;
1469         } else {
1470                 current_display_line = jQuery.extend({}, display_lines[line_num]);  // Shallow clone.
1471                 current_display_move = move_num + current_display_line.start_display_move_num;
1472         }
1473         current_display_line_is_history = (line_num == 0);
1474
1475         update_historic_analysis();
1476         update_displayed_line();
1477         update_board_highlight();
1478         update_move_highlight();
1479         redraw_arrows();
1480 }
1481 window['show_line'] = show_line;
1482
1483 var prev_move = function() {
1484         if (current_display_line &&
1485             current_display_move >= current_display_line.start_display_move_num) {
1486                 --current_display_move;
1487         }
1488         update_historic_analysis();
1489         update_displayed_line();
1490         update_move_highlight();
1491 }
1492 window['prev_move'] = prev_move;
1493
1494 var next_move = function() {
1495         if (current_display_line &&
1496             current_display_move < current_display_line.pretty_pv.length - 1) {
1497                 ++current_display_move;
1498         }
1499         update_historic_analysis();
1500         update_displayed_line();
1501         update_move_highlight();
1502 }
1503 window['next_move'] = next_move;
1504
1505 var update_historic_analysis = function() {
1506         if (!current_display_line_is_history) {
1507                 return;
1508         }
1509         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1510                 displayed_analysis_data = null;
1511                 update_board();
1512         }
1513
1514         // Fetch old analysis for this line if it exists.
1515         var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1516         var filename = "/history/move" + (current_display_move + 1) + "-" +
1517                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1518
1519         current_historic_xhr = $.ajax({
1520                 url: filename
1521         }).done(function(data, textstatus, xhr) {
1522                 displayed_analysis_data = data;
1523                 update_board();
1524         }).fail(function(jqXHR, textStatus, errorThrown) {
1525                 if (textStatus === "abort") {
1526                         // Aborted because we are switching backends. Don't do anything;
1527                         // we will already have been cleared.
1528                 } else {
1529                         displayed_analysis_data = {'failed': true};
1530                         update_board();
1531                 }
1532         });
1533 }
1534
1535 /**
1536  * @param {string} fen
1537  */
1538 var update_imbalance = function(fen) {
1539         var hiddenboard = new Chess(fen);
1540         var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1541         for (var row = 0; row < 8; ++row) {
1542                 for (var col = 0; col < 8; ++col) {
1543                         var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1544                         var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1545                         var square = col_text + row_text;
1546                         var contents = hiddenboard.get(square);
1547                         if (contents !== null) {
1548                                 if (contents.color === 'w') {
1549                                         ++imbalance[contents.type];
1550                                 } else {
1551                                         --imbalance[contents.type];
1552                                 }
1553                         }
1554                 }
1555         }
1556         var white_imbalance = '';
1557         var black_imbalance = '';
1558         for (var piece in imbalance) {
1559                 for (var i = 0; i < imbalance[piece]; ++i) {
1560                         white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1561                 }
1562                 for (var i = 0; i < -imbalance[piece]; ++i) {
1563                         black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1564                 }
1565         }
1566         $('#whiteimbalance').html(white_imbalance);
1567         $('#blackimbalance').html(black_imbalance);
1568 }
1569
1570 /** Mark the currently selected move in red.
1571  * Also replaces the PV with the current displayed line if it's not shown
1572  * anywhere else on the screen.
1573  */
1574 var update_move_highlight = function() {
1575         if (highlighted_move !== null) {
1576                 highlighted_move.removeClass('highlight'); 
1577         }
1578         if (current_display_line) {
1579                 var display_line_num = find_display_line_matching_num();
1580                 if (display_line_num === null) {
1581                         // Replace the PV with the (complete) line.
1582                         $("#pvtitle").text("Exploring:");
1583                         current_display_line.start_display_move_num = 0;
1584                         display_lines.push(current_display_line);
1585                         $("#pv").html(print_pv(display_lines.length - 1));
1586                         display_line_num = display_lines.length - 1;
1587                 }
1588
1589                 highlighted_move = $("#automove" + display_line_num + "-" + (current_display_move - current_display_line.start_display_move_num));
1590                 highlighted_move.addClass('highlight');
1591         }
1592 }
1593
1594 /**
1595  * See if the current displayed line is identical to any of the ones
1596  * we have on screen. (It might not be if e.g. the analysis reloaded
1597  * since we started looking.)
1598  *
1599  * @return {?number}
1600  */
1601 var find_display_line_matching_num = function() {
1602         for (var i = 0; i < display_lines.length; ++i) {
1603                 var line = display_lines[i];
1604                 if (line.start_display_move_num > 0) continue;
1605                 if (current_display_line.start_fen !== line.start_fen) continue;
1606                 if (current_display_line.pretty_pv.length !== line.pretty_pv.length) continue;
1607                 var ok = true;
1608                 for (var j = 0; j < line.pretty_pv.length; ++j) {
1609                         if (current_display_line.pretty_pv[j] !== line.pretty_pv[j]) {
1610                                 ok = false;
1611                                 break;
1612                         }
1613                 }
1614                 if (ok) {
1615                         return i;
1616                 }
1617         }
1618         return null;
1619 }
1620
1621 var update_displayed_line = function() {
1622         if (current_display_line === null) {
1623                 $("#linenav").hide();
1624                 $("#linemsg").show();
1625                 display_fen = base_fen;
1626                 board.position(base_fen);
1627                 update_imbalance(base_fen);
1628                 return;
1629         }
1630
1631         $("#linenav").show();
1632         $("#linemsg").hide();
1633
1634         if (current_display_move <= 0) {
1635                 $("#prevmove").html("Previous");
1636         } else {
1637                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1638         }
1639         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1640                 $("#nextmove").html("Next");
1641         } else {
1642                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1643         }
1644
1645         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1646         display_fen = hiddenboard.fen();
1647         board_is_animating = true;
1648         var old_fen = board.fen();
1649         board.position(hiddenboard.fen());
1650         if (board.fen() === old_fen) {
1651                 board_is_animating = false;
1652         } else if (!current_display_line_is_history) {
1653                 // Fire off a hash request, since we're now off the main position
1654                 // and it just changed.
1655                 explore_hash(display_fen);
1656         }
1657         update_imbalance(hiddenboard.fen());
1658 }
1659
1660 /**
1661  * @param {boolean} param_enable_sound
1662  */
1663 var set_sound = function(param_enable_sound) {
1664         enable_sound = param_enable_sound;
1665         if (enable_sound) {
1666                 $("#soundon").html("<strong>On</strong>");
1667                 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1668
1669                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1670                 // and also preload the file since the user has selected audio.
1671                 var ding = document.getElementById('ding');
1672                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1673                         ding.src = 'ding.opus';
1674                         ding.load();
1675                 }
1676         } else {
1677                 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1678                 $("#soundoff").html("<strong>Off</strong>");
1679         }
1680         if (supports_html5_storage()) {
1681                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1682         }
1683 }
1684 window['set_sound'] = set_sound;
1685
1686 /** Send off a hash probe request to the backend.
1687  * @param {string} fen
1688  */
1689 var explore_hash = function(fen) {
1690         // If we already have a backend response going, abort it.
1691         if (current_hash_xhr) {
1692                 current_hash_xhr.abort();
1693         }
1694         if (current_hash_display_timer) {
1695                 clearTimeout(current_hash_display_timer);
1696                 current_hash_display_timer = null;
1697         }
1698         $("#refutationlines").empty();
1699         current_hash_xhr = $.ajax({
1700                 url: backend_hash_url + "?fen=" + fen
1701         }).done(function(data, textstatus, xhr) {
1702                 show_explore_hash_results(data, fen);
1703         });
1704 }
1705
1706 /** Process the JSON response from a hash probe request.
1707  * @param {!Object} data
1708  * @param {string} fen
1709  */
1710 var show_explore_hash_results = function(data, fen) {
1711         if (board_is_animating) {
1712                 // Updating while the animation is still going causes
1713                 // the animation to jerk. This is pretty crude, but it will do.
1714                 current_hash_display_timer = setTimeout(function() { show_explore_hash_results(data, fen); }, 100);
1715                 return;
1716         }
1717         current_hash_display_timer = null;
1718         hash_refutation_lines = data['lines'];
1719         update_board();
1720 }
1721
1722 // almost all of this stuff comes from the chessboard.js example page
1723 var onDragStart = function(source, piece, position, orientation) {
1724         var pseudogame = new Chess(display_fen);
1725         if (pseudogame.game_over() === true ||
1726             (pseudogame.turn() === 'w' && piece.search(/^b/) !== -1) ||
1727             (pseudogame.turn() === 'b' && piece.search(/^w/) !== -1)) {
1728                 return false;
1729         }
1730
1731         recommended_move = get_best_move(pseudogame, source, null, pseudogame.turn() === 'b');
1732         if (recommended_move) {
1733                 var squareEl = $('#board .square-' + recommended_move.to);
1734                 squareEl.addClass('highlight1-32417');
1735         }
1736         return true;
1737 }
1738
1739 var mousedownSquare = function(e) {
1740         reverse_dragging_from = null;
1741         var square = $(this).attr('data-square');
1742
1743         var pseudogame = new Chess(display_fen);
1744         if (pseudogame.game_over() === true) {
1745                 return;
1746         }
1747
1748         // If the square is empty, or has a piece of the side not to move,
1749         // we handle it. If not, normal piece dragging will take it.
1750         var position = board.position();
1751         if (!position.hasOwnProperty(square) ||
1752             (pseudogame.turn() === 'w' && position[square].search(/^b/) !== -1) ||
1753             (pseudogame.turn() === 'b' && position[square].search(/^w/) !== -1)) {
1754                 reverse_dragging_from = square;
1755                 recommended_move = get_best_move(pseudogame, null, square, pseudogame.turn() === 'b');
1756                 if (recommended_move) {
1757                         var squareEl = $('#board .square-' + recommended_move.from);
1758                         squareEl.addClass('highlight1-32417');
1759                         squareEl = $('#board .square-' + recommended_move.to);
1760                         squareEl.addClass('highlight1-32417');
1761                 }
1762         }
1763 }
1764
1765 var mouseupSquare = function(e) {
1766         if (reverse_dragging_from === null) {
1767                 return;
1768         }
1769         var source = $(this).attr('data-square');
1770         var target = reverse_dragging_from;
1771         reverse_dragging_from = null;
1772         if (onDrop(source, target) !== 'snapback') {
1773                 onSnapEnd(source, target);
1774         }
1775         $("#board").find('.square-55d63').removeClass('highlight1-32417');
1776 }
1777
1778 var get_best_move = function(game, source, target, invert) {
1779         var moves = game.moves({ verbose: true });
1780         if (source !== null) {
1781                 moves = moves.filter(function(move) { return move.from == source; });
1782         }
1783         if (target !== null) {
1784                 moves = moves.filter(function(move) { return move.to == target; });
1785         }
1786         if (moves.length == 0) {
1787                 return null;
1788         }
1789         if (moves.length == 1) {
1790                 return moves[0];
1791         }
1792
1793         // More than one move. Use the display lines (if we have them)
1794         // to disambiguate; otherwise, we have no information.
1795         var move_hash = {};
1796         for (var i = 0; i < moves.length; ++i) {
1797                 move_hash[moves[i].san] = moves[i];
1798         }
1799
1800         // History and PV take priority over the display lines.
1801         for (var i = 0; i < 2; ++i) {
1802                 var line = display_lines[i];
1803                 var first_move = line.pretty_pv[line.start_display_move_num];
1804                 if (move_hash[first_move]) {
1805                         return move_hash[first_move];
1806                 }
1807         }
1808
1809         var best_move = null;
1810         var best_move_score = null;
1811
1812         for (var move in refutation_lines) {
1813                 var line = refutation_lines[move];
1814                 if (!line['score']) {
1815                         continue;
1816                 }
1817                 var first_move = line['pv_pretty'][0];
1818                 if (move_hash[first_move]) {
1819                         var score = compute_score_sort_key(line['score'], invert);
1820                         if (best_move_score === null || score > best_move_score) {
1821                                 best_move = move_hash[first_move];
1822                                 best_move_score = score;
1823                         }
1824                 }
1825         }
1826         return best_move;
1827 }
1828
1829 var onDrop = function(source, target) {
1830         if (source === target) {
1831                 if (recommended_move === null) {
1832                         return 'snapback';
1833                 } else {
1834                         // Accept the move. It will be changed in onSnapEnd.
1835                         return;
1836                 }
1837         } else {
1838                 // Suggestion not asked for.
1839                 recommended_move = null;
1840         }
1841
1842         // see if the move is legal
1843         var pseudogame = new Chess(display_fen);
1844         var move = pseudogame.move({
1845                 from: source,
1846                 to: target,
1847                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1848         });
1849
1850         // illegal move
1851         if (move === null) return 'snapback';
1852 }
1853
1854 var onSnapEnd = function(source, target) {
1855         if (source === target && recommended_move !== null) {
1856                 source = recommended_move.from;
1857                 target = recommended_move.to;
1858         }
1859         recommended_move = null;
1860         var pseudogame = new Chess(display_fen);
1861         var move = pseudogame.move({
1862                 from: source,
1863                 to: target,
1864                 promotion: 'q' // NOTE: always promote to a queen for example simplicity
1865         });
1866
1867         if (current_display_line &&
1868             current_display_move < current_display_line.pretty_pv.length - 1 &&
1869             current_display_line.pretty_pv[current_display_move + 1] === move.san) {
1870                 next_move();
1871                 return;
1872         }
1873
1874         // Walk down the displayed lines until we find one that starts with
1875         // this move, then select that. Note that this gives us a good priority
1876         // order (history first, then PV, then multi-PV lines).
1877         for (var i = 0; i < display_lines.length; ++i) {
1878                 var line = display_lines[i];
1879                 if (line.pretty_pv[line.start_display_move_num] === move.san) {
1880                         show_line(i, 0);
1881                         return;
1882                 }
1883         }
1884
1885         // Shouldn't really be here if we have hash probes, but there's really
1886         // nothing we can do.
1887 }
1888 // End of dragging-related code.
1889
1890 var pad = function(val, num_digits) {
1891         var s = val.toString();
1892         while (s.length < num_digits) {
1893                 s = " " + s;
1894         }
1895         return s;
1896 }
1897
1898 var fmt_cp = function(v) {
1899         if (v === 0) {
1900                 return "0.00";
1901         } else if (v > 0) {
1902                 return "+" + (v / 100).toFixed(2);
1903         } else {
1904                 v = -v;
1905                 return "-" + (v / 100).toFixed(2);
1906         }
1907 }
1908
1909 var format_short_score = function(score) {
1910         if (!score) {
1911                 return "???";
1912         }
1913         if (score[0] === 'm') {
1914                 if (score[2]) {  // Is a bound.
1915                         return score[2] + "\u00a0M" + pad(score[1], 3);
1916                 } else {
1917                         return "M" + pad(score[1], 3);
1918                 }
1919         } else if (score[0] === 'd') {
1920                 return "TB draw";
1921         } else if (score[0] === 'cp') {
1922                 if (score[2]) {  // Is a bound.
1923                         return score[2] + "\u00a0" + fmt_cp(score[1]);
1924                 } else {
1925                         return pad(fmt_cp(score[1]), 5);
1926                 }
1927         }
1928         return null;
1929 }
1930
1931 var format_long_score = function(score) {
1932         if (score[0] === 'm') {
1933                 if (score[1] > 0) {
1934                         return "White mates in " + score[1];
1935                 } else {
1936                         return "Black mates in " + (-score[1]);
1937                 }
1938         } else if (score[0] === 'd') {
1939                 return "Theoretical draw";
1940         } else if (score[0] === 'cp') {
1941                 return "Score: " + format_short_score(score);
1942         }
1943         return null;
1944 }
1945
1946 var compute_plot_score = function(score) {
1947         if (score[0] === 'm') {
1948                 if (score[1] > 0) {
1949                         return 500;
1950                 } else {
1951                         return -500;
1952                 }
1953         } else if (score[0] === 'd') {
1954                 return 0;
1955         } else if (score[0] === 'cp') {
1956                 if (score[1] > 500) {
1957                         return 500;
1958                 } else if (score[1] < -500) {
1959                         return -500;
1960                 } else {
1961                         return score[1];
1962                 }
1963         }
1964         return null;
1965 }
1966
1967 /**
1968  * @param score The score digest tuple.
1969  * @param {boolean} invert Whether black is to play.
1970  * @return {number}
1971  */
1972 var compute_score_sort_key = function(score, invert) {
1973         var s;
1974         if (!score) {
1975                 return -10000000;
1976         }
1977         if (score[0] === 'm') {
1978                 if (score[1] > 0) {
1979                         // White mates.
1980                         s = 99999 - score[1];
1981                 } else {
1982                         // Black mates (note the double negative for score[1]).
1983                         s = -99999 - score[1];
1984                 }
1985                 if (invert) s = -s;
1986                 return s;
1987         } else if (score[0] === 'd') {
1988                 return 0;
1989         } else if (score[0] === 'cp') {
1990                 return invert ? -score[1] : score[1];
1991         }
1992         return null;
1993 }
1994
1995 /**
1996  * @param {string} new_backend_url
1997  */
1998 var switch_backend = function(new_backend_url) {
1999         // Stop looking at historic data.
2000         current_display_line = null;
2001         current_display_move = null;
2002         displayed_analysis_data = null;
2003         if (current_historic_xhr) {
2004                 current_historic_xhr.abort();
2005         }
2006
2007         // If we already have a backend response going, abort it.
2008         if (current_analysis_xhr) {
2009                 current_analysis_xhr.abort();
2010         }
2011         if (current_hash_xhr) {
2012                 current_hash_xhr.abort();
2013         }
2014
2015         // Otherwise, we should have a timer going to start a new one.
2016         // Kill that, too.
2017         if (current_analysis_request_timer) {
2018                 clearTimeout(current_analysis_request_timer);
2019                 current_analysis_request_timer = null;
2020         }
2021         if (current_hash_display_timer) {
2022                 clearTimeout(current_hash_display_timer);
2023                 current_hash_display_timer = null;
2024         }
2025
2026         // Request an immediate fetch with the new backend.
2027         backend_url = new_backend_url;
2028         current_analysis_data = null;
2029         ims = 0;
2030         request_update();
2031 }
2032 window['switch_backend'] = switch_backend;
2033
2034 var init = function() {
2035         unique = get_unique();
2036
2037         // Load settings from HTML5 local storage if available.
2038         if (supports_html5_storage() && localStorage['enable_sound']) {
2039                 set_sound(parseInt(localStorage['enable_sound']));
2040         } else {
2041                 set_sound(false);
2042         }
2043         if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
2044                 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
2045         } else {
2046                 sort_refutation_lines_by_score = true;
2047         }
2048
2049         // Create board.
2050         board = new window.ChessBoard('board', {
2051                 onMoveEnd: function() { board_is_animating = false; },
2052
2053                 draggable: true,
2054                 onDragStart: onDragStart,
2055                 onDrop: onDrop,
2056                 onSnapEnd: onSnapEnd
2057         });
2058         $("#board").on('mousedown', '.square-55d63', mousedownSquare);
2059         $("#board").on('mouseup', '.square-55d63', mouseupSquare);
2060
2061         request_update();
2062         $(window).resize(function() {
2063                 board.resize();
2064                 update_sparkline(displayed_analysis_data || current_analysis_data);
2065                 update_board_highlight();
2066                 redraw_arrows();
2067         });
2068         $(window).keyup(function(event) {
2069                 if (event.which == 39) {
2070                         next_move();
2071                 } else if (event.which == 37) {
2072                         prev_move();
2073                 }
2074         });
2075         window.addEventListener('hashchange', possibly_switch_game_from_hash, false);
2076 };
2077 $(document).ready(init);
2078
2079 })();