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