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