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