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