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