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