a18f93e1cb191a901f5047e36e6d4aa5c7a88180
[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 < 0) {
418                         i = 0;
419                 }
420                 if (i % 2 == 1) {
421                         ++i;
422                 }
423                 move_num += i / 2;
424         } else if (toplay == 'B') {
425                 var move = "<a class=\"move\" id=\"automove" + line_num + "-0\" href=\"javascript:show_line(" + line_num + ", " + 0 + ");\">" + pretty_pv[0] + "</a>";
426                 pv = move_num + '. … ' + move;
427                 toplay = 'W';
428                 ++i;
429                 ++move_num;
430         }
431         for ( ; i < pretty_pv.length; ++i) {
432                 var move = "<a class=\"move\" id=\"automove" + line_num + "-" + i + "\" href=\"javascript:show_line(" + line_num + ", " + i + ");\">" + pretty_pv[i] + "</a>";
433
434                 if (toplay == 'W') {
435                         if (i > opt_limit && !opt_showlast) {
436                                 return pv + ' (…)';
437                         }
438                         if (pv != '') {
439                                 pv += ' ';
440                         }
441                         pv += move_num + '. ' + move;
442                         ++move_num;
443                         toplay = 'B';
444                 } else {
445                         pv += ' ' + move;
446                         toplay = 'W';
447                 }
448         }
449         return pv;
450 }
451
452 var update_highlight = function() {
453         $("#board").find('.square-55d63').removeClass('nonuglyhighlight');
454         if (current_display_line === null && highlight_from !== undefined && highlight_to !== undefined) {
455                 $("#board").find('.square-' + highlight_from).addClass('nonuglyhighlight');
456                 $("#board").find('.square-' + highlight_to).addClass('nonuglyhighlight');
457         }
458 }
459
460 var update_history = function() {
461         if (display_lines[0] === null || display_lines[0].pretty_pv.length == 0) {
462                 $("#history").html("No history");
463         } else if (truncate_display_history) {
464                 $("#history").html(print_pv(0, display_lines[0].pretty_pv, 1, 'W', 8, true));
465         } else {
466                 $("#history").html(
467                         '(<a class="move" href="javascript:collapse_history(true)">collapse</a>) ' +
468                         print_pv(0, display_lines[0].pretty_pv, 1, 'W'));
469         }
470 }
471
472 /**
473  * @param {!boolean} truncate_history
474  */
475 var collapse_history = function(truncate_history) {
476         truncate_display_history = truncate_history;
477         update_history();
478 }
479 window['collapse_history'] = collapse_history;
480
481 var update_refutation_lines = function() {
482         if (fen === null) {
483                 return;
484         }
485         if (display_lines.length > 2) {
486                 display_lines = [ display_lines[0], display_lines[1] ];
487         }
488
489         var tbl = $("#refutationlines");
490         tbl.empty();
491
492         var moves = [];
493         for (var move in refutation_lines) {
494                 moves.push(move);
495         }
496         var compare = sort_refutation_lines_by_score ? compare_by_score : compare_by_sort_key;
497         moves = moves.sort(function(a, b) { return compare(refutation_lines, a, b) });
498         for (var i = 0; i < moves.length; ++i) {
499                 var line = refutation_lines[moves[i]];
500
501                 var tr = document.createElement("tr");
502
503                 var move_td = document.createElement("td");
504                 tr.appendChild(move_td);
505                 $(move_td).addClass("move");
506                 if (line['pv_uci'].length == 0) {
507                         $(move_td).text(line['pretty_move']);
508                 } else {
509                         var move = "<a class=\"move\" href=\"javascript:show_line(" + display_lines.length + ", " + 0 + ");\">" + line['pretty_move'] + "</a>";
510                         $(move_td).html(move);
511                 }
512
513                 var score_td = document.createElement("td");
514                 tr.appendChild(score_td);
515                 $(score_td).addClass("score");
516                 $(score_td).text(line['pretty_score']);
517
518                 var depth_td = document.createElement("td");
519                 tr.appendChild(depth_td);
520                 $(depth_td).addClass("depth");
521                 $(depth_td).text("d" + line['depth']);
522
523                 var pv_td = document.createElement("td");
524                 tr.appendChild(pv_td);
525                 $(pv_td).addClass("pv");
526                 $(pv_td).html(add_pv(fen, line['pv_uci'], line['pv_pretty'], move_num, toplay, 10));
527
528                 tbl.append(tr);
529         }
530
531         // Make one of the links clickable and the other nonclickable.
532         if (sort_refutation_lines_by_score) {
533                 $("#sortbyscore0").html("<a href=\"javascript:resort_refutation_lines(false)\">Move</a>");
534                 $("#sortbyscore1").html("<strong>Score</strong>");
535         } else {
536                 $("#sortbyscore0").html("<strong>Move</strong>");
537                 $("#sortbyscore1").html("<a href=\"javascript:resort_refutation_lines(true)\">Score</a>");
538         }
539 }
540
541 /**
542  * @param {Object} data
543  * @param {number} num_viewers
544  */
545 var update_board = function(data, num_viewers) {
546         display_lines = [];
547
548         // The headline.
549         var headline;
550         if (data['position']['player_w'] && data['position']['player_b']) {
551                 headline = data['position']['player_w'] + '–' +
552                         data['position']['player_b'] + ', analysis';
553         } else {
554                 headline = 'Analysis';
555         }
556         if (data['position']['last_move'] !== 'none') {
557                 headline += ' after '
558                 if (data['position']['toplay'] == 'W') {
559                         headline += (data['position']['move_num']-1) + '… ';
560                 } else {
561                         headline += data['position']['move_num'] + '. ';
562                 }
563                 headline += data['position']['last_move'];
564         }
565
566         $("#headline").text(headline);
567
568         if (num_viewers === null) {
569                 $("#numviewers").text("");
570         } else if (num_viewers == 1) {
571                 $("#numviewers").text("You are the only current viewer");
572         } else {
573                 $("#numviewers").text(num_viewers + " current viewers");
574         }
575
576         // The engine id.
577         if (data['id'] && data['id']['name'] !== null) {
578                 $("#engineid").text(data['id']['name']);
579         }
580
581         // The score.
582         if (data['score'] !== null) {
583                 $("#score").text(data['score']);
584         }
585
586         // The search stats.
587         if (data['nodes'] && data['nps'] && data['depth']) {
588                 var stats = thousands(data['nodes']) + ' nodes, ' + thousands(data['nps']) + ' nodes/sec, depth ' + data['depth'] + ' ply';
589                 if (data['seldepth']) {
590                         stats += ' (' + data['seldepth'] + ' selective)';
591                 }
592                 if (data['tbhits'] && data['tbhits'] > 0) {
593                         if (data['tbhits'] == 1) {
594                                 stats += ', one Syzygy hit';
595                         } else {
596                                 stats += ', ' + thousands(data['tbhits']) + ' Syzygy hits';
597                         }
598                 }
599
600                 $("#searchstats").text(stats);
601         }
602
603         // Update the board itself.
604         fen = data['position']['fen'];
605         update_displayed_line();
606
607         if (data['position']['last_move_uci']) {
608                 highlight_from = data['position']['last_move_uci'].substr(0, 2);
609                 highlight_to = data['position']['last_move_uci'].substr(2, 2);
610         } else {
611                 highlight_from = highlight_to = undefined;
612         }
613         update_highlight();
614
615         // Print the history.
616         if (data['position']['history']) {
617                 add_pv('start', data['position']['history'], data['position']['pretty_history'], 1, 'W', 8, true);
618         } else {
619                 display_lines.push(null);
620         }
621         update_history();
622
623         // Print the PV.
624         $("#pv").html(add_pv(data['position']['fen'], data['pv_uci'], data['pv_pretty'], data['position']['move_num'], data['position']['toplay']));
625
626         // Update the PV arrow.
627         clear_arrows();
628         if (data['pv_uci'].length >= 1) {
629                 // draw a continuation arrow as long as it's the same piece
630                 for (var i = 0; i < data['pv_uci'].length; i += 2) {
631                         var from = data['pv_uci'][i].substr(0, 2);
632                         var to = data['pv_uci'][i].substr(2,4);
633                         if ((i >= 2 && from != data['pv_uci'][i - 2].substr(2, 2)) ||
634                              interfering_arrow(from, to)) {
635                                 break;
636                         }
637                         create_arrow(from, to, '#f66', 6, 20);
638                 }
639
640                 var alt_moves = find_nonstupid_moves(data, 30);
641                 for (var i = 1; i < alt_moves.length && i < 3; ++i) {
642                         create_arrow(alt_moves[i].substr(0, 2),
643                                      alt_moves[i].substr(2, 2), '#f66', 1, 10);
644                 }
645         }
646
647         // See if all semi-reasonable moves have only one possible response.
648         if (data['pv_uci'].length >= 2) {
649                 var nonstupid_moves = find_nonstupid_moves(data, 300);
650                 var response = data['pv_uci'][1];
651                 for (var i = 0; i < nonstupid_moves.length; ++i) {
652                         if (nonstupid_moves[i] == data['pv_uci'][0]) {
653                                 // ignore the PV move for refutation lines.
654                                 continue;
655                         }
656                         if (!data['refutation_lines'] ||
657                             !data['refutation_lines'][nonstupid_moves[i]] ||
658                             !data['refutation_lines'][nonstupid_moves[i]]['pv_uci'] ||
659                             data['refutation_lines'][nonstupid_moves[i]]['pv_uci'].length < 1) {
660                                 // Incomplete PV, abort.
661                                 response = undefined;
662                                 break;
663                         }
664                         var this_response = data['refutation_lines'][nonstupid_moves[i]]['pv_uci'][1];
665                         if (response !== this_response) {
666                                 // Different response depending on lines, abort.
667                                 response = undefined;
668                                 break;
669                         }
670                 }
671
672                 if (nonstupid_moves.length > 0 && response !== undefined) {
673                         create_arrow(response.substr(0, 2),
674                                      response.substr(2, 2), '#66f', 6, 20);
675                 }
676         }
677
678         // Update the refutation lines.
679         fen = data['position']['fen'];
680         move_num = data['position']['move_num'];
681         toplay = data['position']['toplay'];
682         refutation_lines = data['refutation_lines'];
683         update_refutation_lines();
684
685         // Next update.
686         setTimeout(function() { request_update(); }, 100);
687 }
688
689 /**
690  * @param {boolean} sort_by_score
691  */
692 var resort_refutation_lines = function(sort_by_score) {
693         sort_refutation_lines_by_score = sort_by_score;
694         update_refutation_lines();
695 }
696 window['resort_refutation_lines'] = resort_refutation_lines;
697
698 /**
699  * @param {boolean} truncate_history
700  */
701 var set_truncate_history = function(truncate_history) {
702         truncate_display_history = truncate_history;
703         update_refutation_lines();
704 }
705 window['set_truncate_history'] = set_truncate_history;
706
707 /**
708  * @param {number} line_num
709  * @param {number} move_num
710  */
711 var show_line = function(line_num, move_num) {
712         if (line_num == -1) {
713                 current_display_line = null;
714                 current_display_move = null;
715         } else {
716                 current_display_line = display_lines[line_num];
717                 current_display_move = move_num;
718         }
719         update_displayed_line();
720         update_highlight();
721         redraw_arrows();
722 }
723 window['show_line'] = show_line;
724
725 var prev_move = function() {
726         if (current_display_move > -1) {
727                 --current_display_move;
728         }
729         update_displayed_line();
730 }
731 window['prev_move'] = prev_move;
732
733 var next_move = function() {
734         if (current_display_line && current_display_move < current_display_line.pretty_pv.length - 1) {
735                 ++current_display_move;
736         }
737         update_displayed_line();
738 }
739 window['next_move'] = next_move;
740
741 var update_displayed_line = function() {
742         if (highlighted_move !== null) {
743                 highlighted_move.removeClass('highlight'); 
744         }
745         if (current_display_line === null) {
746                 $("#linenav").hide();
747                 $("#linemsg").show();
748                 board.position(fen);
749                 return;
750         }
751
752         $("#linenav").show();
753         $("#linemsg").hide();
754
755         if (current_display_move <= 0) {
756                 $("#prevmove").html("Previous");
757         } else {
758                 $("#prevmove").html("<a href=\"javascript:prev_move();\">Previous</a></span>");
759         }
760         if (current_display_move == current_display_line.uci_pv.length - 1) {
761                 $("#nextmove").html("Next");
762         } else {
763                 $("#nextmove").html("<a href=\"javascript:next_move();\">Next</a></span>");
764         }
765
766         hiddenboard.position(current_display_line.start_fen, false);
767         for (var i = 0; i <= current_display_move; ++i) {
768                 var pos = hiddenboard.position();
769                 var move = current_display_line.uci_pv[i];
770                 var source = move.substr(0, 2);
771                 var target = move.substr(2, 2);
772                 var promo = move.substr(4, 1);
773
774                 // Check if we need to do en passant.
775                 var piece = pos[source];
776                 if (piece == "wP" || piece == "bP") {
777                         if (source.substr(0, 1) != target.substr(0, 1) &&
778                             pos[target] === undefined) {
779                                 var ep_square = target.substr(0, 1) + source.substr(1, 1);
780                                 delete pos[ep_square];
781                                 hiddenboard.position(pos, false);
782                         }
783                 }
784
785                 move = source + "-" + target;
786                 hiddenboard.move(move, false);
787
788                 // Do promotion if needed.
789                 if (promo != "") {
790                         pos[target] = pos[target].substr(0, 1) + promo.toUpperCase();
791                         hiddenboard.position(pos, false);
792                 }
793
794                 // chessboard.js does not automatically move the rook on castling
795                 // (issue #51; marked as won't fix), so update it ourselves.
796                 if (move == "e1-g1" && hiddenboard.position().g1 == "wK") {  // white O-O
797                         hiddenboard.move("h1-f1", false);
798                 } else if (move == "e1-c1" && hiddenboard.position().c1 == "wK") {  // white O-O-O
799                         hiddenboard.move("a1-d1", false);
800                 } else if (move == "e8-g8" && hiddenboard.position().g8 == "bK") {  // black O-O
801                         hiddenboard.move("h8-f8", false);
802                 } else if (move == "e8-c8" && hiddenboard.position().c8 == "bK") {  // black O-O-O
803                         hiddenboard.move("a8-d8", false);
804                 }
805         }
806
807         highlighted_move = $("#automove" + current_display_line.line_number + "-" + current_display_move);
808         highlighted_move.addClass('highlight'); 
809
810         board.position(hiddenboard.position());
811 }
812
813 var init = function() {
814         // Create board.
815         board = new window.ChessBoard('board', 'start');
816         hiddenboard = new window.ChessBoard('hiddenboard', 'start');
817
818         request_update();
819         $(window).resize(function() {
820                 board.resize();
821                 update_highlight();
822                 redraw_arrows();
823         });
824         $(window).keyup(function(event) {
825                 if (event.which == 39) {
826                         next_move();
827                 } else if (event.which == 37) {
828                         prev_move();
829                 }
830         });
831 };
832 $(document).ready(init);
833
834 })();