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