More header squeezing.
[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 {Object} data
638  * @param {?Object} display_data
639  */
640 var update_board = function(current_data, display_data) {
641         var data = display_data || current_data;
642
643         display_lines = [];
644
645         // Print the history. This is pretty much the only thing that's
646         // unconditionally taken from current_data (we're not interested in
647         // historic history).
648         if (current_data['position']['pretty_history']) {
649                 add_pv('start', current_data['position']['pretty_history'], 1, 'W', 8, true);
650         } else {
651                 display_lines.push(null);
652         }
653         update_history();
654
655         // The headline. Names are always fetched from current_data;
656         // the rest can depend a bit.
657         var headline;
658         if (current_data &&
659             current_data['position']['player_w'] && current_data['position']['player_b']) {
660                 headline = current_data['position']['player_w'] + '–' +
661                         current_data['position']['player_b'] + ', analysis';
662         } else {
663                 headline = 'Analysis';
664         }
665
666         var last_move;
667         if (display_data) {
668                 // Displaying some non-current position, pick out the last move
669                 // from the history. This will work even if the fetch failed.
670                 last_move = format_move_with_number(
671                         current_display_line.pretty_pv[current_display_move],
672                         Math.floor((current_display_move + 1) / 2) + 1,
673                         (current_display_move % 2 == 1));
674                 headline += ' after ' + last_move;
675         } else if (data['position']['last_move'] !== 'none') {
676                 last_move = format_move_with_number(
677                         data['position']['last_move'],
678                         data['position']['move_num'],
679                         data['position']['toplay'] == 'W');
680                 headline += ' after ' + last_move;
681         } else {
682                 last_move = null;
683         }
684         $("#headline").text(headline);
685
686         // The <title> contains a very brief headline.
687         var title_elems = [];
688         if (data['short_score'] !== undefined && data['short_score'] !== null) {
689                 title_elems.push(data['short_score'].replace(/^ /, ""));
690         }
691         if (last_move !== null) {
692                 title_elems.push(last_move);
693         }
694
695         if (title_elems.length != 0) {
696                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
697         } else {
698                 document.title = 'analysis.sesse.net';
699         }
700
701         // The last move (shown by highlighting the from and to squares).
702         if (data['position'] && data['position']['last_move_uci']) {
703                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
704                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
705         } else if (current_display_line_is_history && current_display_move >= 0) {
706                 // We don't have historic analysis for this position, but we
707                 // can reconstruct what the last move was by just replaying
708                 // from the start.
709                 var hiddenboard = new Chess();
710                 for (var i = 0; i <= current_display_move; ++i) {
711                         hiddenboard.move(current_display_line.pretty_pv[i]);
712                 }
713                 var moves = hiddenboard.history({ verbose: true });
714                 var last_move = moves.pop();
715                 highlight_from = last_move.from;
716                 highlight_to = last_move.to;
717         } else {
718                 highlight_from = highlight_to = undefined;
719         }
720         update_highlight();
721
722         if (data['failed']) {
723                 $("#score").text("No analysis for this move");
724                 $("#pv").empty();
725                 $("#searchstats").html("&nbsp;");
726                 $("#refutationlines").empty();
727                 $("#whiteclock").empty();
728                 $("#blackclock").empty();
729                 refutation_lines = [];
730                 update_refutation_lines();
731                 clear_arrows();
732                 update_displayed_line();
733                 return;
734         }
735
736         update_clock();
737
738         // The engine id.
739         if (data['id'] && data['id']['name'] !== null) {
740                 $("#engineid").text(data['id']['name']);
741         }
742
743         // The score.
744         if (data['score'] !== null) {
745                 $("#score").text(data['score']);
746         }
747
748         // The search stats.
749         if (data['tablebase'] == 1) {
750                 $("#searchstats").text("Tablebase result");
751         } else if (data['nodes'] && data['nps'] && data['depth']) {
752                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
753                 if (data['seldepth']) {
754                         stats += ' (' + data['seldepth'] + ' selective)';
755                 }
756                 if (data['tbhits'] && data['tbhits'] > 0) {
757                         if (data['tbhits'] == 1) {
758                                 stats += ', one Syzygy hit';
759                         } else {
760                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
761                         }
762                 }
763
764                 $("#searchstats").text(stats);
765         } else {
766                 $("#searchstats").text("");
767         }
768
769         // Update the board itself.
770         fen = data['position']['fen'];
771         update_displayed_line();
772
773         // Print the PV.
774         $("#pv").html(add_pv(data['position']['fen'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
775
776         // Update the PV arrow.
777         clear_arrows();
778         if (data['pv_uci'].length >= 1) {
779                 // draw a continuation arrow as long as it's the same piece
780                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
781                         var from = data['pv_uci'][i].substr(0, 2);
782                         var to = data['pv_uci'][i].substr(2,4);
783                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
784                              interfering_arrow(from, to)) {
785                                 break;
786                         }
787                         create_arrow(from, to, '#f66', 6, 20);
788                 }
789
790                 var alt_moves = find_nonstupid_moves(data, 30);
791                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
792                         create_arrow(alt_moves[i].substr(0, 2),
793                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
794                 }
795         }
796
797         // See if all semi-reasonable moves have only one possible response.
798         if (data['pv_uci'].length >= 2) {
799                 var nonstupid_moves = find_nonstupid_moves(data, 300);
800                 var response = data['pv_uci'][1];
801                 for (var i = 0; i < nonstupid_moves.length; ++i) {
802                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
803                                 // ignore the PV move for refutation lines.
804                                 continue;
805                         }
806                         if (!data['refutation_lines'] ||
807                             !data['refutation_lines'][nonstupid_moves[i]] ||
808                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
809                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
810                                 // Incomplete PV, abort.
811                                 response = undefined;
812                                 break;
813                         }
814                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
815                         if (response !== this_response) {
816                                 // Different response depending on lines, abort.
817                                 response = undefined;
818                                 break;
819                         }
820                 }
821
822                 if (nonstupid_moves.length > 0 && response !== undefined) {
823                         create_arrow(response.substr(0, 2),
824                                      response.substr(2, 2), '#66f', 6, 20);
825                 }
826         }
827
828         // Update the refutation lines.
829         fen = data['position']['fen'];
830         move_num = data['position']['move_num'];
831         toplay = data['position']['toplay'];
832         refutation_lines = data['refutation_lines'];
833         update_refutation_lines();
834 }
835
836 /**
837  * @param {number} num_viewers
838  */
839 var update_num_viewers = function(num_viewers) {
840         if (num_viewers === null) {
841                 $("#numviewers").text("");
842         } else if (num_viewers == 1) {
843                 $("#numviewers").text("You are the only current viewer");
844         } else {
845                 $("#numviewers").text(num_viewers + " current viewers");
846         }
847 }
848
849 var update_clock = function() {
850         clearTimeout(clock_timer);
851
852         var data = displayed_analysis_data || current_analysis_data;
853         if (data['position']) {
854                 var result = data['position']['result'];
855                 if (result === '1-0') {
856                         $("#whiteclock").text("1");
857                         $("#blackclock").text("0");
858                         $("#whiteclock").removeClass("running-clock");
859                         $("#blackclock").removeClass("running-clock");
860                         return;
861                 }
862                 if (result === '1/2-1/2') {
863                         $("#whiteclock").text("1/2");
864                         $("#blackclock").text("1/2");
865                         $("#whiteclock").removeClass("running-clock");
866                         $("#blackclock").removeClass("running-clock");
867                         return;
868                 }       
869                 if (result === '0-1') {
870                         $("#whiteclock").text("0");
871                         $("#blackclock").text("1");
872                         $("#whiteclock").removeClass("running-clock");
873                         $("#blackclock").removeClass("running-clock");
874                         return;
875                 }
876         }
877
878         var white_clock = "";
879         var black_clock = "";
880
881         // Static clocks.
882         if (data['position'] &&
883             data['position']['white_clock'] &&
884             data['position']['black_clock']) {
885                 white_clock = data['position']['white_clock'].replace(/:[0-5][0-9]$/, "");
886                 black_clock = data['position']['black_clock'].replace(/:[0-5][0-9]$/, "");
887         }
888
889         // Dynamic clock (only one, obviously).
890         var color;
891         if (data['position']['white_clock_target']) {
892                 color = "white";
893                 $("#whiteclock").addClass("running-clock");
894                 $("#blackclock").removeClass("running-clock");
895         } else if (data['position']['black_clock_target']) {
896                 color = "black";
897                 $("#whiteclock").removeClass("running-clock");
898                 $("#blackclock").addClass("running-clock");
899         } else {
900                 $("#whiteclock").removeClass("running-clock");
901                 $("#blackclock").removeClass("running-clock");
902         }
903         if (color) {
904                 var now = new Date().getTime() + client_clock_offset_ms;
905                 var remaining_ms = data['position'][color + '_clock_target'] * 1000 - now;
906                 if (color === "white") {
907                         white_clock = format_clock(remaining_ms);
908                 } else {
909                         black_clock = format_clock(remaining_ms);
910                 }
911
912                 // See when the clock will change next, and update right after that.
913                 var next_update_ms = remaining_ms % 60000 + 100;
914                 clock_timer = setTimeout(update_clock, next_update_ms);
915         }
916
917         $("#whiteclock").text(white_clock);
918         $("#blackclock").text(black_clock);
919 }
920
921 /**
922  * @param {Number} remaining_ms
923  */
924 var format_clock = function(remaining_ms) {
925         if (remaining_ms <= 0) {
926                 return "00:00";
927         }
928
929         var remaining = Math.floor(remaining_ms / 1000);
930         var seconds = remaining % 60;
931         remaining = (remaining - seconds) / 60;
932         var minutes = remaining % 60;
933         remaining = (remaining - minutes) / 60;
934         var hours = remaining;
935         return format_2d(hours) + ":" + format_2d(minutes);
936 }
937
938 /**
939  * @param {Number} x
940  */
941 var format_2d = function(x) {
942         if (x >= 10) {
943                 return x;
944         } else {
945                 return "0" + x;
946         }
947 }
948
949 /**
950  * @param {string} move
951  * @param {Number} move_num
952  * @param {boolean} white_to_play
953  */
954 var format_move_with_number = function(move, move_num, white_to_play) {
955         var ret;
956         if (white_to_play) {
957                 ret = (move_num - 1) + '… ';
958         } else {
959                 ret = move_num + '. ';
960         }
961         ret += move;
962         return ret;
963 }
964
965 /**
966  * @param {boolean} sort_by_score
967  */
968 var resort_refutation_lines = function(sort_by_score) {
969         sort_refutation_lines_by_score = sort_by_score;
970         if (supports_html5_storage()) {
971                 localStorage['sort_refutation_lines_by_score'] = sort_by_score ? 1 : 0;
972         }
973         update_refutation_lines();
974 }
975 window['resort_refutation_lines'] = resort_refutation_lines;
976
977 /**
978  * @param {boolean} truncate_history
979  */
980 var set_truncate_history = function(truncate_history) {
981         truncate_display_history = truncate_history;
982         update_refutation_lines();
983 }
984 window['set_truncate_history'] = set_truncate_history;
985
986 /**
987  * @param {number} line_num
988  * @param {number} move_num
989  */
990 var show_line = function(line_num, move_num) {
991         if (line_num == -1) {
992                 current_display_line = null;
993                 current_display_move = null;
994                 if (displayed_analysis_data) {
995                         // TODO: Support exiting to history position if we are in an
996                         // analysis line of a history position.
997                         displayed_analysis_data = null;
998                         update_board(current_analysis_data, displayed_analysis_data);
999                 }
1000         } else {
1001                 current_display_line = display_lines[line_num];
1002                 current_display_move = move_num;
1003         }
1004         current_display_line_is_history = (line_num == 0);
1005
1006         update_historic_analysis();
1007         update_displayed_line();
1008         update_highlight();
1009         redraw_arrows();
1010 }
1011 window['show_line'] = show_line;
1012
1013 var prev_move = function() {
1014         if (current_display_move > -1) {
1015                 --current_display_move;
1016         }
1017         update_historic_analysis();
1018         update_displayed_line();
1019 }
1020 window['prev_move'] = prev_move;
1021
1022 var next_move = function() {
1023         if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
1024                 ++current_display_move;
1025         }
1026         update_historic_analysis();
1027         update_displayed_line();
1028 }
1029 window['next_move'] = next_move;
1030
1031 var update_historic_analysis = function() {
1032         if (!current_display_line_is_history) {
1033                 return;
1034         }
1035         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1036                 displayed_analysis_data = null;
1037                 update_board(current_analysis_data, displayed_analysis_data);
1038         }
1039
1040         // Fetch old analysis for this line if it exists.
1041         var hiddenboard = new Chess();
1042         for (var i = 0; i <= current_display_move; ++i) {
1043                 hiddenboard.move(current_display_line.pretty_pv[i]);
1044         }
1045         var filename = "/history/move" + (current_display_move + 1) + "-" +
1046                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
1047
1048         $.ajax({
1049                 url: filename
1050         }).done(function(data, textstatus, xhr) {
1051                 displayed_analysis_data = data;
1052                 update_board(current_analysis_data, displayed_analysis_data);
1053         }).fail(function() {
1054                 displayed_analysis_data = {'failed': true};
1055                 update_board(current_analysis_data, displayed_analysis_data);
1056         });
1057 }
1058
1059 var update_displayed_line = function() {
1060         if (highlighted_move !== null) {
1061                 highlighted_move.removeClass('highlight'); 
1062         }
1063         if (current_display_line === null) {
1064                 $("#linenav").hide();
1065                 $("#linemsg").show();
1066                 board.position(fen);
1067                 return;
1068         }
1069
1070         $("#linenav").show();
1071         $("#linemsg").hide();
1072
1073         if (current_display_move <= 0) {
1074                 $("#prevmove").html("Previous");
1075         } else {
1076                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
1077         }
1078         if (current_display_move == current_display_line.pretty_pv.length - 1) {
1079                 $("#nextmove").html("Next");
1080         } else {
1081                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
1082         }
1083
1084         var hiddenboard = new Chess();
1085         hiddenboard.load(current_display_line.start_fen);
1086         for (var i = 0; i <= current_display_move; ++i) {
1087                 hiddenboard.move(current_display_line.pretty_pv[i]);
1088         }
1089
1090         highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
1091         highlighted_move.addClass('highlight'); 
1092
1093         board.position(hiddenboard.fen());
1094 }
1095
1096 /**
1097  * @param {boolean} param_enable_sound
1098  */
1099 var set_sound = function(param_enable_sound) {
1100         enable_sound = param_enable_sound;
1101         if (enable_sound) {
1102                 $("#soundon").html("<strong>On</strong>");
1103                 $("#soundoff").html("<a href=\"javascript:set_sound(false)\">Off</a>");
1104
1105                 // Seemingly at least Firefox prefers MP3 over Opus; tell it otherwise,
1106                 // and also preload the file since the user has selected audio.
1107                 var ding = document.getElementById('ding');
1108                 if (ding && ding.canPlayType && ding.canPlayType('audio/ogg; codecs="opus"') === 'probably') {
1109                         ding.src = 'ding.opus';
1110                         ding.load();
1111                 }
1112         } else {
1113                 $("#soundon").html("<a href=\"javascript:set_sound(true)\">On</a>");
1114                 $("#soundoff").html("<strong>Off</strong>");
1115         }
1116         if (supports_html5_storage()) {
1117                 localStorage['enable_sound'] = enable_sound ? 1 : 0;
1118         }
1119 }
1120 window['set_sound'] = set_sound;
1121
1122 var init = function() {
1123         unique = get_unique();
1124
1125         // Load settings from HTML5 local storage if available.
1126         if (supports_html5_storage() && localStorage['enable_sound']) {
1127                 set_sound(parseInt(localStorage['enable_sound']));
1128         } else {
1129                 set_sound(false);
1130         }
1131         if (supports_html5_storage() && localStorage['sort_refutation_lines_by_score']) {
1132                 sort_refutation_lines_by_score = parseInt(localStorage['sort_refutation_lines_by_score']);
1133         } else {
1134                 sort_refutation_lines_by_score = true;
1135         }
1136
1137         // Create board.
1138         board = new window.ChessBoard('board', 'start');
1139
1140         request_update();
1141         $(window).resize(function() {
1142                 board.resize();
1143                 update_highlight();
1144                 redraw_arrows();
1145         });
1146         $(window).keyup(function(event) {
1147                 if (event.which == 39) {
1148                         next_move();
1149                 } else if (event.which == 37) {
1150                         prev_move();
1151                 }
1152         });
1153 };
1154 $(document).ready(init);
1155
1156 })();