]> git.sesse.net Git - remoteglot/blob - www/js/remoteglot.js
37c6b87fca488a9d5b87483e32142ab2e80198d6
[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 /** The current position on the board, represented as a FEN string.
69  * @type {?string}
70  * @private
71  */
72 var fen = null;
73
74 /** @typedef {{
75  *    start_fen: string,
76  *    uci_pv: Array.<string>,
77  *    pretty_pv: Array.<string>,
78  *    line_num: number
79  * }} DisplayLine
80  */
81
82 /** @type {Array.<DisplayLine>}
83  * @private
84  */
85 var display_lines = [];
86
87 /** @type {?DisplayLine} @private */
88 var current_display_line = null;
89
90 /** @type {boolean} @private */
91 var current_display_line_is_history = false;
92
93 /** @type {?number} @private */
94 var current_display_move = null;
95
96 var supports_html5_storage = function() {
97         try {
98                 return 'localStorage' in window && window['localStorage'] !== null;
99         } catch (e) {
100                 return false;
101         }
102 }
103
104 // Make the unique token persistent so people refreshing the page won't count twice.
105 // Of course, you can never fully protect against people deliberately wanting to spam.
106 var get_unique = function() {
107         var use_local_storage = supports_html5_storage();
108         if (use_local_storage && localStorage['unique']) {
109                 return localStorage['unique'];
110         }
111         var unique = Math.random();
112         if (use_local_storage) {
113                 localStorage['unique'] = unique;
114         }
115         return unique;
116 }
117
118 var request_update = function() {
119         $.ajax({
120                 url: "/analysis.pl?ims=" + ims + "&unique=" + unique
121         }).done(function(data, textstatus, xhr) {
122                 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
123                 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
124                 current_analysis_data = data;
125                 update_board(current_analysis_data, displayed_analysis_data);
126                 update_num_viewers(num_viewers);
127
128                 // Next update.
129                 setTimeout(function() { request_update(); }, 100);
130         }).fail(function() {
131                 // Wait ten seconds, then try again.
132                 setTimeout(function() { request_update(); }, 10000);
133         });
134 }
135
136 var clear_arrows = function() {
137         for (var i = 0; i < arrows.length; ++i) {
138                 if (arrows[i].svg) {
139                         arrows[i].svg.parentElement.removeChild(arrows[i].svg);
140                         delete arrows[i].svg;
141                 }
142         }
143         arrows = [];
144
145         occupied_by_arrows = [];
146         for (var y = 0; y < 8; ++y) {
147                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
148         }
149 }
150
151 var redraw_arrows = function() {
152         for (var i = 0; i < arrows.length; ++i) {
153                 position_arrow(arrows[i]);
154         }
155 }
156
157 /** @param {!number} x
158  * @return {!number}
159  */
160 var sign = function(x) {
161         if (x > 0) {
162                 return 1;
163         } else if (x < 0) {
164                 return -1;
165         } else {
166                 return 0;
167         }
168 }
169
170 /** See if drawing this arrow on the board would cause unduly amount of confusion.
171  * @param {!string} from The square the arrow is from (e.g. e4).
172  * @param {!string} to The square the arrow is to (e.g. e4).
173  * @return {boolean}
174  */
175 var interfering_arrow = function(from, to) {
176         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
177         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
178         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
179         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
180
181         occupied_by_arrows[from_row][from_col] = true;
182
183         // Knight move: Just check that we haven't been at the destination before.
184         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
185             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
186                 return occupied_by_arrows[to_row][to_col];
187         }
188
189         // Sliding piece: Check if anything except the from-square is seen before.
190         var dx = sign(to_col - from_col);
191         var dy = sign(to_row - from_row);
192         var x = from_col;
193         var y = from_row;
194         do {
195                 x += dx;
196                 y += dy;
197                 if (occupied_by_arrows[y][x]) {
198                         return true;
199                 }
200                 occupied_by_arrows[y][x] = true;
201         } while (x != to_col || y != to_row);
202
203         return false;
204 }
205
206 /** Find a point along the coordinate system given by the given line,
207  * <t> units forward from the start of the line, <u> units to the right of it.
208  * @param {!number} x1
209  * @param {!number} x2
210  * @param {!number} y1
211  * @param {!number} y2
212  * @param {!number} t
213  * @param {!number} u
214  * @return {!string} The point in "x y" form, suitable for SVG paths.
215  */
216 var point_from_start = function(x1, y1, x2, y2, t, u) {
217         var dx = x2 - x1;
218         var dy = y2 - y1;
219
220         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
221         dx *= norm;
222         dy *= norm;
223
224         var x = x1 + dx * t + dy * u;
225         var y = y1 + dy * t - dx * u;
226         return x + " " + y;
227 }
228
229 /** Find a point along the coordinate system given by the given line,
230  * <t> units forward from the end of the line, <u> units to the right of it.
231  * @param {!number} x1
232  * @param {!number} x2
233  * @param {!number} y1
234  * @param {!number} y2
235  * @param {!number} t
236  * @param {!number} u
237  * @return {!string} The point in "x y" form, suitable for SVG paths.
238  */
239 var point_from_end = function(x1, y1, x2, y2, t, u) {
240         var dx = x2 - x1;
241         var dy = y2 - y1;
242
243         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
244         dx *= norm;
245         dy *= norm;
246
247         var x = x2 + dx * t + dy * u;
248         var y = y2 + dy * t - dx * u;
249         return x + " " + y;
250 }
251
252 var position_arrow = function(arrow) {
253         if (arrow.svg) {
254                 arrow.svg.parentElement.removeChild(arrow.svg);
255                 delete arrow.svg;
256         }
257         if (current_display_line !== null) {
258                 return;
259         }
260
261         var pos = $(".square-a8").position();
262
263         var zoom_factor = $("#board").width() / 400.0;
264         var line_width = arrow.line_width * zoom_factor;
265         var arrow_size = arrow.arrow_size * zoom_factor;
266
267         var square_width = $(".square-a8").width();
268         var from_y = (7 - arrow.from_row + 0.5)*square_width;
269         var to_y = (7 - arrow.to_row + 0.5)*square_width;
270         var from_x = (arrow.from_col + 0.5)*square_width;
271         var to_x = (arrow.to_col + 0.5)*square_width;
272
273         var SVG_NS = "http://www.w3.org/2000/svg";
274         var XHTML_NS = "http://www.w3.org/1999/xhtml";
275         var svg = document.createElementNS(SVG_NS, "svg");
276         svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
277         svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
278         svg.setAttribute("style", "position: absolute");
279         svg.setAttribute("position", "absolute");
280         svg.setAttribute("version", "1.1");
281         svg.setAttribute("class", "c1");
282         svg.setAttribute("xmlns", XHTML_NS);
283
284         var x1 = from_x;
285         var y1 = from_y;
286         var x2 = to_x;
287         var y2 = to_y;
288
289         // Draw the line.
290         var outline = document.createElementNS(SVG_NS, "path");
291         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));
292         outline.setAttribute("xmlns", XHTML_NS);
293         outline.setAttribute("stroke", "#666");
294         outline.setAttribute("stroke-width", line_width + 2);
295         outline.setAttribute("fill", "none");
296         svg.appendChild(outline);
297
298         var path = document.createElementNS(SVG_NS, "path");
299         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));
300         path.setAttribute("xmlns", XHTML_NS);
301         path.setAttribute("stroke", arrow.fg_color);
302         path.setAttribute("stroke-width", line_width);
303         path.setAttribute("fill", "none");
304         svg.appendChild(path);
305
306         // Then the arrow head.
307         var head = document.createElementNS(SVG_NS, "path");
308         head.setAttribute("d",
309                 "M " +  point_from_end(x1, y1, x2, y2, 0, 0) +
310                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
311                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
312                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
313                 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
314         head.setAttribute("xmlns", XHTML_NS);
315         head.setAttribute("stroke", "#000");
316         head.setAttribute("stroke-width", "1");
317         head.setAttribute("fill", arrow.fg_color);
318         svg.appendChild(head);
319
320         $(svg).css({ top: pos.top, left: pos.left });
321         document.body.appendChild(svg);
322         arrow.svg = svg;
323 }
324
325 /**
326  * @param {!string} from_square
327  * @param {!string} to_square
328  * @param {!string} fg_color
329  * @param {number} line_width
330  * @param {number} arrow_size
331  */
332 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
333         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
334         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
335         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
336         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
337
338         // Create arrow.
339         var arrow = {
340                 from_col: from_col,
341                 from_row: from_row,
342                 to_col: to_col,
343                 to_row: to_row,
344                 line_width: line_width,
345                 arrow_size: arrow_size,
346                 fg_color: fg_color
347         };
348
349         position_arrow(arrow);
350         arrows.push(arrow);
351 }
352
353 var compare_by_sort_key = function(refutation_lines, a, b) {
354         var ska = refutation_lines[a]['sort_key'];
355         var skb = refutation_lines[b]['sort_key'];
356         if (ska < skb) return -1;
357         if (ska > skb) return 1;
358         return 0;
359 };
360
361 var compare_by_score = function(refutation_lines, a, b) {
362         var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
363         var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
364         return sa - sb;
365 }
366
367 /**
368  * Fake multi-PV using the refutation lines. Find all “relevant” moves,
369  * sorted by quality, descending.
370  *
371  * @param {!Object} data
372  * @param {number} margin The maximum number of centipawns worse than the
373  *     best move can be and still be included.
374  * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
375  *     moves, in score order.
376  */
377 var find_nonstupid_moves = function(data, margin) {
378         // First of all, if there are any moves that are more than 0.5 ahead of
379         // the primary move, the refutation lines are probably bunk, so just
380         // kill them all. 
381         var best_score = undefined;
382         var pv_score = undefined;
383         for (var move in data['refutation_lines']) {
384                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
385                 if (move == data['pv_uci'][0]) {
386                         pv_score = score;
387                 }
388                 if (best_score === undefined || score > best_score) {
389                         best_score = score;
390                 }
391                 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
392                         return [];
393                 }
394         }
395
396         if (best_score - pv_score > 50) {
397                 return [];
398         }
399
400         // Now find all moves that are within “margin” of the best score.
401         // The PV move will always be first.
402         var moves = [];
403         for (var move in data['refutation_lines']) {
404                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
405                 if (move != data['pv_uci'][0] && best_score - score <= margin) {
406                         moves.push(move);
407                 }
408         }
409         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
410         moves.unshift(data['pv_uci'][0]);
411
412         return moves;
413 }
414
415 /**
416  * @param {number} x
417  * @return {!string}
418  */
419 var thousands = function(x) {
420         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
421 }
422
423 /**
424  * @param {!string} fen
425  * @param {Array.<string>} uci_pv
426  * @param {number} move_num
427  * @param {!string} toplay
428  * @param {number=} opt_limit
429  * @param {boolean=} opt_showlast
430  */
431 var add_pv = function(fen, uci_pv, move_num, toplay, opt_limit, opt_showlast) {
432         var hiddenboard = new Chess();
433         hiddenboard.load(fen);
434         for (var i = 0; i < uci_pv.length; ++i) {
435                 hiddenboard.move(ucimove_to_chessjs_move(uci_pv[i]));
436         }
437         var pretty_pv = hiddenboard.history();
438
439         display_lines.push({
440                 start_fen: fen,
441                 uci_pv: uci_pv,
442                 pretty_pv: pretty_pv,
443                 line_number: display_lines.length
444         });
445         return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
446 }
447
448 /**
449  * @param {number} line_num
450  * @param {Array.<string>} pretty_pv
451  * @param {number} move_num
452  * @param {!string} toplay
453  * @param {number=} opt_limit
454  * @param {boolean=} opt_showlast
455  */
456 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
457         var pv = '';
458         var i = 0;
459         if (opt_limit && opt_showlast && pretty_pv.length > opt_limit) {
460                 // Truncate the PV at the beginning (instead of at the end).
461                 // We assume here that toplay is 'W'. We also assume that if
462                 // opt_showlast is set, then it is the history, and thus,
463                 // the UI should be to expand the history.
464                 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
465                 i = pretty_pv.length - opt_limit;
466                 if (i % 2 == 1) {
467                         ++i;
468                 }
469                 move_num += i / 2;
470         } else if (toplay == 'B' && pretty_pv.length > 0) {
471                 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
472                 pv = move_num + '. … ' + move;
473                 toplay = 'W';
474                 ++i;
475                 ++move_num;
476         }
477         for ( ; i < pretty_pv.length; ++i) {
478                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
479
480                 if (toplay == 'W') {
481                         if (i > opt_limit && !opt_showlast) {
482                                 return pv + ' (…)';
483                         }
484                         if (pv != '') {
485                                 pv += ' ';
486                         }
487                         pv += move_num + '. ' + move;
488                         ++move_num;
489                         toplay = 'B';
490                 } else {
491                         pv += ' ' + move;
492                         toplay = 'W';
493                 }
494         }
495         return pv;
496 }
497
498 var update_highlight = function() {
499         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
500         if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
501                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
502                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
503         }
504 }
505
506 var update_history = function() {
507         if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
508                 $("#history").html("No history");
509         } else if (truncate_display_history) {
510                 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
511         } else {
512                 $("#history").html(
513                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
514                         print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
515         }
516 }
517
518 /**
519  * @param {!boolean} truncate_history
520  */
521 var collapse_history = function(truncate_history) {
522         truncate_display_history = truncate_history;
523         update_history();
524 }
525 window['collapse_history'] = collapse_history;
526
527 var update_refutation_lines = function() {
528         if (fen === null) {
529                 return;
530         }
531         if (display_lines.length > 2) {
532                 display_lines = [ display_lines[0], display_lines[1] ];
533         }
534
535         var tbl = $("#refutationlines");
536         tbl.empty();
537
538         var moves = [];
539         for (var move in refutation_lines) {
540                 moves.push(move);
541         }
542         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
543         moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
544         for (var i = 0; i < moves.length; ++i) {
545                 var line = refutation_lines[moves[i]];
546
547                 var tr = document.createElement("tr");
548
549                 var move_td = document.createElement("td");
550                 tr.appendChild(move_td);
551                 $(move_td).addClass("move");
552                 if (line['pv_uci'].length == 0) {
553                         $(move_td).text(line['pretty_move']);
554                 } else {
555                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
556                         $(move_td).html(move);
557                 }
558
559                 var score_td = document.createElement("td");
560                 tr.appendChild(score_td);
561                 $(score_td).addClass("score");
562                 $(score_td).text(line['pretty_score']);
563
564                 var depth_td = document.createElement("td");
565                 tr.appendChild(depth_td);
566                 $(depth_td).addClass("depth");
567                 $(depth_td).text("d" + line['depth']);
568
569                 var pv_td = document.createElement("td");
570                 tr.appendChild(pv_td);
571                 $(pv_td).addClass("pv");
572                 $(pv_td).html(add_pv(fen, line['pv_uci'], move_num, toplay, 10));
573
574                 tbl.append(tr);
575         }
576
577         // Make one of the links clickable and the other nonclickable.
578         if (sort_refutation_lines_by_score) {
579                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
580                 $("#sortbyscore1").html("<strong>Score</strong>");
581         } else {
582                 $("#sortbyscore0").html("<strong>Move</strong>");
583                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
584         }
585 }
586
587 /**
588  * @param {Object} data
589  * @param {?Object} display_data
590  */
591 var update_board = function(current_data, display_data) {
592         var data = display_data || current_data;
593
594         display_lines = [];
595
596         // Print the history. This is pretty much the only thing that's
597         // unconditionally taken from current_data (we're not interested in
598         // historic history).
599         if (current_data['position']['history']) {
600                 add_pv('start', current_data['position']['history'], 1, 'W', 8, true);
601         } else {
602                 display_lines.push(null);
603         }
604         update_history();
605
606         // The headline. Names are always fetched from current_data;
607         // the rest can depend a bit.
608         var headline;
609         if (current_data &&
610             current_data['position']['player_w'] && current_data['position']['player_b']) {
611                 headline = current_data['position']['player_w'] + '–' +
612                         current_data['position']['player_b'] + ', analysis';
613         } else {
614                 headline = 'Analysis';
615         }
616
617         var last_move;
618         if (display_data) {
619                 // Displaying some non-current position, pick out the last move
620                 // from the history. This will work even if the fetch failed.
621                 last_move = format_move_with_number(
622                         current_display_line.pretty_pv[current_display_move],
623                         Math.floor((current_display_move + 1) / 2) + 1,
624                         (current_display_move % 2 == 1));
625                 headline += ' after ' + last_move;
626         } else if (data['position']['last_move'] !== 'none') {
627                 last_move = format_move_with_number(
628                         data['position']['last_move'],
629                         data['position']['move_num'],
630                         data['position']['toplay'] == 'W');
631                 headline += ' after ' + last_move;
632         } else {
633                 last_move = null;
634         }
635         $("#headline").text(headline);
636
637         // The <title> contains a very brief headline.
638         var title_elems = [];
639         if (data['short_score'] !== undefined && data['short_score'] !== null) {
640                 title_elems.push(data['short_score']);
641         }
642         if (last_move !== null) {
643                 title_elems.push(last_move);
644         }
645
646         if (title_elems.length != 0) {
647                 document.title = '(' + title_elems.join(', ') + ') analysis.sesse.net';
648         } else {
649                 document.title = 'analysis.sesse.net';
650         }
651
652         if (data['failed']) {
653                 $("#score").text("No analysis for this move");
654                 $("#pv").empty();
655                 $("#searchstats").html("&nbsp;");
656                 $("#refutationlines").empty();
657                 refutation_lines = [];
658                 update_refutation_lines();
659                 return;
660         }
661
662         // The engine id.
663         if (data['id'] && data['id']['name'] !== null) {
664                 $("#engineid").text(data['id']['name']);
665         }
666
667         // The score.
668         if (data['score'] !== null) {
669                 $("#score").text(data['score']);
670         }
671
672         // The search stats.
673         if (data['tablebase'] == 1) {
674                 $("#searchstats").text("Tablebase result");
675         } else if (data['nodes'] && data['nps'] && data['depth']) {
676                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
677                 if (data['seldepth']) {
678                         stats += ' (' + data['seldepth'] + ' selective)';
679                 }
680                 if (data['tbhits'] && data['tbhits'] > 0) {
681                         if (data['tbhits'] == 1) {
682                                 stats += ', one Syzygy hit';
683                         } else {
684                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
685                         }
686                 }
687
688                 $("#searchstats").text(stats);
689         } else {
690                 $("#searchstats").text("");
691         }
692
693         // Update the board itself.
694         fen = data['position']['fen'];
695         update_displayed_line();
696
697         if (data['position']['last_move_uci']) {
698                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
699                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
700         } else {
701                 highlight_from = highlight_to = undefined;
702         }
703         update_highlight();
704
705         // Print the PV.
706         $("#pv").html(add_pv(data['position']['fen'], data['pv_uci'], data['position']['move_num'], data['position']['toplay']));
707
708         // Update the PV arrow.
709         clear_arrows();
710         if (data['pv_uci'].length >= 1) {
711                 // draw a continuation arrow as long as it's the same piece
712                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
713                         var from = data['pv_uci'][i].substr(0, 2);
714                         var to = data['pv_uci'][i].substr(2,4);
715                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
716                              interfering_arrow(from, to)) {
717                                 break;
718                         }
719                         create_arrow(from, to, '#f66', 6, 20);
720                 }
721
722                 var alt_moves = find_nonstupid_moves(data, 30);
723                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
724                         create_arrow(alt_moves[i].substr(0, 2),
725                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
726                 }
727         }
728
729         // See if all semi-reasonable moves have only one possible response.
730         if (data['pv_uci'].length >= 2) {
731                 var nonstupid_moves = find_nonstupid_moves(data, 300);
732                 var response = data['pv_uci'][1];
733                 for (var i = 0; i < nonstupid_moves.length; ++i) {
734                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
735                                 // ignore the PV move for refutation lines.
736                                 continue;
737                         }
738                         if (!data['refutation_lines'] ||
739                             !data['refutation_lines'][nonstupid_moves[i]] ||
740                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
741                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
742                                 // Incomplete PV, abort.
743                                 response = undefined;
744                                 break;
745                         }
746                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
747                         if (response !== this_response) {
748                                 // Different response depending on lines, abort.
749                                 response = undefined;
750                                 break;
751                         }
752                 }
753
754                 if (nonstupid_moves.length > 0 && response !== undefined) {
755                         create_arrow(response.substr(0, 2),
756                                      response.substr(2, 2), '#66f', 6, 20);
757                 }
758         }
759
760         // Update the refutation lines.
761         fen = data['position']['fen'];
762         move_num = data['position']['move_num'];
763         toplay = data['position']['toplay'];
764         refutation_lines = data['refutation_lines'];
765         update_refutation_lines();
766 }
767
768 /**
769  * @param {number} num_viewers
770  */
771 var update_num_viewers = function(num_viewers) {
772         if (num_viewers === null) {
773                 $("#numviewers").text("");
774         } else if (num_viewers == 1) {
775                 $("#numviewers").text("You are the only current viewer");
776         } else {
777                 $("#numviewers").text(num_viewers + " current viewers");
778         }
779 }
780
781 /**
782  * @param {string} move
783  * @param {Number} move_num
784  * @param {boolean} white_to_play
785  */
786 var format_move_with_number = function(move, move_num, white_to_play) {
787         var ret;
788         if (white_to_play) {
789                 ret = (move_num - 1) + '… ';
790         } else {
791                 ret = move_num + '. ';
792         }
793         ret += move;
794         return ret;
795 }
796
797 /**
798  * @param {boolean} sort_by_score
799  */
800 var resort_refutation_lines = function(sort_by_score) {
801         sort_refutation_lines_by_score = sort_by_score;
802         update_refutation_lines();
803 }
804 window['resort_refutation_lines'] = resort_refutation_lines;
805
806 /**
807  * @param {boolean} truncate_history
808  */
809 var set_truncate_history = function(truncate_history) {
810         truncate_display_history = truncate_history;
811         update_refutation_lines();
812 }
813 window['set_truncate_history'] = set_truncate_history;
814
815 /**
816  * @param {number} line_num
817  * @param {number} move_num
818  */
819 var show_line = function(line_num, move_num) {
820         if (line_num == -1) {
821                 current_display_line = null;
822                 current_display_move = null;
823                 if (displayed_analysis_data) {
824                         // TODO: Support exiting to history position if we are in an
825                         // analysis line of a history position.
826                         displayed_analysis_data = null;
827                         update_board(current_analysis_data, displayed_analysis_data);
828                 }
829         } else {
830                 current_display_line = display_lines[line_num];
831                 current_display_move = move_num;
832         }
833         current_display_line_is_history = (line_num == 0);
834
835         update_historic_analysis();
836         update_displayed_line();
837         update_highlight();
838         redraw_arrows();
839 }
840 window['show_line'] = show_line;
841
842 var prev_move = function() {
843         if (current_display_move > -1) {
844                 --current_display_move;
845         }
846         update_historic_analysis();
847         update_displayed_line();
848 }
849 window['prev_move'] = prev_move;
850
851 var next_move = function() {
852         if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
853                 ++current_display_move;
854         }
855         update_historic_analysis();
856         update_displayed_line();
857 }
858 window['next_move'] = next_move;
859
860 var update_historic_analysis = function() {
861         if (!current_display_line_is_history) {
862                 return;
863         }
864         if (current_display_move == current_display_line.pretty_pv.length - 1) {
865                 displayed_analysis_data = null;
866                 update_board(current_analysis_data, displayed_analysis_data);
867         }
868
869         // Fetch old analysis for this line if it exists.
870         var hiddenboard = new Chess();
871         for (var i = 0; i <= current_display_move; ++i) {
872                 hiddenboard.move(ucimove_to_chessjs_move(current_display_line.uci_pv[i]));
873         }
874         var filename = "/history/move" + (current_display_move + 1) + "-" +
875                 hiddenboard.fen().replace(/ /g, '_').replace(/\//g, '-') + ".json";
876
877         $.ajax({
878                 url: filename
879         }).done(function(data, textstatus, xhr) {
880                 displayed_analysis_data = data;
881                 update_board(current_analysis_data, displayed_analysis_data);
882         }).fail(function() {
883                 displayed_analysis_data = {'failed': true};
884                 update_board(current_analysis_data, displayed_analysis_data);
885         });
886 }
887
888 var update_displayed_line = function() {
889         if (highlighted_move !== null) {
890                 highlighted_move.removeClass('highlight'); 
891         }
892         if (current_display_line === null) {
893                 $("#linenav").hide();
894                 $("#linemsg").show();
895                 board.position(fen);
896                 return;
897         }
898
899         $("#linenav").show();
900         $("#linemsg").hide();
901
902         if (current_display_move <= 0) {
903                 $("#prevmove").html("Previous");
904         } else {
905                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
906         }
907         if (current_display_move == current_display_line.uci_pv.length - 1) {
908                 $("#nextmove").html("Next");
909         } else {
910                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
911         }
912
913         var hiddenboard = new Chess();
914         hiddenboard.load(current_display_line.start_fen);
915         for (var i = 0; i <= current_display_move; ++i) {
916                 hiddenboard.move(ucimove_to_chessjs_move(current_display_line.uci_pv[i]));
917         }
918
919         highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
920         highlighted_move.addClass('highlight'); 
921
922         board.position(hiddenboard.fen());
923 }
924
925 var ucimove_to_chessjs_move = function(move) {
926         var source = move.substr(0, 2);
927         var target = move.substr(2, 2);
928         var promo = move.substr(4, 1);
929
930         if (promo === '') {
931                 return { from: source, to: target };
932         } else {
933                 return { from: source, to: target, promotion: promo };
934         }
935 }
936
937 var init = function() {
938         unique = get_unique();
939
940         // Create board.
941         board = new window.ChessBoard('board', 'start');
942
943         request_update();
944         $(window).resize(function() {
945                 board.resize();
946                 update_highlight();
947                 redraw_arrows();
948         });
949         $(window).keyup(function(event) {
950                 if (event.which == 39) {
951                         next_move();
952                 } else if (event.which == 37) {
953                         prev_move();
954                 }
955         });
956 };
957 $(document).ready(init);
958
959 })();