]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
440419fd0062eb702e5f928655b1e22b0092ef13
[remoteglot] / www / js / remoteglot.js
1 (function() {
2
3 /** @type {window.ChessBoard} @private */
4 var board = null;
5
6 /**
7  * The most recent analysis data we have from the server
8  * (about the most recent position).
9  *
10  * @type {?Object}
11  * @private */
12 var current_analysis_data = null;
13
14 /**
15  * If we are displaying previous analysis, this is non-null,
16  * and will override most of current_analysis_data.
17  *
18  * @type {?Object}
19  * @private
20  */
21 var displayed_analysis_data = null;
22
23 /** @type {Array.<{
24  *      from_col: number,
25  *      from_row: number,
26  *      to_col: number,
27  *      to_row: number,
28  *      line_width: number,
29  *      arrow_size: number,
30  *      fg_color: string
31  * }>}
32  * @private
33  */
34 var arrows = [];
35
36 /** @type {Array.<Array.<boolean>>} */
37 var occupied_by_arrows = [];
38
39 var refutation_lines = [];
40
41 /** @type {!number} @private */
42 var move_num = 1;
43
44 /** @type {!string} @private */
45 var toplay = 'W';
46
47 /** @type {number} @private */
48 var ims = 0;
49
50 /** @type {boolean} @private */
51 var sort_refutation_lines_by_score = true;
52
53 /** @type {boolean} @private */
54 var truncate_display_history = true;
55
56 /** @type {!string|undefined} @private */
57 var highlight_from = undefined;
58
59 /** @type {!string|undefined} @private */
60 var highlight_to = undefined;
61
62 /** @type {?jQuery} @private */
63 var highlighted_move = null;
64
65 /** @type {?number} @private */
66 var unique = null;
67
68 /** @type {boolean} @private */
69 var enable_sound = false;
70
71 /**
72  * Our best estimate of how many milliseconds we need to add to 
73  * new Date() to get the true UTC time. Calibrated against the
74  * server clock.
75  *
76  * @type {?number}
77  * @private
78  */
79 var client_clock_offset_ms = null;
80
81 var clock_timer = null;
82
83 /** The current position on the board, represented as a FEN string.
84  * @type {?string}
85  * @private
86  */
87 var fen = null;
88
89 /** @typedef {{
90  *    start_fen: string,
91  *    uci_pv: Array.<string>,
92  *    pretty_pv: Array.<string>,
93  *    line_num: number
94  * }} DisplayLine
95  */
96
97 /** @type {Array.<DisplayLine>}
98  * @private
99  */
100 var display_lines = [];
101
102 /** @type {?DisplayLine} @private */
103 var current_display_line = null;
104
105 /** @type {boolean} @private */
106 var current_display_line_is_history = false;
107
108 /** @type {?number} @private */
109 var current_display_move = null;
110
111 var supports_html5_storage = function() {
112         try {
113                 return 'localStorage' in window && window['localStorage'] !== null;
114         } catch (e) {
115                 return false;
116         }
117 }
118
119 // Make the unique token persistent so people refreshing the page won't count twice.
120 // Of course, you can never fully protect against people deliberately wanting to spam.
121 var get_unique = function() {
122         var use_local_storage = supports_html5_storage();
123         if (use_local_storage && localStorage['unique']) {
124                 return localStorage['unique'];
125         }
126         var unique = Math.random();
127         if (use_local_storage) {
128                 localStorage['unique'] = unique;
129         }
130         return unique;
131 }
132
133 var request_update = function() {
134         $.ajax({
135                 url: "/analysis.pl?ims=" + ims + "&unique=" + unique
136         }).done(function(data, textstatus, xhr) {
137                 sync_server_clock(xhr.getResponseHeader('Date'));
138                 ims = xhr.getResponseHeader('X-RGLM');
139                 var num_viewers = xhr.getResponseHeader('X-RGNV');
140                 var new_data;
141                 if (Array.isArray(data)) {
142                         new_data = JSON.parse(JSON.stringify(current_analysis_data));
143                         JSON_delta.patch(new_data, data);
144                 } else {
145                         new_data = data;
146                 }
147                 possibly_play_sound(current_analysis_data, new_data);
148                 current_analysis_data = new_data;
149                 update_board(current_analysis_data, displayed_analysis_data);
150                 update_num_viewers(num_viewers);
151
152                 // Next update.
153                 setTimeout(function() { request_update(); }, 100);
154         }).fail(function() {
155                 // Wait ten seconds, then try again.
156                 setTimeout(function() { request_update(); }, 10000);
157         });
158 }
159
160 var possibly_play_sound = function(old_data, new_data) {
161         if (!enable_sound) {
162                 return;
163         }
164         if (old_data === null) {
165                 return;
166         }
167         var ding = document.getElementById('ding');
168         if (ding && ding.play) {
169                 if (old_data['position'] && old_data['position']['fen'] &&
170                     new_data['position'] && new_data['position']['fen'] &&
171                     (old_data['position']['fen'] !== new_data['position']['fen'] ||
172                      old_data['position']['move_num'] !== new_data['position']['move_num'])) {
173                         ding.play();
174                 }
175         }
176 }
177
178 /**
179  * @type {!string} server_date_string
180  */
181 var sync_server_clock = function(server_date_string) {
182         var server_time_ms = new Date(server_date_string).getTime();
183         var client_time_ms = new Date().getTime();
184         var estimated_offset_ms = server_time_ms - client_time_ms;
185
186         // In order not to let the noise move us too much back and forth
187         // (the server only has one-second resolution anyway), we only
188         // change an existing skew if we are at least five seconds off.
189         if (client_clock_offset_ms === null ||
190             Math.abs(estimated_offset_ms - client_clock_offset_ms) > 5000) {
191                 client_clock_offset_ms = estimated_offset_ms;
192         }
193 }
194
195 var clear_arrows = function() {
196         for (var i = 0; i < arrows.length; ++i) {
197                 if (arrows[i].svg) {
198                         arrows[i].svg.parentElement.removeChild(arrows[i].svg);
199                         delete arrows[i].svg;
200                 }
201         }
202         arrows = [];
203
204         occupied_by_arrows = [];
205         for (var y = 0; y < 8; ++y) {
206                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
207         }
208 }
209
210 var redraw_arrows = function() {
211         for (var i = 0; i < arrows.length; ++i) {
212                 position_arrow(arrows[i]);
213         }
214 }
215
216 /** @param {!number} x
217  * @return {!number}
218  */
219 var sign = function(x) {
220         if (x > 0) {
221                 return 1;
222         } else if (x < 0) {
223                 return -1;
224         } else {
225                 return 0;
226         }
227 }
228
229 /** See if drawing this arrow on the board would cause unduly amount of confusion.
230  * @param {!string} from The square the arrow is from (e.g. e4).
231  * @param {!string} to The square the arrow is to (e.g. e4).
232  * @return {boolean}
233  */
234 var interfering_arrow = function(from, to) {
235         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
236         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
237         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
238         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
239
240         occupied_by_arrows[from_row][from_col] = true;
241
242         // Knight move: Just check that we haven't been at the destination before.
243         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
244             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
245                 return occupied_by_arrows[to_row][to_col];
246         }
247
248         // Sliding piece: Check if anything except the from-square is seen before.
249         var dx = sign(to_col - from_col);
250         var dy = sign(to_row - from_row);
251         var x = from_col;
252         var y = from_row;
253         do {
254                 x += dx;
255                 y += dy;
256                 if (occupied_by_arrows[y][x]) {
257                         return true;
258                 }
259                 occupied_by_arrows[y][x] = true;
260         } while (x != to_col || y != to_row);
261
262         return false;
263 }
264
265 /** Find a point along the coordinate system given by the given line,
266  * <t> units forward from the start of the line, <u> units to the right of it.
267  * @param {!number} x1
268  * @param {!number} x2
269  * @param {!number} y1
270  * @param {!number} y2
271  * @param {!number} t
272  * @param {!number} u
273  * @return {!string} The point in "x y" form, suitable for SVG paths.
274  */
275 var point_from_start = function(x1, y1, x2, y2, t, u) {
276         var dx = x2 - x1;
277         var dy = y2 - y1;
278
279         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
280         dx *= norm;
281         dy *= norm;
282
283         var x = x1 + dx * t + dy * u;
284         var y = y1 + dy * t - dx * u;
285         return x + " " + y;
286 }
287
288 /** Find a point along the coordinate system given by the given line,
289  * <t> units forward from the end of the line, <u> units to the right of it.
290  * @param {!number} x1
291  * @param {!number} x2
292  * @param {!number} y1
293  * @param {!number} y2
294  * @param {!number} t
295  * @param {!number} u
296  * @return {!string} The point in "x y" form, suitable for SVG paths.
297  */
298 var point_from_end = function(x1, y1, x2, y2, t, u) {
299         var dx = x2 - x1;
300         var dy = y2 - y1;
301
302         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
303         dx *= norm;
304         dy *= norm;
305
306         var x = x2 + dx * t + dy * u;
307         var y = y2 + dy * t - dx * u;
308         return x + " " + y;
309 }
310
311 var position_arrow = function(arrow) {
312         if (arrow.svg) {
313                 arrow.svg.parentElement.removeChild(arrow.svg);
314                 delete arrow.svg;
315         }
316         if (current_display_line !== null && !current_display_line_is_history) {
317                 return;
318         }
319
320         var pos = $(".square-a8").position();
321
322         var zoom_factor = $("#board").width() / 400.0;
323         var line_width = arrow.line_width * zoom_factor;
324         var arrow_size = arrow.arrow_size * zoom_factor;
325
326         var square_width = $(".square-a8").width();
327         var from_y = (7 - arrow.from_row + 0.5)*square_width;
328         var to_y = (7 - arrow.to_row + 0.5)*square_width;
329         var from_x = (arrow.from_col + 0.5)*square_width;
330         var to_x = (arrow.to_col + 0.5)*square_width;
331
332         var SVG_NS = "http://www.w3.org/2000/svg";
333         var XHTML_NS = "http://www.w3.org/1999/xhtml";
334         var svg = document.createElementNS(SVG_NS, "svg");
335         svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
336         svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
337         svg.setAttribute("style", "position: absolute");
338         svg.setAttribute("position", "absolute");
339         svg.setAttribute("version", "1.1");
340         svg.setAttribute("class", "c1");
341         svg.setAttribute("xmlns", XHTML_NS);
342
343         var x1 = from_x;
344         var y1 = from_y;
345         var x2 = to_x;
346         var y2 = to_y;
347
348         // Draw the line.
349         var outline = document.createElementNS(SVG_NS, "path");
350         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));
351         outline.setAttribute("xmlns", XHTML_NS);
352         outline.setAttribute("stroke", "#666");
353         outline.setAttribute("stroke-width", line_width + 2);
354         outline.setAttribute("fill", "none");
355         svg.appendChild(outline);
356
357         var path = document.createElementNS(SVG_NS, "path");
358         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));
359         path.setAttribute("xmlns", XHTML_NS);
360         path.setAttribute("stroke", arrow.fg_color);
361         path.setAttribute("stroke-width", line_width);
362         path.setAttribute("fill", "none");
363         svg.appendChild(path);
364
365         // Then the arrow head.
366         var head = document.createElementNS(SVG_NS, "path");
367         head.setAttribute("d",
368                 "M " +  point_from_end(x1, y1, x2, y2, 0, 0) +
369                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
370                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
371                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
372                 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
373         head.setAttribute("xmlns", XHTML_NS);
374         head.setAttribute("stroke", "#000");
375         head.setAttribute("stroke-width", "1");
376         head.setAttribute("fill", arrow.fg_color);
377         svg.appendChild(head);
378
379         $(svg).css({ top: pos.top, left: pos.left });
380         document.body.appendChild(svg);
381         arrow.svg = svg;
382 }
383
384 /**
385  * @param {!string} from_square
386  * @param {!string} to_square
387  * @param {!string} fg_color
388  * @param {number} line_width
389  * @param {number} arrow_size
390  */
391 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
392         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
393         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
394         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
395         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
396
397         // Create arrow.
398         var arrow = {
399                 from_col: from_col,
400                 from_row: from_row,
401                 to_col: to_col,
402                 to_row: to_row,
403                 line_width: line_width,
404                 arrow_size: arrow_size,
405                 fg_color: fg_color
406         };
407
408         position_arrow(arrow);
409         arrows.push(arrow);
410 }
411
412 var compare_by_sort_key = function(refutation_lines, a, b) {
413         var ska = refutation_lines[a]['sort_key'];
414         var skb = refutation_lines[b]['sort_key'];
415         if (ska < skb) return -1;
416         if (ska > skb) return 1;
417         return 0;
418 };
419
420 var compare_by_score = function(refutation_lines, a, b) {
421         var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
422         var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
423         return sa - sb;
424 }
425
426 /**
427  * Fake multi-PV using the refutation lines. Find all “relevant” moves,
428  * sorted by quality, descending.
429  *
430  * @param {!Object} data
431  * @param {number} margin The maximum number of centipawns worse than the
432  *     best move can be and still be included.
433  * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
434  *     moves, in score order.
435  */
436 var find_nonstupid_moves = function(data, margin) {
437         // First of all, if there are any moves that are more than 0.5 ahead of
438         // the primary move, the refutation lines are probably bunk, so just
439         // kill them all. 
440         var best_score = undefined;
441         var pv_score = undefined;
442         for (var move in data['refutation_lines']) {
443                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
444                 if (move == data['pv_uci'][0]) {
445                         pv_score = score;
446                 }
447                 if (best_score === undefined || score > best_score) {
448                         best_score = score;
449                 }
450                 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
451                         return [];
452                 }
453         }
454
455         if (best_score - pv_score > 50) {
456                 return [];
457         }
458
459         // Now find all moves that are within “margin” of the best score.
460         // The PV move will always be first.
461         var moves = [];
462         for (var move in data['refutation_lines']) {
463                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
464                 if (move != data['pv_uci'][0] && best_score - score <= margin) {
465                         moves.push(move);
466                 }
467         }
468         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
469         moves.unshift(data['pv_uci'][0]);
470
471         return moves;
472 }
473
474 /**
475  * @param {number} x
476  * @return {!string}
477  */
478 var thousands = function(x) {
479         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
480 }
481
482 /**
483  * @param {!string} fen
484  * @param {Array.<string>} pretty_pv
485  * @param {number} move_num
486  * @param {!string} toplay
487  * @param {number=} opt_limit
488  * @param {boolean=} opt_showlast
489  */
490 var add_pv = function(fen, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
491         display_lines.push({
492                 start_fen: fen,
493                 pretty_pv: pretty_pv,
494                 line_number: display_lines.length
495         });
496         return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
497 }
498
499 /**
500  * @param {number} line_num
501  * @param {Array.<string>} pretty_pv
502  * @param {number} move_num
503  * @param {!string} toplay
504  * @param {number=} opt_limit
505  * @param {boolean=} opt_showlast
506  */
507 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
508         var pv = '';
509         var i = 0;
510         if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
511                 // Truncate the PV at the beginning (instead of at the end).
512                 // We assume here that toplay is 'W'. We also assume that if
513                 // opt_showlast is set, then it is the history, and thus,
514                 // the UI should be to expand the history.
515                 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
516                 i = pretty_pv.length - opt_limit;
517                 if (i % 2 == 1) {
518                         ++i;
519                 }
520                 move_num += i / 2;
521         } else if (toplay == 'B' && pretty_pv.length > 0) {
522                 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
523                 pv = move_num + '. … ' + move;
524                 toplay = 'W';
525                 ++i;
526                 ++move_num;
527         }
528         for ( ; i < pretty_pv.length; ++i) {
529                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
530
531                 if (toplay == 'W') {
532                         if (i > opt_limit && !opt_showlast) {
533                                 return pv + ' (…)';
534                         }
535                         if (pv != '') {
536                                 pv += ' ';
537                         }
538                         pv += move_num + '. ' + move;
539                         ++move_num;
540                         toplay = 'B';
541                 } else {
542                         pv += ' ' + move;
543                         toplay = 'W';
544                 }
545         }
546         return pv;
547 }
548
549 var update_highlight = function() {
550         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
551         if ((current_display_line === null || current_display_line_is_history) &&
552             highlight_from !== undefined && highlight_to !== undefined) {
553                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
554                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
555         }
556 }
557
558 var update_history = function() {
559         if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
560                 $("#history").html("No history");
561         } else if (truncate_display_history) {
562                 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
563         } else {
564                 $("#history").html(
565                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
566                         print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
567         }
568 }
569
570 /**
571  * @param {!boolean} truncate_history
572  */
573 var collapse_history = function(truncate_history) {
574         truncate_display_history = truncate_history;
575         update_history();
576 }
577 window['collapse_history'] = collapse_history;
578
579 var update_refutation_lines = function() {
580         if (fen === null) {
581                 return;
582         }
583         if (display_lines.length > 2) {
584                 display_lines = [ display_lines[0], display_lines[1] ];
585         }
586
587         var tbl = $("#refutationlines");
588         tbl.empty();
589
590         var moves = [];
591         for (var move in refutation_lines) {
592                 moves.push(move);
593         }
594         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
595         moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
596         for (var i = 0; i < moves.length; ++i) {
597                 var line = refutation_lines[moves[i]];
598
599                 var tr = document.createElement("tr");
600
601                 var move_td = document.createElement("td");
602                 tr.appendChild(move_td);
603                 $(move_td).addClass("move");
604                 if (line['pv_pretty'].length == 0) {
605                         $(move_td).text(line['pretty_move']);
606                 } else {
607                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
608                         $(move_td).html(move);
609                 }
610
611                 var score_td = document.createElement("td");
612                 tr.appendChild(score_td);
613                 $(score_td).addClass("score");
614                 $(score_td).text(line['pretty_score']);
615
616                 var depth_td = document.createElement("td");
617                 tr.appendChild(depth_td);
618                 $(depth_td).addClass("depth");
619                 $(depth_td).text("d" + line['depth']);
620
621                 var pv_td = document.createElement("td");
622                 tr.appendChild(pv_td);
623                 $(pv_td).addClass("pv");
624                 $(pv_td).html(add_pv(fen, line['pv_pretty'], move_num, toplay, 10));
625
626                 tbl.append(tr);
627         }
628
629         // Make one of the links clickable and the other nonclickable.
630         if (sort_refutation_lines_by_score) {
631                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
632                 $("#sortbyscore1").html("<strong>Score</strong>");
633         } else {
634                 $("#sortbyscore0").html("<strong>Move</strong>");
635                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
636         }
637 }
638
639 /**
640  * @param {?string} fen
641  * @param {Array.<string>} moves
642  * @param {number} last_move
643  */
644 var chess_from = function(fen, moves, last_move) {
645         var hiddenboard = new Chess();
646         if (fen !== null) {
647                 hiddenboard.load(fen);
648         }
649         for (var i = 0; i <= last_move; ++i) {
650                 if (moves[i] === '0-0') {
651                         hiddenboard.move('O-O');
652                 } else if (moves[i] === '0-0-0') {
653                         hiddenboard.move('O-O-O');
654                 } else {
655                         hiddenboard.move(moves[i]);
656                 }
657         }
658         return hiddenboard;
659 }
660
661 /**
662  * @param {Object} data
663  * @param {?Object} display_data
664  */
665 var update_board = function(current_data, display_data) {
666         var data = display_data || current_data;
667
668         display_lines = [];
669
670         // Print the history. This is pretty much the only thing that's
671         // unconditionally taken from current_data (we're not interested in
672         // historic history).
673         if (current_data['position']['pretty_history']) {
674                 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
675         } else {
676                 display_lines.push(null);
677         }
678         update_history();
679
680         // The headline. Names are always fetched from current_data;
681         // the rest can depend a bit.
682         var headline;
683         if (current_data &&
684             current_data['position']['player_w'] && current_data['position']['player_b']) {
685                 headline = current_data['position']['player_w'] + '–' +
686                         current_data['position']['player_b'] + ', analysis';
687         } else {
688                 headline = 'Analysis';
689         }
690
691         var last_move;
692         if (display_data) {
693                 // Displaying some non-current position, pick out the last move
694                 // from the history. This will work even if the fetch failed.
695                 last_move = format_halfmove_with_number(
696                         current_display_line.pretty_pv[current_display_move],
697                         current_display_move + 1);
698                 headline += ' after ' + last_move;
699         } else if (data['position']['last_move'] !== 'none') {
700                 last_move = format_move_with_number(
701                         data['position']['last_move'],
702                         data['position']['move_num'],
703                         data['position']['toplay'] == 'W');
704                 headline += ' after ' + last_move;
705         } else {
706                 last_move = null;
707         }
708         $("#headline").text(headline);
709
710         // The <title> contains a very brief headline.
711         var title_elems = [];
712         if (data['short_score'] !== undefined && data['short_score'] !== null) {
713                 title_elems.push(data['short_score'].replace(/^ /, ""));
714         }
715         if (last_move !== null) {
716                 title_elems.push(last_move);
717         }
718
719         if (title_elems.length != 0) {
720                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
721         } else {
722                 document.title = 'analysis.sesse.net';
723         }
724
725         // The last move (shown by highlighting the from and to squares).
726         if (data['position'] && data['position']['last_move_uci']) {
727                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
728                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
729         } else if (current_display_line_is_history && current_display_move >= 0) {
730                 // We don't have historic analysis for this position, but we
731                 // can reconstruct what the last move was by just replaying
732                 // from the start.
733                 var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
734                 var moves = hiddenboard.history({ verbose: true });
735                 var last_move = moves.pop();
736                 highlight_from = last_move.from;
737                 highlight_to = last_move.to;
738         } else {
739                 highlight_from = highlight_to = undefined;
740         }
741         update_highlight();
742
743         if (data['failed']) {
744                 $("#score").text("No analysis for this move");
745                 $("#pv").empty();
746                 $("#searchstats").html("&nbsp;");
747                 $("#refutationlines").empty();
748                 $("#whiteclock").empty();
749                 $("#blackclock").empty();
750                 refutation_lines = [];
751                 update_refutation_lines();
752                 clear_arrows();
753                 update_displayed_line();
754                 return;
755         }
756
757         update_clock();
758
759         // The engine id.
760         if (data['id'] && data['id']['name'] !== null) {
761                 $("#engineid").text(data['id']['name']);
762         }
763
764         // The score.
765         if (data['score'] !== null) {
766                 $("#score").text(data['score']);
767         }
768
769         // The search stats.
770         if (data['tablebase'] == 1) {
771                 $("#searchstats").text("Tablebase result");
772         } else if (data['nodes'] && data['nps'] && data['depth']) {
773                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
774                 if (data['seldepth']) {
775                         stats += ' (' + data['seldepth'] + ' selective)';
776                 }
777                 if (data['tbhits'] && data['tbhits'] > 0) {
778                         if (data['tbhits'] == 1) {
779                                 stats += ', one Syzygy hit';
780                         } else {
781                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
782                         }
783                 }
784
785                 $("#searchstats").text(stats);
786         } else {
787                 $("#searchstats").text("");
788         }
789
790         // Update the board itself.
791         fen = data['position']['fen'];
792         update_displayed_line();
793
794         // Print the PV.
795         $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
796
797         // Update the PV arrow.
798         clear_arrows();
799         if (data['pv_uci'].length >= 1) {
800                 // draw a continuation arrow as long as it's the same piece
801                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
802                         var from = data['pv_uci'][i].substr(0, 2);
803                         var to = data['pv_uci'][i].substr(2,4);
804                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
805                              interfering_arrow(from, to)) {
806                                 break;
807                         }
808                         create_arrow(from, to, '#f66', 6, 20);
809                 }
810
811                 var alt_moves = find_nonstupid_moves(data, 30);
812                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
813                         create_arrow(alt_moves[i].substr(0, 2),
814                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
815                 }
816         }
817
818         // See if all semi-reasonable moves have only one possible response.
819         if (data['pv_uci'].length >= 2) {
820                 var nonstupid_moves = find_nonstupid_moves(data, 300);
821                 var response = data['pv_uci'][1];
822                 for (var i = 0; i < nonstupid_moves.length; ++i) {
823                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
824                                 // ignore the PV move for refutation lines.
825                                 continue;
826                         }
827                         if (!data['refutation_lines'] ||
828                             !data['refutation_lines'][nonstupid_moves[i]] ||
829                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
830                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
831                                 // Incomplete PV, abort.
832                                 response = undefined;
833                                 break;
834                         }
835                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
836                         if (response !== this_response) {
837                                 // Different response depending on lines, abort.
838                                 response = undefined;
839                                 break;
840                         }
841                 }
842
843                 if (nonstupid_moves.length > 0 && response !== undefined) {
844                         create_arrow(response.substr(0, 2),
845                                      response.substr(2, 2), '#66f', 6, 20);
846                 }
847         }
848
849         // Update the refutation lines.
850         fen = data['position']['fen'];
851         move_num = data['position']['move_num'];
852         toplay = data['position']['toplay'];
853         refutation_lines = data['refutation_lines'];
854         update_refutation_lines();
855
856         // Update the sparkline last, since its size depends on how everything else reflowed.
857         update_sparkline(data);
858 }
859
860 var update_sparkline = function(data) {
861         if (data && data['score_history']) {
862                 var first_move_num = undefined;
863                 for (var halfmove_num in data['score_history']) {
864                         halfmove_num = parseInt(halfmove_num);
865                         if (first_move_num === undefined || halfmove_num < first_move_num) {
866                                 first_move_num = halfmove_num;
867                         }
868                 }
869                 if (first_move_num !== undefined) {
870                         var last_move_num = data['position']['move_num'] * 2 - 3;
871                         if (data['position']['toplay'] === 'B') {
872                                 ++last_move_num;
873                         }
874
875                         // Possibly truncate some moves if we don't have enough width.
876                         // FIXME: Sometimes width() for #scorecontainer (and by extent,
877                         // #scoresparkcontainer) on Chrome for mobile seems to start off
878                         // at something very small, and then suddenly snap back into place.
879                         // Figure out why.
880                         var max_moves = Math.floor($("#scoresparkcontainer").width() / 5) - 5;
881                         if (last_move_num - first_move_num > max_moves) {
882                                 first_move_num = last_move_num - max_moves;
883                         }
884
885                         var min_score = -100;
886                         var max_score = 100;
887                         var last_score = null;
888                         var scores = [];
889                         for (var halfmove_num = first_move_num; halfmove_num <= last_move_num; ++halfmove_num) {
890                                 if (data['score_history'][halfmove_num]) {
891                                         var score = data['score_history'][halfmove_num][0];
892                                         if (score < min_score) min_score = score;
893                                         if (score > max_score) max_score = score;
894                                         last_score = data['score_history'][halfmove_num][0];
895                                 }
896                                 scores.push(last_score);
897                         }
898                         if (data['plot_score']) {
899                                 scores.push(data['plot_score']);
900                         }
901                         // FIXME: at some widths, calling sparkline() seems to push
902                         // #scorecontainer under the board.
903                         $("#scorespark").sparkline(scores, {
904                                 type: 'bar',
905                                 zeroColor: 'gray',
906                                 chartRangeMin: min_score,
907                                 chartRangeMax: max_score,
908                                 tooltipFormatter: function(sparkline, options, fields) {
909                                         return format_tooltip(data, fields[0].offset + first_move_num);
910                                 }
911                         });
912                 } else {
913                         $("#scorespark").text("");
914                 }
915         } else {
916                 $("#scorespark").text("");
917         }
918 }
919
920 /**
921  * @param {number} num_viewers
922  */
923 var update_num_viewers = function(num_viewers) {
924         if (num_viewers === null) {
925                 $("#numviewers").text("");
926         } else if (num_viewers == 1) {
927                 $("#numviewers").text("You are the only current viewer");
928         } else {
929                 $("#numviewers").text(num_viewers + " current viewers");
930         }
931 }
932
933 var update_clock = function() {
934         clearTimeout(clock_timer);
935
936         var data = displayed_analysis_data || current_analysis_data;
937         if (data['position']) {
938                 var result = data['position']['result'];
939                 if (result === '1-0') {
940                         $("#whiteclock").text("1");
941                         $("#blackclock").text("0");
942                         $("#whiteclock").removeClass("running-clock");
943                         $("#blackclock").removeClass("running-clock");
944                         return;
945                 }
946                 if (result === '1/2-1/2') {
947                         $("#whiteclock").text("1/2");
948                         $("#blackclock").text("1/2");
949                         $("#whiteclock").removeClass("running-clock");
950                         $("#blackclock").removeClass("running-clock");
951                         return;
952                 }       
953                 if (result === '0-1') {
954                         $("#whiteclock").text("0");
955                         $("#blackclock").text("1");
956                         $("#whiteclock").removeClass("running-clock");
957                         $("#blackclock").removeClass("running-clock");
958                         return;
959                 }
960         }
961
962         var white_clock_ms = null;
963         var black_clock_ms = null;
964         var show_seconds = false;
965
966         // Static clocks.
967         if (data['position'] &&
968             data['position']['white_clock'] &&
969             data['position']['black_clock']) {
970                 white_clock_ms = data['position']['white_clock'] * 1000;
971                 black_clock_ms = data['position']['black_clock'] * 1000;
972         }
973
974         // Dynamic clock (only one, obviously).
975         var color;
976         if (data['position']['white_clock_target']) {
977                 color = "white";
978                 $("#whiteclock").addClass("running-clock");
979                 $("#blackclock").removeClass("running-clock");
980         } else if (data['position']['black_clock_target']) {
981                 color = "black";
982                 $("#whiteclock").removeClass("running-clock");
983                 $("#blackclock").addClass("running-clock");
984         } else {
985                 $("#whiteclock").removeClass("running-clock");
986                 $("#blackclock").removeClass("running-clock");
987         }
988         var remaining_ms;
989         if (color) {
990                 var now = new Date().getTime() + client_clock_offset_ms;
991                 remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
992                 if (color === "white") {
993                         white_clock_ms = remaining_ms;
994                 } else {
995                         black_clock_ms = remaining_ms;
996                 }
997         }
998
999         if (white_clock_ms === null || black_clock_ms === null) {
1000                 $("#whiteclock").empty();
1001                 $("#blackclock").empty();
1002                 return;
1003         }
1004
1005         // If either player has ten minutes or less left, add the second counters.
1006         var show_seconds = (white_clock_ms < 60 * 10 * 1000 || black_clock_ms < 60 * 10 * 1000);
1007
1008         if (color) {
1009                 // See when the clock will change next, and update right after that.
1010                 var next_update_ms;
1011                 if (show_seconds) {
1012                         next_update_ms = remaining_ms % 1000 + 100;
1013                 } else {
1014                         next_update_ms = remaining_ms % 60000 + 100;
1015                 }
1016                 clock_timer = setTimeout(update_clock, next_update_ms);
1017         }
1018
1019         $("#whiteclock").text(format_clock(white_clock_ms, show_seconds));
1020         $("#blackclock").text(format_clock(black_clock_ms, show_seconds));
1021 }
1022
1023 /**
1024  * @param {Number} remaining_ms
1025  * @param {boolean} show_seconds
1026  */
1027 var format_clock = function(remaining_ms, show_seconds) {
1028         if (remaining_ms <= 0) {
1029                 if (show_seconds) {
1030                         return "00:00:00";
1031                 } else {
1032                         return "00:00";
1033                 }
1034         }
1035
1036         var remaining = Math.floor(remaining_ms / 1000);
1037         var seconds = remaining % 60;
1038         remaining = (remaining - seconds) / 60;
1039         var minutes = remaining % 60;
1040         remaining = (remaining - minutes) / 60;
1041         var hours = remaining;
1042         if (show_seconds) {
1043                 return format_2d(hours) + ":" + format_2d(minutes) + ":" + format_2d(seconds);
1044         } else {
1045                 return format_2d(hours) + ":" + format_2d(minutes);
1046         }
1047 }
1048
1049 /**
1050  * @param {Number} x
1051  */
1052 var format_2d = function(x) {
1053         if (x >= 10) {
1054                 return x;
1055         } else {
1056                 return "0" + x;
1057         }
1058 }
1059
1060 /**
1061  * @param {string} move
1062  * @param {Number} move_num
1063  * @param {boolean} white_to_play
1064  */
1065 var format_move_with_number = function(move, move_num, white_to_play) {
1066         var ret;
1067         if (white_to_play) {
1068                 ret = (move_num - 1) + '… ';
1069         } else {
1070                 ret = move_num + '. ';
1071         }
1072         ret += move;
1073         return ret;
1074 }
1075
1076 /**
1077  * @param {string} move
1078  * @param {Number} halfmove_num
1079  */
1080 var format_halfmove_with_number = function(move, halfmove_num) {
1081         return format_move_with_number(
1082                 move,
1083                 Math.floor(halfmove_num / 2) + 1,
1084                 halfmove_num % 2 == 0);
1085 }
1086
1087 /**
1088  * @param {Object} data
1089  * @param {Number} halfmove_num
1090  */
1091 var format_tooltip = function(data, halfmove_num) {
1092         if (data['score_history'][halfmove_num] ||
1093             halfmove_num === data['position']['pretty_history'].length) {
1094                 var move;
1095                 var short_score;
1096                 if (halfmove_num === data['position']['pretty_history'].length) {
1097                         move = data['position']['last_move'];
1098                         short_score = data['short_score'];
1099                 } else {
1100                         move = data['position']['pretty_history'][halfmove_num];
1101                         short_score = data['score_history'][halfmove_num][1];
1102                 }
1103                 var move_with_number = format_halfmove_with_number(move, halfmove_num);
1104
1105                 return "After " + move_with_number + ": " + short_score;
1106         } else {
1107                 for (var i = halfmove_num; i --> 0; ) {
1108                         if (data['score_history'][i]) {
1109                                 var move = data['position']['pretty_history'][i];
1110                                 return "[Analysis kept from " + format_halfmove_with_number(move, i) + "]";
1111                         }
1112                 }
1113         }
1114 }
1115
1116 /**
1117  * @param {boolean} sort_by_score
1118  */
1119 var resort_refutation_lines = function(sort_by_score) {
1120         sort_refutation_lines_by_score = sort_by_score;
1121         if (supports_html5_storage()) {
1122                 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
1123         }
1124         update_refutation_lines();
1125 }
1126 window['resort_refutation_lines'] = resort_refutation_lines;
1127
1128 /**
1129  * @param {boolean} truncate_history
1130  */
1131 var set_truncate_history = function(truncate_history) {
1132         truncate_display_history = truncate_history;
1133         update_refutation_lines();
1134 }
1135 window['set_truncate_history'] = set_truncate_history;
1136
1137 /**
1138  * @param {number} line_num
1139  * @param {number} move_num
1140  */
1141 var show_line = function(line_num, move_num) {
1142         if (line_num == -1) {
1143                 current_display_line = null;
1144                 current_display_move = null;
1145                 if (displayed_analysis_data) {
1146                         // TODO: Support exiting to history position if we are in an
1147                         // analysis line of a history position.
1148                         displayed_analysis_data = null;
1149                         update_board(current_analysis_data, displayed_analysis_data);
1150                 }
1151         } else {
1152                 current_display_line = display_lines[line_num];
1153                 current_display_move = move_num;
1154         }
1155         current_display_line_is_history = (line_num == 0);
1156
1157         update_historic_analysis();
1158         update_displayed_line();
1159         update_highlight();
1160         redraw_arrows();
1161 }
1162 window['show_line'] = show_line;
1163
1164 var prev_move = function() {
1165         if (current_display_move > -1) {
1166                 --current_display_move;
1167         }
1168         update_historic_analysis();
1169         update_displayed_line();
1170 }
1171 window['prev_move'] = prev_move;
1172
1173 var next_move = function() {
1174         if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1175                 ++current_display_move;
1176         }
1177         update_historic_analysis();
1178         update_displayed_line();
1179 }
1180 window['next_move'] = next_move;
1181
1182 var update_historic_analysis = function() {
1183         if (!current_display_line_is_history) {
1184                 return;
1185         }
1186         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1187                 displayed_analysis_data = null;
1188                 update_board(current_analysis_data, displayed_analysis_data);
1189         }
1190
1191         // Fetch old analysis for this line if it exists.
1192         var hiddenboard = chess_from(null, current_display_line.pretty_pv, current_display_move);
1193         var filename = "/history/move" + (current_display_move + 1) + "-" +
1194                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1195
1196         $.ajax({
1197                 url: filename
1198         }).done(function(data, textstatus, xhr) {
1199                 displayed_analysis_data = data;
1200                 update_board(current_analysis_data, displayed_analysis_data);
1201         }).fail(function() {
1202                 displayed_analysis_data = {'failed': true};
1203                 update_board(current_analysis_data, displayed_analysis_data);
1204         });
1205 }
1206
1207 /**
1208  * @param {string} fen
1209  */
1210 var update_imbalance = function(fen) {
1211         var hiddenboard = new Chess(fen);
1212         var imbalance = {'k': 0, 'q': 0, 'r': 0, 'b': 0, 'n': 0, 'p': 0};
1213         for (var row = 0; row < 8; ++row) {
1214                 for (var col = 0; col < 8; ++col) {
1215                         var col_text = String.fromCharCode('a1'.charCodeAt(0) + col);
1216                         var row_text = String.fromCharCode('a1'.charCodeAt(1) + row);
1217                         var square = col_text + row_text;
1218                         var contents = hiddenboard.get(square);
1219                         if (contents !== null) {
1220                                 if (contents.color === 'w') {
1221                                         ++imbalance[contents.type];
1222                                 } else {
1223                                         --imbalance[contents.type];
1224                                 }
1225                         }
1226                 }
1227         }
1228         var white_imbalance = '';
1229         var black_imbalance = '';
1230         for (var piece in imbalance) {
1231                 for (var i = 0; i < imbalance[piece]; ++i) {
1232                         white_imbalance += '<img src="img/chesspieces/wikipedia/w' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1233                 }
1234                 for (var i = 0; i < -imbalance[piece]; ++i) {
1235                         black_imbalance += '<img src="img/chesspieces/wikipedia/b' + piece.toUpperCase() + '.png" alt="" style="width: 15px;height: 15px;">';
1236                 }
1237         }
1238         $('#whiteimbalance').html(white_imbalance);
1239         $('#blackimbalance').html(black_imbalance);
1240 }
1241
1242 var update_displayed_line = function() {
1243         if (highlighted_move !== null) {
1244                 highlighted_move.removeClass('highlight'); 
1245         }
1246         if (current_display_line === null) {
1247                 $("#linenav").hide();
1248                 $("#linemsg").show();
1249                 board.position(fen);
1250                 update_imbalance(fen);
1251                 return;
1252         }
1253
1254         $("#linenav").show();
1255         $("#linemsg").hide();
1256
1257         if (current_display_move <= 0) {
1258                 $("#prevmove").html("Previous");
1259         } else {
1260                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1261         }
1262         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1263                 $("#nextmove").html("Next");
1264         } else {
1265                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1266         }
1267
1268         highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1269         highlighted_move.addClass('highlight'); 
1270
1271         var hiddenboard = chess_from(current_display_line.start_fen, current_display_line.pretty_pv, current_display_move);
1272         board.position(hiddenboard.fen());
1273         update_imbalance(hiddenboard.fen());
1274 }
1275
1276 /**
1277  * @param {boolean} param_enable_sound
1278  */
1279 var set_sound = function(param_enable_sound) {
1280         enable_sound = param_enable_sound;
1281         if (enable_sound) {
1282                 $("#soundon").html("<strong>On</strong>");
1283                 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1284
1285                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1286                 // and also preload the file since the user has selected audio.
1287                 var ding = document.getElementById('ding');
1288                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1289                         ding.src = 'ding.opus';
1290                         ding.load();
1291                 }
1292         } else {
1293                 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1294                 $("#soundoff").html("<strong>Off</strong>");
1295         }
1296         if (supports_html5_storage()) {
1297                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1298         }
1299 }
1300 window['set_sound'] = set_sound;
1301
1302 var init = function() {
1303         unique = get_unique();
1304
1305         // Load settings from HTML5 local storage if available.
1306         if (supports_html5_storage() && localStorage['enable_sound']) {
1307                 set_sound(parseInt(localStorage['enable_sound']));
1308         } else {
1309                 set_sound(false);
1310         }
1311         if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1312                 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1313         } else {
1314                 sort_refutation_lines_by_score = true;
1315         }
1316
1317         // Create board.
1318         board = new window.ChessBoard('board', 'start');
1319
1320         request_update();
1321         $(window).resize(function() {
1322                 board.resize();
1323                 update_sparkline(displayed_analysis_data || current_analysis_data);
1324                 update_highlight();
1325                 redraw_arrows();
1326         });
1327         $(window).keyup(function(event) {
1328                 if (event.which == 39) {
1329                         next_move();
1330                 } else if (event.which == 37) {
1331                         prev_move();
1332                 }
1333         });
1334 };
1335 $(document).ready(init);
1336
1337 })();