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