Fix an issue where the Previous link would wrongly reappear.
[remoteglot] / www / js / remoteglot.js
1 (function() {
2
3 /** @type {window.ChessBoard} @private */
4 var board = null;
5
6 /** @type {window.ChessBoard} @private */
7 var hiddenboard = null;
8
9 /** @type {Array.<{
10  *      from_col: number,
11  *      from_row: number,
12  *      to_col: number,
13  *      to_row: number,
14  *      line_width: number,
15  *      arrow_size: number,
16  *      fg_color: string
17  * }>}
18  * @private
19  */
20 var arrows = [];
21
22 /** @type {Array.<Array.<boolean>>} */
23 var occupied_by_arrows = [];
24
25 var refutation_lines = [];
26
27 /** @type {!number} @private */
28 var move_num = 1;
29
30 /** @type {!string} @private */
31 var toplay = 'W';
32
33 /** @type {number} @private */
34 var ims = 0;
35
36 /** @type {boolean} @private */
37 var sort_refutation_lines_by_score = true;
38
39 /** @type {boolean} @private */
40 var truncate_display_history = true;
41
42 /** @type {!string|undefined} @private */
43 var highlight_from = undefined;
44
45 /** @type {!string|undefined} @private */
46 var highlight_to = undefined;
47
48 /** @type {?jQuery} @private */
49 var highlighted_move = null;
50
51 /** @type {!number} @private */
52 var unique = Math.random();
53
54 /** The current position on the board, represented as a FEN string.
55  * @type {?string}
56  * @private
57  */
58 var fen = null;
59
60 /** @typedef {{
61  *    start_fen: string,
62  *    uci_pv: Array.<string>,
63  *    pretty_pv: Array.<string>,
64  *    line_num: number
65  * }} DisplayLine
66  */
67
68 /** @type {Array.<DisplayLine>}
69  * @private
70  */
71 var display_lines = [];
72
73 /** @type {?DisplayLine} @private */
74 var current_display_line = null;
75
76 /** @type {?number} @private */
77 var current_display_move = null;
78
79 var request_update = function() {
80         $.ajax({
81                 url: "http://analysis.sesse.net/analysis.pl?ims=" + ims + "&unique=" + unique
82                 //url: "http://analysis.sesse.net:5000/analysis.pl?ims=" + ims + "&unique=" + unique
83         }).done(function(data, textstatus, xhr) {
84                 ims = xhr.getResponseHeader('X-Remoteglot-Last-Modified');
85                 var num_viewers = xhr.getResponseHeader('X-Remoteglot-Num-Viewers');
86                 update_board(data, num_viewers);
87         }).fail(function() {
88                 // Wait ten seconds, then try again.
89                 setTimeout(function() { request_update(); }, 10000);
90         });
91 }
92
93 var clear_arrows = function() {
94         for (var i = 0; i < arrows.length; ++i) {
95                 if (arrows[i].svg) {
96                         arrows[i].svg.parentElement.removeChild(arrows[i].svg);
97                         delete arrows[i].svg;
98                 }
99         }
100         arrows = [];
101
102         occupied_by_arrows = [];
103         for (var y = 0; y < 8; ++y) {
104                 occupied_by_arrows.push([false, false, false, false, false, false, false, false]);
105         }
106 }
107
108 var redraw_arrows = function() {
109         for (var i = 0; i < arrows.length; ++i) {
110                 position_arrow(arrows[i]);
111         }
112 }
113
114 /** @param {!number} x
115  * @return {!number}
116  */
117 var sign = function(x) {
118         if (x > 0) {
119                 return 1;
120         } else if (x < 0) {
121                 return -1;
122         } else {
123                 return 0;
124         }
125 }
126
127 /** See if drawing this arrow on the board would cause unduly amount of confusion.
128  * @param {!string} from The square the arrow is from (e.g. e4).
129  * @param {!string} to The square the arrow is to (e.g. e4).
130  * @return {boolean}
131  */
132 var interfering_arrow = function(from, to) {
133         var from_col = from.charCodeAt(0) - "a1".charCodeAt(0);
134         var from_row = from.charCodeAt(1) - "a1".charCodeAt(1);
135         var to_col   = to.charCodeAt(0) - "a1".charCodeAt(0);
136         var to_row   = to.charCodeAt(1) - "a1".charCodeAt(1);
137
138         occupied_by_arrows[from_row][from_col] = true;
139
140         // Knight move: Just check that we haven't been at the destination before.
141         if ((Math.abs(to_col - from_col) == 2 && Math.abs(to_row - from_row) == 1) ||
142             (Math.abs(to_col - from_col) == 1 && Math.abs(to_row - from_row) == 2)) {
143                 return occupied_by_arrows[to_row][to_col];
144         }
145
146         // Sliding piece: Check if anything except the from-square is seen before.
147         var dx = sign(to_col - from_col);
148         var dy = sign(to_row - from_row);
149         var x = from_col;
150         var y = from_row;
151         do {
152                 x += dx;
153                 y += dy;
154                 if (occupied_by_arrows[y][x]) {
155                         return true;
156                 }
157                 occupied_by_arrows[y][x] = true;
158         } while (x != to_col || y != to_row);
159
160         return false;
161 }
162
163 /** Find a point along the coordinate system given by the given line,
164  * <t> units forward from the start of the line, <u> units to the right of it.
165  * @param {!number} x1
166  * @param {!number} x2
167  * @param {!number} y1
168  * @param {!number} y2
169  * @param {!number} t
170  * @param {!number} u
171  * @return {!string} The point in "x y" form, suitable for SVG paths.
172  */
173 var point_from_start = function(x1, y1, x2, y2, t, u) {
174         var dx = x2 - x1;
175         var dy = y2 - y1;
176
177         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
178         dx *= norm;
179         dy *= norm;
180
181         var x = x1 + dx * t + dy * u;
182         var y = y1 + dy * t - dx * u;
183         return x + " " + y;
184 }
185
186 /** Find a point along the coordinate system given by the given line,
187  * <t> units forward from the end of the line, <u> units to the right of it.
188  * @param {!number} x1
189  * @param {!number} x2
190  * @param {!number} y1
191  * @param {!number} y2
192  * @param {!number} t
193  * @param {!number} u
194  * @return {!string} The point in "x y" form, suitable for SVG paths.
195  */
196 var point_from_end = function(x1, y1, x2, y2, t, u) {
197         var dx = x2 - x1;
198         var dy = y2 - y1;
199
200         var norm = 1.0 / Math.sqrt(dx * dx + dy * dy);
201         dx *= norm;
202         dy *= norm;
203
204         var x = x2 + dx * t + dy * u;
205         var y = y2 + dy * t - dx * u;
206         return x + " " + y;
207 }
208
209 var position_arrow = function(arrow) {
210         if (arrow.svg) {
211                 arrow.svg.parentElement.removeChild(arrow.svg);
212                 delete arrow.svg;
213         }
214         if (current_display_line !== null) {
215                 return;
216         }
217
218         var pos = $(".square-a8").position();
219
220         var zoom_factor = $("#board").width() / 400.0;
221         var line_width = arrow.line_width * zoom_factor;
222         var arrow_size = arrow.arrow_size * zoom_factor;
223
224         var square_width = $(".square-a8").width();
225         var from_y = (7 - arrow.from_row + 0.5)*square_width;
226         var to_y = (7 - arrow.to_row + 0.5)*square_width;
227         var from_x = (arrow.from_col + 0.5)*square_width;
228         var to_x = (arrow.to_col + 0.5)*square_width;
229
230         var SVG_NS = "http://www.w3.org/2000/svg";
231         var XHTML_NS = "http://www.w3.org/1999/xhtml";
232         var svg = document.createElementNS(SVG_NS, "svg");
233         svg.setAttribute("width", /** @type{number} */ ($("#board").width()));
234         svg.setAttribute("height", /** @type{number} */ ($("#board").height()));
235         svg.setAttribute("style", "position: absolute");
236         svg.setAttribute("position", "absolute");
237         svg.setAttribute("version", "1.1");
238         svg.setAttribute("class", "c1");
239         svg.setAttribute("xmlns", XHTML_NS);
240
241         var x1 = from_x;
242         var y1 = from_y;
243         var x2 = to_x;
244         var y2 = to_y;
245
246         // Draw the line.
247         var outline = document.createElementNS(SVG_NS, "path");
248         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));
249         outline.setAttribute("xmlns", XHTML_NS);
250         outline.setAttribute("stroke", "#666");
251         outline.setAttribute("stroke-width", line_width + 2);
252         outline.setAttribute("fill", "none");
253         svg.appendChild(outline);
254
255         var path = document.createElementNS(SVG_NS, "path");
256         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));
257         path.setAttribute("xmlns", XHTML_NS);
258         path.setAttribute("stroke", arrow.fg_color);
259         path.setAttribute("stroke-width", line_width);
260         path.setAttribute("fill", "none");
261         svg.appendChild(path);
262
263         // Then the arrow head.
264         var head = document.createElementNS(SVG_NS, "path");
265         head.setAttribute("d",
266                 "M " +  point_from_end(x1, y1, x2, y2, 0, 0) +
267                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, -arrow_size / 2) +
268                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size * .623, 0.0) +
269                 " L " + point_from_end(x1, y1, x2, y2, -arrow_size, arrow_size / 2) +
270                 " L " + point_from_end(x1, y1, x2, y2, 0, 0));
271         head.setAttribute("xmlns", XHTML_NS);
272         head.setAttribute("stroke", "#000");
273         head.setAttribute("stroke-width", "1");
274         head.setAttribute("fill", arrow.fg_color);
275         svg.appendChild(head);
276
277         $(svg).css({ top: pos.top, left: pos.left });
278         document.body.appendChild(svg);
279         arrow.svg = svg;
280 }
281
282 /**
283  * @param {!string} from_square
284  * @param {!string} to_square
285  * @param {!string} fg_color
286  * @param {number} line_width
287  * @param {number} arrow_size
288  */
289 var create_arrow = function(from_square, to_square, fg_color, line_width, arrow_size) {
290         var from_col = from_square.charCodeAt(0) - "a1".charCodeAt(0);
291         var from_row = from_square.charCodeAt(1) - "a1".charCodeAt(1);
292         var to_col   = to_square.charCodeAt(0) - "a1".charCodeAt(0);
293         var to_row   = to_square.charCodeAt(1) - "a1".charCodeAt(1);
294
295         // Create arrow.
296         var arrow = {
297                 from_col: from_col,
298                 from_row: from_row,
299                 to_col: to_col,
300                 to_row: to_row,
301                 line_width: line_width,
302                 arrow_size: arrow_size,
303                 fg_color: fg_color
304         };
305
306         position_arrow(arrow);
307         arrows.push(arrow);
308 }
309
310 var compare_by_sort_key = function(refutation_lines, a, b) {
311         var ska = refutation_lines[a]['sort_key'];
312         var skb = refutation_lines[b]['sort_key'];
313         if (ska < skb) return -1;
314         if (ska > skb) return 1;
315         return 0;
316 };
317
318 var compare_by_score = function(refutation_lines, a, b) {
319         var sa = parseInt(refutation_lines[b]['score_sort_key'], 10);
320         var sb = parseInt(refutation_lines[a]['score_sort_key'], 10);
321         return sa - sb;
322 }
323
324 /**
325  * Fake multi-PV using the refutation lines. Find all “relevant” moves,
326  * sorted by quality, descending.
327  *
328  * @param {!Object} data
329  * @param {number} margin The maximum number of centipawns worse than the
330  *     best move can be and still be included.
331  * @return {Array.<string>} The UCI representation (e.g. e1g1) of all
332  *     moves, in score order.
333  */
334 var find_nonstupid_moves = function(data, margin) {
335         // First of all, if there are any moves that are more than 0.5 ahead of
336         // the primary move, the refutation lines are probably bunk, so just
337         // kill them all. 
338         var best_score = undefined;
339         var pv_score = undefined;
340         for (var move in data['refutation_lines']) {
341                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
342                 if (move == data['pv_uci'][0]) {
343                         pv_score = score;
344                 }
345                 if (best_score === undefined || score > best_score) {
346                         best_score = score;
347                 }
348                 if (!(data['refutation_lines'][move]['depth'] >= 8)) {
349                         return [];
350                 }
351         }
352
353         if (best_score - pv_score > 50) {
354                 return [];
355         }
356
357         // Now find all moves that are within “margin” of the best score.
358         // The PV move will always be first.
359         var moves = [];
360         for (var move in data['refutation_lines']) {
361                 var score = parseInt(data['refutation_lines'][move]['score_sort_key'], 10);
362                 if (move != data['pv_uci'][0] && best_score - score <= margin) {
363                         moves.push(move);
364                 }
365         }
366         moves = moves.sort(function(a, b) { return compare_by_score(data['refutation_lines'], a, b) });
367         moves.unshift(data['pv_uci'][0]);
368
369         return moves;
370 }
371
372 /**
373  * @param {number} x
374  * @return {!string}
375  */
376 var thousands = function(x) {
377         return String(x).split('').reverse().join('').replace(/(\d{3}\B)/g, '$1,').split('').reverse().join('');
378 }
379
380 /**
381  * @param {!string} fen
382  * @param {Array.<string>} uci_pv
383  * @param {Array.<string>} pretty_pv
384  * @param {number} move_num
385  * @param {!string} toplay
386  * @param {number=} opt_limit
387  * @param {boolean=} opt_showlast
388  */
389 var add_pv = function(fen, uci_pv, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
390         display_lines.push({
391                 start_fen: fen,
392                 uci_pv: uci_pv,
393                 pretty_pv: pretty_pv,
394                 line_number: display_lines.length
395         });
396         return print_pv(display_lines.length - 1, pretty_pv, move_num, toplay, opt_limit, opt_showlast);
397 }
398
399 /**
400  * @param {number} line_num
401  * @param {Array.<string>} pretty_pv
402  * @param {number} move_num
403  * @param {!string} toplay
404  * @param {number=} opt_limit
405  * @param {boolean=} opt_showlast
406  */
407 var print_pv = function(line_num, pretty_pv, move_num, toplay, opt_limit, opt_showlast) {
408         var pv = '';
409         var i = 0;
410         if (opt_limit && opt_showlast) {
411                 // Truncate the PV at the beginning (instead of at the end).
412                 // We assume here that toplay is 'W'. We also assume that if
413                 // opt_showlast is set, then it is the history, and thus,
414                 // the UI should be to expand the history.
415                 pv = '(<a class="move" href="javascript:collapse_history(false)">…</a>) ';
416                 i = pretty_pv.length - opt_limit;
417                 if (i % 2 == 1) {
418                         ++i;
419                 }
420                 move_num += i / 2;
421         } else if (toplay == 'B') {
422                 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
423                 pv = move_num + '. … ' + move;
424                 toplay = 'W';
425                 ++i;
426                 ++move_num;
427         }
428         for ( ; i < pretty_pv.length; ++i) {
429                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
430
431                 if (toplay == 'W') {
432                         if (i > opt_limit && !opt_showlast) {
433                                 return pv + ' (…)';
434                         }
435                         if (pv != '') {
436                                 pv += ' ';
437                         }
438                         pv += move_num + '. ' + move;
439                         ++move_num;
440                         toplay = 'B';
441                 } else {
442                         pv += ' ' + move;
443                         toplay = 'W';
444                 }
445         }
446         return pv;
447 }
448
449 var update_highlight = function() {
450         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
451         if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
452                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
453                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
454         }
455 }
456
457 var update_history = function() {
458         if (display_lines[0] === null) {
459                 $("#history").html("No history");
460         } else if (truncate_display_history) {
461                 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
462         } else {
463                 $("#history").html(
464                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
465                         print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
466         }
467 }
468
469 /**
470  * @param {!boolean} truncate_history
471  */
472 var collapse_history = function(truncate_history) {
473         truncate_display_history = truncate_history;
474         update_history();
475 }
476 window['collapse_history'] = collapse_history;
477
478 var update_refutation_lines = function() {
479         if (fen === null) {
480                 return;
481         }
482         if (display_lines.length > 2) {
483                 display_lines = [ display_lines[0], display_lines[1] ];
484         }
485
486         var tbl = $("#refutationlines");
487         tbl.empty();
488
489         var moves = [];
490         for (var move in refutation_lines) {
491                 moves.push(move);
492         }
493         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
494         moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
495         for (var i = 0; i < moves.length; ++i) {
496                 var line = refutation_lines[moves[i]];
497
498                 var tr = document.createElement("tr");
499
500                 var move_td = document.createElement("td");
501                 tr.appendChild(move_td);
502                 $(move_td).addClass("move");
503                 if (line['pv_uci'].length == 0) {
504                         $(move_td).text(line['pretty_move']);
505                 } else {
506                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
507                         $(move_td).html(move);
508                 }
509
510                 var score_td = document.createElement("td");
511                 tr.appendChild(score_td);
512                 $(score_td).addClass("score");
513                 $(score_td).text(line['pretty_score']);
514
515                 var depth_td = document.createElement("td");
516                 tr.appendChild(depth_td);
517                 $(depth_td).addClass("depth");
518                 $(depth_td).text("d" + line['depth']);
519
520                 var pv_td = document.createElement("td");
521                 tr.appendChild(pv_td);
522                 $(pv_td).addClass("pv");
523                 $(pv_td).html(add_pv(fen, line['pv_uci'], line['pv_pretty'], move_num, toplay, 10));
524
525                 tbl.append(tr);
526         }
527
528         // Make one of the links clickable and the other nonclickable.
529         if (sort_refutation_lines_by_score) {
530                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
531                 $("#sortbyscore1").html("<strong>Score</strong>");
532         } else {
533                 $("#sortbyscore0").html("<strong>Move</strong>");
534                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
535         }
536 }
537
538 /**
539  * @param {Object} data
540  * @param {number} num_viewers
541  */
542 var update_board = function(data, num_viewers) {
543         display_lines = [];
544
545         // The headline.
546         var headline;
547         if (data['position']['player_w'] && data['position']['player_b']) {
548                 headline = data['position']['player_w'] + '–' +
549                         data['position']['player_b'] + ', analysis';
550         } else {
551                 headline = 'Analysis';
552         }
553         if (data['position']['last_move'] !== 'none') {
554                 headline += ' after '
555                 if (data['position']['toplay'] == 'W') {
556                         headline += (data['position']['move_num']-1) + '… ';
557                 } else {
558                         headline += data['position']['move_num'] + '. ';
559                 }
560                 headline += data['position']['last_move'];
561         }
562
563         $("#headline").text(headline);
564
565         if (num_viewers === null) {
566                 $("#numviewers").text("");
567         } else if (num_viewers == 1) {
568                 $("#numviewers").text("You are the only current viewer");
569         } else {
570                 $("#numviewers").text(num_viewers + " current viewers");
571         }
572
573         // The engine id.
574         if (data['id'] && data['id']['name'] !== null) {
575                 $("#engineid").text(data['id']['name']);
576         }
577
578         // The score.
579         if (data['score'] !== null) {
580                 $("#score").text(data['score']);
581         }
582
583         // The search stats.
584         if (data['nodes'] && data['nps'] && data['depth']) {
585                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
586                 if (data['seldepth']) {
587                         stats += ' (' + data['seldepth'] + ' selective)';
588                 }
589                 if (data['tbhits'] && data['tbhits'] > 0) {
590                         if (data['tbhits'] == 1) {
591                                 stats += ', one Syzygy hit';
592                         } else {
593                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
594                         }
595                 }
596
597                 $("#searchstats").text(stats);
598         }
599
600         // Update the board itself.
601         fen = data['position']['fen'];
602         update_displayed_line();
603
604         if (data['position']['last_move_uci']) {
605                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
606                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
607         } else {
608                 highlight_from = highlight_to = undefined;
609         }
610         update_highlight();
611
612         // Print the history.
613         if (data['position']['history']) {
614                 add_pv('start', data['position']['history'], data['position']['pretty_history'], 1, 'W', 8, true);
615         } else {
616                 display_lines.push(null);
617         }
618         update_history();
619
620         // Print the PV.
621         $("#pv").html(add_pv(data['position']['fen'], data['pv_uci'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
622
623         // Update the PV arrow.
624         clear_arrows();
625         if (data['pv_uci'].length >= 1) {
626                 // draw a continuation arrow as long as it's the same piece
627                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
628                         var from = data['pv_uci'][i].substr(0, 2);
629                         var to = data['pv_uci'][i].substr(2,4);
630                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
631                              interfering_arrow(from, to)) {
632                                 break;
633                         }
634                         create_arrow(from, to, '#f66', 6, 20);
635                 }
636
637                 var alt_moves = find_nonstupid_moves(data, 30);
638                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
639                         create_arrow(alt_moves[i].substr(0, 2),
640                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
641                 }
642         }
643
644         // See if all semi-reasonable moves have only one possible response.
645         if (data['pv_uci'].length >= 2) {
646                 var nonstupid_moves = find_nonstupid_moves(data, 300);
647                 var response = data['pv_uci'][1];
648                 for (var i = 0; i < nonstupid_moves.length; ++i) {
649                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
650                                 // ignore the PV move for refutation lines.
651                                 continue;
652                         }
653                         if (!data['refutation_lines'] ||
654                             !data['refutation_lines'][nonstupid_moves[i]] ||
655                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
656                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
657                                 // Incomplete PV, abort.
658                                 response = undefined;
659                                 break;
660                         }
661                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
662                         if (response !== this_response) {
663                                 // Different response depending on lines, abort.
664                                 response = undefined;
665                                 break;
666                         }
667                 }
668
669                 if (nonstupid_moves.length > 0 && response !== undefined) {
670                         create_arrow(response.substr(0, 2),
671                                      response.substr(2, 2), '#66f', 6, 20);
672                 }
673         }
674
675         // Update the refutation lines.
676         fen = data['position']['fen'];
677         move_num = data['position']['move_num'];
678         toplay = data['position']['toplay'];
679         refutation_lines = data['refutation_lines'];
680         update_refutation_lines();
681
682         // Next update.
683         setTimeout(function() { request_update(); }, 100);
684 }
685
686 /**
687  * @param {boolean} sort_by_score
688  */
689 var resort_refutation_lines = function(sort_by_score) {
690         sort_refutation_lines_by_score = sort_by_score;
691         update_refutation_lines();
692 }
693 window['resort_refutation_lines'] = resort_refutation_lines;
694
695 /**
696  * @param {boolean} truncate_history
697  */
698 var set_truncate_history = function(truncate_history) {
699         truncate_display_history = truncate_history;
700         update_refutation_lines();
701 }
702 window['set_truncate_history'] = set_truncate_history;
703
704 /**
705  * @param {number} line_num
706  * @param {number} move_num
707  */
708 var show_line = function(line_num, move_num) {
709         if (line_num == -1) {
710                 current_display_line = null;
711                 current_display_move = null;
712         } else {
713                 current_display_line = display_lines[line_num];
714                 current_display_move = move_num;
715         }
716         update_displayed_line();
717         update_highlight();
718         redraw_arrows();
719 }
720 window['show_line'] = show_line;
721
722 var prev_move = function() {
723         if (current_display_move > -1) {
724                 --current_display_move;
725         }
726         update_displayed_line();
727 }
728 window['prev_move'] = prev_move;
729
730 var next_move = function() {
731         if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
732                 ++current_display_move;
733         }
734         update_displayed_line();
735 }
736 window['next_move'] = next_move;
737
738 var update_displayed_line = function() {
739         if (highlighted_move !== null) {
740                 highlighted_move.removeClass('highlight'); 
741         }
742         if (current_display_line === null) {
743                 $("#linenav").hide();
744                 $("#linemsg").show();
745                 board.position(fen);
746                 return;
747         }
748
749         $("#linenav").show();
750         $("#linemsg").hide();
751
752         if (current_display_move <= 0) {
753                 $("#prevmove").html("Previous");
754         } else {
755                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
756         }
757         if (current_display_move == current_display_line.uci_pv.length - 1) {
758                 $("#nextmove").html("Next");
759         } else {
760                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
761         }
762
763         hiddenboard.position(current_display_line.start_fen, false);
764         for (var i = 0; i <= current_display_move; ++i) {
765                 var move = current_display_line.uci_pv[i];
766                 var promo = move.substr(4, 1);
767                 move = move.substr(0, 2) + "-" + move.substr(2, 2);
768                 hiddenboard.move(move, false);
769
770                 // Do promotion if needed.
771                 if (promo != "") {
772                         var pos = hiddenboard.position();
773                         var target = move.substr(3, 2);
774                         pos[target] = pos[target].substr(0, 1) + promo.toUpperCase();
775                         hiddenboard.position(pos, false);
776                 }
777
778                 // chessboard.js does not automatically move the rook on castling
779                 // (issue #51; marked as won't fix), so update it ourselves.
780                 if (move == "e1-g1" && hiddenboard.position().g1 == "wK") {  // white O-O
781                         hiddenboard.move("h1-f1", false);
782                 } else if (move == "e1-c1" && hiddenboard.position().c1 == "wK") {  // white O-O-O
783                         hiddenboard.move("a1-d1", false);
784                 } else if (move == "e8-g8" && hiddenboard.position().g8 == "bK") {  // black O-O
785                         hiddenboard.move("h8-f8", false);
786                 } else if (move == "e8-c8" && hiddenboard.position().c8 == "bK") {  // black O-O-O
787                         hiddenboard.move("a8-d8", false);
788                 }
789         }
790
791         highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
792         highlighted_move.addClass('highlight'); 
793
794         board.position(hiddenboard.position());
795 }
796
797 var init = function() {
798         // Create board.
799         board = new window.ChessBoard('board', 'start');
800         hiddenboard = new window.ChessBoard('hiddenboard', 'start');
801
802         request_update();
803         $(window).resize(function() {
804                 board.resize();
805                 update_highlight();
806                 redraw_arrows();
807         });
808         $(window).keyup(function(event) {
809                 if (event.which == 39) {
810                         next_move();
811                 } else if (event.which == 37) {
812                         prev_move();
813                 }
814         });
815 };
816 $(document).ready(init);
817
818 })();