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