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