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