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