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