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