]> git.sesse.net Git - remoteglot/blob - www/js/chessboard-0.3.0.js
Cheaper createId().
[remoteglot] / www / js / chessboard-0.3.0.js
1 /*!
2  * chessboard.js v0.3.0+asn
3  *
4  * Copyright 2013 Chris Oakman
5  * Portions copyright 2022 Steinar H. Gunderson
6  * Released under the MIT license
7  * http://chessboardjs.com/license
8  *
9  * Date: 10 Aug 2013
10  */
11
12 // start anonymous scope
13 ;(function() {
14 'use strict';
15
16 //------------------------------------------------------------------------------
17 // Chess Util Functions
18 //------------------------------------------------------------------------------
19 var COLUMNS = 'abcdefgh'.split('');
20
21 function validMove(move) {
22   // move should be a string
23   if (typeof move !== 'string') return false;
24
25   // move should be in the form of "e2-e4", "f6-d5"
26   var tmp = move.split('-');
27   if (tmp.length !== 2) return false;
28
29   return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true);
30 }
31
32 function validSquare(square) {
33   if (typeof square !== 'string') return false;
34   return (square.search(/^[a-h][1-8]$/) !== -1);
35 }
36
37 function validPieceCode(code) {
38   if (typeof code !== 'string') return false;
39   return (code.search(/^[bw][KQRNBP]$/) !== -1);
40 }
41
42 // TODO: this whole function could probably be replaced with a single regex
43 function validFen(fen) {
44   if (typeof fen !== 'string') return false;
45
46   // cut off any move, castling, etc info from the end
47   // we're only interested in position information
48   fen = fen.replace(/ .+$/, '');
49
50   // FEN should be 8 sections separated by slashes
51   var chunks = fen.split('/');
52   if (chunks.length !== 8) return false;
53
54   // check the piece sections
55   for (var i = 0; i < 8; i++) {
56     if (chunks[i] === '' ||
57         chunks[i].length > 8 ||
58         chunks[i].search(/[^kqrbnpKQRNBP1-8]/) !== -1) {
59       return false;
60     }
61   }
62
63   return true;
64 }
65
66 function validPositionObject(pos) {
67   if (typeof pos !== 'object') return false;
68
69   for (var i in pos) {
70     if (pos.hasOwnProperty(i) !== true) continue;
71
72     if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) {
73       return false;
74     }
75   }
76
77   return true;
78 }
79
80 // convert FEN piece code to bP, wK, etc
81 function fenToPieceCode(piece) {
82   // black piece
83   if (piece.toLowerCase() === piece) {
84     return 'b' + piece.toUpperCase();
85   }
86
87   // white piece
88   return 'w' + piece.toUpperCase();
89 }
90
91 // convert bP, wK, etc code to FEN structure
92 function pieceCodeToFen(piece) {
93   var tmp = piece.split('');
94
95   // white piece
96   if (tmp[0] === 'w') {
97     return tmp[1].toUpperCase();
98   }
99
100   // black piece
101   return tmp[1].toLowerCase();
102 }
103
104 // convert FEN string to position object
105 // returns false if the FEN string is invalid
106 function fenToObj(fen) {
107   if (validFen(fen) !== true) {
108     return false;
109   }
110
111   // cut off any move, castling, etc info from the end
112   // we're only interested in position information
113   fen = fen.replace(/ .+$/, '');
114
115   var rows = fen.split('/');
116   var position = {};
117
118   var currentRow = 8;
119   for (var i = 0; i < 8; i++) {
120     var row = rows[i].split('');
121     var colIndex = 0;
122
123     // loop through each character in the FEN section
124     for (var j = 0; j < row.length; j++) {
125       // number / empty squares
126       if (row[j].search(/[1-8]/) !== -1) {
127         var emptySquares = parseInt(row[j], 10);
128         colIndex += emptySquares;
129       }
130       // piece
131       else {
132         var square = COLUMNS[colIndex] + currentRow;
133         position[square] = fenToPieceCode(row[j]);
134         colIndex++;
135       }
136     }
137
138     currentRow--;
139   }
140
141   return position;
142 }
143
144 // position object to FEN string
145 // returns false if the obj is not a valid position object
146 function objToFen(obj) {
147   if (validPositionObject(obj) !== true) {
148     return false;
149   }
150
151   var fen = '';
152
153   var currentRow = 8;
154   for (var i = 0; i < 8; i++) {
155     for (var j = 0; j < 8; j++) {
156       var square = COLUMNS[j] + currentRow;
157
158       // piece exists
159       if (obj.hasOwnProperty(square) === true) {
160         fen += pieceCodeToFen(obj[square]);
161       }
162
163       // empty space
164       else {
165         fen += '1';
166       }
167     }
168
169     if (i !== 7) {
170       fen += '/';
171     }
172
173     currentRow--;
174   }
175
176   // squeeze the numbers together
177   // haha, I love this solution...
178   fen = fen.replace(/11111111/g, '8');
179   fen = fen.replace(/1111111/g, '7');
180   fen = fen.replace(/111111/g, '6');
181   fen = fen.replace(/11111/g, '5');
182   fen = fen.replace(/1111/g, '4');
183   fen = fen.replace(/111/g, '3');
184   fen = fen.replace(/11/g, '2');
185
186   return fen;
187 }
188
189 /** @struct */
190 var cfg;
191
192 /** @constructor */
193 window.ChessBoard = function(containerElOrId, cfg) {
194 'use strict';
195
196 cfg = cfg || {};
197
198 //------------------------------------------------------------------------------
199 // Constants
200 //------------------------------------------------------------------------------
201
202 var MINIMUM_JQUERY_VERSION = '1.7.0',
203   START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR',
204   START_POSITION = fenToObj(START_FEN);
205
206 // use unique class names to prevent clashing with anything else on the page
207 // and simplify selectors
208 var CSS = {
209   alpha: 'alpha-d2270',
210   board: 'board-b72b1',
211   chessboard: 'chessboard-63f37',
212   clearfix: 'clearfix-7da63',
213   highlight1: 'highlight1-32417',
214   highlight2: 'highlight2-9c5d2',
215   notation: 'notation-322f9',
216   numeric: 'numeric-fc462',
217   piece: 'piece-417db',
218   row: 'row-5277c',
219   sparePieces: 'spare-pieces-7492f',
220   sparePiecesBottom: 'spare-pieces-bottom-ae20f',
221   sparePiecesTop: 'spare-pieces-top-4028b',
222   square: 'square-55d63'
223 };
224 var CSSColor = {};
225 CSSColor['white'] = 'white-1e1d7';
226 CSSColor['black'] = 'black-3c85d';
227
228 //------------------------------------------------------------------------------
229 // Module Scope Variables
230 //------------------------------------------------------------------------------
231
232 // DOM elements
233 var containerEl,
234   boardEl,
235   draggedPieceEl,
236   sparePiecesTopEl,
237   sparePiecesBottomEl;
238
239 // constructor return object
240 var widget = {};
241
242 //------------------------------------------------------------------------------
243 // Stateful
244 //------------------------------------------------------------------------------
245
246 var BOARD_BORDER_SIZE = 2,
247   CURRENT_ORIENTATION = 'white',
248   CURRENT_POSITION = {},
249   SQUARE_SIZE,
250   DRAGGED_PIECE,
251   DRAGGED_PIECE_LOCATION,
252   DRAGGED_PIECE_SOURCE,
253   DRAGGING_A_PIECE = false,
254   SPARE_PIECE_ELS_IDS = {},
255   SQUARE_ELS_IDS = {},
256   SQUARE_ELS_OFFSETS;
257
258 //------------------------------------------------------------------------------
259 // JS Util Functions
260 //------------------------------------------------------------------------------
261
262 let id_counter = 0;
263 function createId() {
264   return 'chesspiece-id-' + (id_counter++);
265 }
266
267 function deepCopy(thing) {
268   return JSON.parse(JSON.stringify(thing));
269 }
270
271 function parseSemVer(version) {
272   var tmp = version.split('.');
273   return {
274     major: parseInt(tmp[0], 10),
275     minor: parseInt(tmp[1], 10),
276     patch: parseInt(tmp[2], 10)
277   };
278 }
279
280 // returns true if version is >= minimum
281 function compareSemVer(version, minimum) {
282   version = parseSemVer(version);
283   minimum = parseSemVer(minimum);
284
285   var versionNum = (version.major * 10000 * 10000) +
286     (version.minor * 10000) + version.patch;
287   var minimumNum = (minimum.major * 10000 * 10000) +
288     (minimum.minor * 10000) + minimum.patch;
289
290   return (versionNum >= minimumNum);
291 }
292
293 //------------------------------------------------------------------------------
294 // Validation / Errors
295 //------------------------------------------------------------------------------
296
297 /**
298  * @param {!number} code
299  * @param {!string} msg
300  * @param {Object=} obj
301  */
302 function error(code, msg, obj) {
303   // do nothing if showErrors is not set
304   if (cfg.hasOwnProperty('showErrors') !== true ||
305       cfg.showErrors === false) {
306     return;
307   }
308
309   var errorText = 'ChessBoard Error ' + code + ': ' + msg;
310
311   // print to console
312   if (cfg.showErrors === 'console' &&
313       typeof console === 'object' &&
314       typeof console.log === 'function') {
315     console.log(errorText);
316     if (arguments.length >= 2) {
317       console.log(obj);
318     }
319     return;
320   }
321
322   // alert errors
323   if (cfg.showErrors === 'alert') {
324     if (obj) {
325       errorText += '\n\n' + JSON.stringify(obj);
326     }
327     window.alert(errorText);
328     return;
329   }
330
331   // custom function
332   if (typeof cfg.showErrors === 'function') {
333     cfg.showErrors(code, msg, obj);
334   }
335 }
336
337 // check dependencies
338 function checkDeps() {
339   // if containerId is a string, it must be the ID of a DOM node
340   if (typeof containerElOrId === 'string') {
341     // cannot be empty
342     if (containerElOrId === '') {
343       window.alert('ChessBoard Error 1001: ' +
344         'The first argument to ChessBoard() cannot be an empty string.' +
345         '\n\nExiting...');
346       return false;
347     }
348
349     // make sure the container element exists in the DOM
350     var el = document.getElementById(containerElOrId);
351     if (! el) {
352       window.alert('ChessBoard Error 1002: Element with id "' +
353         containerElOrId + '" does not exist in the DOM.' +
354         '\n\nExiting...');
355       return false;
356     }
357
358     // set the containerEl
359     containerEl = el;
360   }
361
362   // else it must be a DOM node
363   else {
364     containerEl = containerElOrId;
365   }
366
367   return true;
368 }
369
370 function validAnimationSpeed(speed) {
371   if (speed === 'fast' || speed === 'slow') {
372     return true;
373   }
374
375   if ((parseInt(speed, 10) + '') !== (speed + '')) {
376     return false;
377   }
378
379   return (speed >= 0);
380 }
381
382 // validate config / set default options
383 function expandConfig() {
384   if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
385     cfg = {
386       position: cfg
387     };
388   }
389
390   // default for orientation is white
391   if (cfg.orientation !== 'black') {
392     cfg.orientation = 'white';
393   }
394   CURRENT_ORIENTATION = cfg.orientation;
395
396   // default for showNotation is true
397   if (cfg.showNotation !== false) {
398     cfg.showNotation = true;
399   }
400
401   // default for draggable is false
402   if (cfg.draggable !== true) {
403     cfg.draggable = false;
404   }
405
406   // default for dropOffBoard is 'snapback'
407   if (cfg.dropOffBoard !== 'trash') {
408     cfg.dropOffBoard = 'snapback';
409   }
410
411   // default for sparePieces is false
412   if (cfg.sparePieces !== true) {
413     cfg.sparePieces = false;
414   }
415
416   // draggable must be true if sparePieces is enabled
417   if (cfg.sparePieces === true) {
418     cfg.draggable = true;
419   }
420
421   // default piece theme is wikipedia
422   if (cfg.hasOwnProperty('pieceTheme') !== true ||
423       (typeof cfg.pieceTheme !== 'string' &&
424        typeof cfg.pieceTheme !== 'function')) {
425     cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';
426   }
427
428   // animation speeds
429   if (cfg.hasOwnProperty('appearSpeed') !== true ||
430       validAnimationSpeed(cfg.appearSpeed) !== true) {
431     cfg.appearSpeed = 200;
432   }
433   if (cfg.hasOwnProperty('moveSpeed') !== true ||
434       validAnimationSpeed(cfg.moveSpeed) !== true) {
435     cfg.moveSpeed = 200;
436   }
437   if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
438       validAnimationSpeed(cfg.snapbackSpeed) !== true) {
439     cfg.snapbackSpeed = 50;
440   }
441   if (cfg.hasOwnProperty('snapSpeed') !== true ||
442       validAnimationSpeed(cfg.snapSpeed) !== true) {
443     cfg.snapSpeed = 25;
444   }
445   if (cfg.hasOwnProperty('trashSpeed') !== true ||
446       validAnimationSpeed(cfg.trashSpeed) !== true) {
447     cfg.trashSpeed = 100;
448   }
449
450   // make sure position is valid
451   if (cfg.hasOwnProperty('position') === true) {
452     if (cfg.position === 'start') {
453       CURRENT_POSITION = deepCopy(START_POSITION);
454     }
455
456     else if (validFen(cfg.position) === true) {
457       CURRENT_POSITION = fenToObj(cfg.position);
458     }
459
460     else if (validPositionObject(cfg.position) === true) {
461       CURRENT_POSITION = deepCopy(cfg.position);
462     }
463
464     else {
465       error(7263, 'Invalid value passed to config.position.', cfg.position);
466     }
467   }
468
469   return true;
470 }
471
472 //------------------------------------------------------------------------------
473 // DOM Misc
474 //------------------------------------------------------------------------------
475
476 // calculates square size based on the width of the container
477 // got a little CSS black magic here, so let me explain:
478 // get the width of the container element (could be anything), reduce by 1 for
479 // fudge factor, and then keep reducing until we find an exact mod 8 for
480 // our square size
481 function calculateSquareSize() {
482   var containerWidth = parseInt(getComputedStyle(containerEl).width, 10);
483
484   // defensive, prevent infinite loop
485   if (! containerWidth || containerWidth <= 0) {
486     return 0;
487   }
488
489   // pad one pixel
490   var boardWidth = containerWidth - 1;
491
492   while (boardWidth % 8 !== 0 && boardWidth > 0) {
493     boardWidth--;
494   }
495
496   return (boardWidth / 8);
497 }
498
499 // create random IDs for elements
500 function createElIds() {
501   // squares on the board
502   for (var i = 0; i < COLUMNS.length; i++) {
503     for (var j = 1; j <= 8; j++) {
504       var square = COLUMNS[i] + j;
505       SQUARE_ELS_IDS[square] = square + '-' + createId();
506     }
507   }
508
509   // spare pieces
510   var pieces = 'KQRBNP'.split('');
511   for (var i = 0; i < pieces.length; i++) {
512     var whitePiece = 'w' + pieces[i];
513     var blackPiece = 'b' + pieces[i];
514     SPARE_PIECE_ELS_IDS[whitePiece] = whitePiece + '-' + createId();
515     SPARE_PIECE_ELS_IDS[blackPiece] = blackPiece + '-' + createId();
516   }
517 }
518
519 //------------------------------------------------------------------------------
520 // Markup Building
521 //------------------------------------------------------------------------------
522
523 function buildBoardContainer() {
524   var html = '<div class="' + CSS.chessboard + '">';
525
526   if (cfg.sparePieces === true) {
527     html += '<div class="' + CSS.sparePieces + ' ' +
528       CSS.sparePiecesTop + '"></div>';
529   }
530
531   html += '<div class="' + CSS.board + '"></div>';
532
533   if (cfg.sparePieces === true) {
534     html += '<div class="' + CSS.sparePieces + ' ' +
535       CSS.sparePiecesBottom + '"></div>';
536   }
537
538   html += '</div>';
539
540   return html;
541 }
542
543 /*
544 var buildSquare = function(color, size, id) {
545   var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
546   'style="width: ' + size + 'px; height: ' + size + 'px" ' +
547   'id="' + id + '">';
548
549   if (cfg.showNotation === true) {
550
551   }
552
553   html += '</div>';
554
555   return html;
556 };
557 */
558
559 function buildBoard(orientation) {
560   if (orientation !== 'black') {
561     orientation = 'white';
562   }
563
564   var html = '';
565
566   // algebraic notation / orientation
567   var alpha = deepCopy(COLUMNS);
568   var row = 8;
569   if (orientation === 'black') {
570     alpha.reverse();
571     row = 1;
572   }
573
574   var squareColor = 'white';
575   for (var i = 0; i < 8; i++) {
576     html += '<div class="' + CSS.row + '">';
577     for (var j = 0; j < 8; j++) {
578       var square = alpha[j] + row;
579
580       html += '<div class="' + CSS.square + ' ' + CSSColor[squareColor] + ' ' +
581         'square-' + square + '" ' +
582         'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' +
583         'id="' + SQUARE_ELS_IDS[square] + '" ' +
584         'data-square="' + square + '">';
585
586       if (cfg.showNotation === true) {
587         // alpha notation
588         if ((orientation === 'white' && row === 1) ||
589             (orientation === 'black' && row === 8)) {
590           html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
591             alpha[j] + '</div>';
592         }
593
594         // numeric notation
595         if (j === 0) {
596           html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
597             row + '</div>';
598         }
599       }
600
601       html += '</div>'; // end .square
602
603       squareColor = (squareColor === 'white' ? 'black' : 'white');
604     }
605     html += '<div class="' + CSS.clearfix + '"></div></div>';
606
607     squareColor = (squareColor === 'white' ? 'black' : 'white');
608
609     if (orientation === 'white') {
610       row--;
611     }
612     else {
613       row++;
614     }
615   }
616
617   return html;
618 }
619
620 function buildPieceImgSrc(piece) {
621   if (typeof cfg.pieceTheme === 'function') {
622     return cfg.pieceTheme(piece);
623   }
624
625   if (typeof cfg.pieceTheme === 'string') {
626     return cfg.pieceTheme.replace(/{piece}/g, piece);
627   }
628
629   // NOTE: this should never happen
630   error(8272, 'Unable to build image source for cfg.pieceTheme.');
631   return '';
632 }
633
634 /**
635  * @param {!string} piece
636  * @param {boolean=} hidden
637  * @param {!string=} id
638  */
639 function buildPiece(piece, hidden, id) {
640   let img = document.createElement('img');
641   img.src = buildPieceImgSrc(piece);
642   if (id && typeof id === 'string') {
643     img.setAttribute('id', id);
644   }
645   img.setAttribute('alt', '');
646   img.classList.add(CSS.piece);
647   img.setAttribute('data-piece', piece);
648   img.style.width = SQUARE_SIZE + 'px';
649   img.style.height = SQUARE_SIZE + 'px';
650   if (hidden === true) {
651     img.style.display = 'none';
652   }
653   return img;
654 }
655
656 function buildSparePieces(color) {
657   var pieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP'];
658   if (color === 'black') {
659     pieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP'];
660   }
661
662   var html = '';
663   for (var i = 0; i < pieces.length; i++) {
664     html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
665   }
666
667   return html;
668 }
669
670 //------------------------------------------------------------------------------
671 // Animations
672 //------------------------------------------------------------------------------
673
674 function offset(el) {  // From https://youmightnotneedjquery.com/.
675   let box = el.getBoundingClientRect();
676   let docElem = document.documentElement;
677   return {
678     top: box.top + window.pageYOffset - docElem.clientTop,
679     left: box.left + window.pageXOffset - docElem.clientLeft
680   };
681 }
682
683 function animateSquareToSquare(src, dest, piece, completeFn) {
684   // get information about the source and destination squares
685   var srcSquareEl = document.getElementById(SQUARE_ELS_IDS[src]);
686   var srcSquarePosition = offset(srcSquareEl);
687   var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
688   var destSquarePosition = offset(destSquareEl);
689
690   // create the animated piece and absolutely position it
691   // over the source square
692   var animatedPieceId = createId();
693   document.body.append(buildPiece(piece, true, animatedPieceId));
694   var animatedPieceEl = document.getElementById(animatedPieceId);
695   animatedPieceEl.style.display = null;
696   animatedPieceEl.style.position = 'absolute';
697   animatedPieceEl.style.top = srcSquarePosition.top + 'px';
698   animatedPieceEl.style.left = srcSquarePosition.left + 'px';
699
700   // remove original piece(s) from source square
701   // TODO: multiple pieces should never really happen, but it will if we are moving
702   // while another animation still isn't done
703   srcSquareEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
704
705   // on complete
706   var complete = function() {
707     // add the "real" piece to the destination square
708     destSquareEl.append(buildPiece(piece));
709
710     // remove the animated piece
711     animatedPieceEl.remove();
712
713     // run complete function
714     if (typeof completeFn === 'function') {
715       completeFn();
716     }
717   };
718
719   // animate the piece to the destination square
720   animatedPieceEl.addEventListener('transitionend', complete, {once: true});
721   requestAnimationFrame(() => {
722     animatedPieceEl.style.transitionProperty = 'top, left';
723     animatedPieceEl.style.transitionDuration = cfg.moveSpeed + 'ms';
724     animatedPieceEl.style.top = destSquarePosition.top + 'px';
725     animatedPieceEl.style.left = destSquarePosition.left + 'px';
726   });
727 }
728
729 function animateSparePieceToSquare(piece, dest, completeFn) {
730   var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
731   var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
732   var destOffset = offset(destSquareEl);
733
734   // create the animate piece
735   var pieceId = createId();
736   document.body.append(buildPiece(piece, true, pieceId));
737   var animatedPieceEl = document.getElementById(pieceId);
738   animatedPieceEl.style.display = '';
739   animatedPieceEl.style.position = 'absolute';
740   animatedPieceEl.style.left = srcOffset.left;
741   animatedPieceEl.style.top = srcOffset.top;
742
743   // on complete
744   var complete = function() {
745     // add the "real" piece to the destination square
746     destSquareEl.querySelector('.' + CSS.piece).remove();
747     destSquareEl.append(buildPiece(piece));
748
749     // remove the animated piece
750     animatedPieceEl.remove();
751
752     // run complete function
753     if (typeof completeFn === 'function') {
754       completeFn();
755     }
756   };
757
758   // animate the piece to the destination square
759   // FIXME: support this for non-jquery
760   var opts = {
761     duration: cfg.moveSpeed,
762     complete: complete
763   };
764   //$(animatedPieceEl).animate(destOffset, opts);
765 }
766
767 function fadeIn(pieces, onFinish) {
768   pieces.forEach((piece) => {
769     piece.style.opacity = 0;
770     piece.style.display = null;
771     piece.addEventListener('transitionend', onFinish, {once: true});
772   });
773   requestAnimationFrame(() => {
774     pieces.forEach((piece) => {
775       piece.style.transitionProperty = 'opacity';
776       piece.style.transitionDuration = cfg.appearSpeed + 'ms';
777       piece.style.opacity = 1;
778     });
779   });
780 }
781
782 function fadeOut(pieces, onFinish) {
783   pieces.forEach((piece) => {
784     piece.style.opacity = 1;
785     piece.style.display = null;
786     piece.addEventListener('transitionend', onFinish, {once: true});
787   });
788   requestAnimationFrame(() => {
789     pieces.forEach((piece) => {
790       piece.style.transitionProperty = 'opacity';
791       piece.style.transitionDuration = cfg.trashSpeed + 'ms';
792       piece.style.opacity = 0;
793     });
794   });
795 }
796
797 // execute an array of animations
798 function doAnimations(a, oldPos, newPos) {
799   var numFinished = 0;
800   function onFinish(e) {
801     if (e && e.target) {
802       e.target.transitionProperty = null;
803     }
804
805     numFinished++;
806
807     // exit if all the animations aren't finished
808     if (numFinished !== a.length) return;
809
810     drawPositionInstant();
811
812     // run their onMoveEnd function
813     if (cfg.hasOwnProperty('onMoveEnd') === true &&
814       typeof cfg.onMoveEnd === 'function') {
815       cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
816     }
817   }
818
819   requestAnimationFrame(() => {  // Firefox workaround.
820     let fadeout_pieces = [];
821     let fadein_pieces = [];
822
823     for (var i = 0; i < a.length; i++) {
824       // clear a piece
825       if (a[i].type === 'clear') {
826         document.getElementById(SQUARE_ELS_IDS[a[i].square]).querySelectorAll('.' + CSS.piece).forEach(
827           (piece) => fadeout_pieces.push(piece)
828         );
829       }
830
831       // add a piece (no spare pieces)
832       if (a[i].type === 'add' && cfg.sparePieces !== true) {
833         let square = document.getElementById(SQUARE_ELS_IDS[a[i].square]);
834         square.append(buildPiece(a[i].piece, true));
835         let piece = square.querySelector('.' + CSS.piece);
836         fadein_pieces.push(piece);
837       }
838
839       // add a piece from a spare piece
840       if (a[i].type === 'add' && cfg.sparePieces === true) {
841         animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
842       }
843
844       // move a piece
845       if (a[i].type === 'move') {
846         animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
847           onFinish);
848       }
849     }
850
851     // TODO: Batch moves as well, not just fade in/out.
852     // (We batch them because requestAnimationFrame seemingly costs real time.)
853     if (fadeout_pieces.length > 0) {
854       fadeOut(fadeout_pieces, onFinish);
855     }
856     if (fadein_pieces.length > 0) {
857       fadeIn(fadein_pieces, onFinish);
858     }
859   });
860 }
861
862 // returns the distance between two squares
863 function squareDistance(s1, s2) {
864   s1 = s1.split('');
865   var s1x = COLUMNS.indexOf(s1[0]) + 1;
866   var s1y = parseInt(s1[1], 10);
867
868   s2 = s2.split('');
869   var s2x = COLUMNS.indexOf(s2[0]) + 1;
870   var s2y = parseInt(s2[1], 10);
871
872   var xDelta = Math.abs(s1x - s2x);
873   var yDelta = Math.abs(s1y - s2y);
874
875   if (xDelta >= yDelta) return xDelta;
876   return yDelta;
877 }
878
879 // returns the square of the closest instance of piece
880 // returns false if no instance of piece is found in position
881 function findClosestPiece(position, piece, square) {
882   let best_square = false;
883   let best_dist = 1e9;
884   for (var i = 0; i < COLUMNS.length; i++) {
885     for (var j = 1; j <= 8; j++) {
886       let other_square = COLUMNS[i] + j;
887
888       if (position[other_square] === piece && square != other_square) {
889         let dist = squareDistance(square, other_square);
890         if (dist < best_dist) {
891           best_square = other_square;
892           best_dist = dist;
893         }
894       }
895     }
896   }
897
898   return best_square;
899 }
900
901 // calculate an array of animations that need to happen in order to get
902 // from pos1 to pos2
903 function calculateAnimations(pos1, pos2) {
904   // make copies of both
905   pos1 = deepCopy(pos1);
906   pos2 = deepCopy(pos2);
907
908   var animations = [];
909   var squaresMovedTo = {};
910
911   // remove pieces that are the same in both positions
912   for (var i in pos2) {
913     if (pos2.hasOwnProperty(i) !== true) continue;
914
915     if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
916       delete pos1[i];
917       delete pos2[i];
918     }
919   }
920
921   // find all the "move" animations
922   for (var i in pos2) {
923     if (pos2.hasOwnProperty(i) !== true) continue;
924
925     var closestPiece = findClosestPiece(pos1, pos2[i], i);
926     if (closestPiece !== false) {
927       animations.push({
928         type: 'move',
929         source: closestPiece,
930         destination: i,
931         piece: pos2[i]
932       });
933
934       delete pos1[closestPiece];
935       delete pos2[i];
936       squaresMovedTo[i] = true;
937     }
938   }
939
940   // add pieces to pos2
941   for (var i in pos2) {
942     if (pos2.hasOwnProperty(i) !== true) continue;
943
944     animations.push({
945       type: 'add',
946       square: i,
947       piece: pos2[i]
948     })
949
950     delete pos2[i];
951   }
952
953   // clear pieces from pos1
954   for (var i in pos1) {
955     if (pos1.hasOwnProperty(i) !== true) continue;
956
957     // do not clear a piece if it is on a square that is the result
958     // of a "move", ie: a piece capture
959     if (squaresMovedTo.hasOwnProperty(i) === true) continue;
960
961     animations.push({
962       type: 'clear',
963       square: i,
964       piece: pos1[i]
965     });
966
967     delete pos1[i];
968   }
969
970   return animations;
971 }
972
973 //------------------------------------------------------------------------------
974 // Control Flow
975 //------------------------------------------------------------------------------
976
977 function drawPositionInstant() {
978   // clear the board
979   boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
980
981   // add the pieces
982   for (var i in CURRENT_POSITION) {
983     if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
984
985     document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
986   }
987 }
988
989 function drawBoard() {
990   boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
991   drawPositionInstant();
992
993   if (cfg.sparePieces === true) {
994     if (CURRENT_ORIENTATION === 'white') {
995       sparePiecesTopEl.innerHTML = buildSparePieces('black');
996       sparePiecesBottomEl.innerHTML = buildSparePieces('white');
997     }
998     else {
999       sparePiecesTopEl.innerHTML = buildSparePieces('white');
1000       sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1001     }
1002   }
1003 }
1004
1005 // given a position and a set of moves, return a new position
1006 // with the moves executed
1007 function calculatePositionFromMoves(position, moves) {
1008   position = deepCopy(position);
1009
1010   for (var i in moves) {
1011     if (moves.hasOwnProperty(i) !== true) continue;
1012
1013     // skip the move if the position doesn't have a piece on the source square
1014     if (position.hasOwnProperty(i) !== true) continue;
1015
1016     var piece = position[i];
1017     delete position[i];
1018     position[moves[i]] = piece;
1019   }
1020
1021   return position;
1022 }
1023
1024 function setCurrentPosition(position) {
1025   var oldPos = deepCopy(CURRENT_POSITION);
1026   var newPos = deepCopy(position);
1027   var oldFen = objToFen(oldPos);
1028   var newFen = objToFen(newPos);
1029
1030   // do nothing if no change in position
1031   if (oldFen === newFen) return;
1032
1033   // run their onChange function
1034   if (cfg.hasOwnProperty('onChange') === true &&
1035     typeof cfg.onChange === 'function') {
1036     cfg.onChange(oldPos, newPos);
1037   }
1038
1039   // update state
1040   CURRENT_POSITION = position;
1041 }
1042
1043 function isXYOnSquare(x, y) {
1044   for (var i in SQUARE_ELS_OFFSETS) {
1045     if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1046
1047     var s = SQUARE_ELS_OFFSETS[i];
1048     if (x >= s.left && x < s.left + SQUARE_SIZE &&
1049         y >= s.top && y < s.top + SQUARE_SIZE) {
1050       return i;
1051     }
1052   }
1053
1054   return 'offboard';
1055 }
1056
1057 // records the XY coords of every square into memory
1058 function captureSquareOffsets() {
1059   SQUARE_ELS_OFFSETS = {};
1060
1061   for (var i in SQUARE_ELS_IDS) {
1062     if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1063
1064     SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1065   }
1066 }
1067
1068 function removeSquareHighlights() {
1069   boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1070     piece.classList.remove(CSS.highlight1);
1071     piece.classList.remove(CSS.highlight2);
1072   });
1073 }
1074
1075 function snapbackDraggedPiece() {
1076   // there is no "snapback" for spare pieces
1077   if (DRAGGED_PIECE_SOURCE === 'spare') {
1078     trashDraggedPiece();
1079     return;
1080   }
1081
1082   removeSquareHighlights();
1083
1084   // animation complete
1085   function complete() {
1086     drawPositionInstant();
1087     draggedPieceEl.style.display = 'none';
1088
1089     // run their onSnapbackEnd function
1090     if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1091       typeof cfg.onSnapbackEnd === 'function') {
1092       cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1093         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1094     }
1095   }
1096
1097   // get source square position
1098   var sourceSquarePosition =
1099     offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1100
1101   // animate the piece to the target square
1102   draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1103   requestAnimationFrame(() => {
1104     draggedPieceEl.style.transitionProperty = 'top, left';
1105     draggedPieceEl.style.transitionDuration = cfg.snapbackSpeed + 'ms';
1106     draggedPieceEl.style.top = sourceSquarePosition.top + 'px';
1107     draggedPieceEl.style.left = sourceSquarePosition.left + 'px';
1108   });
1109
1110   // set state
1111   DRAGGING_A_PIECE = false;
1112 }
1113
1114 function trashDraggedPiece() {
1115   removeSquareHighlights();
1116
1117   // remove the source piece
1118   var newPosition = deepCopy(CURRENT_POSITION);
1119   delete newPosition[DRAGGED_PIECE_SOURCE];
1120   setCurrentPosition(newPosition);
1121
1122   // redraw the position
1123   drawPositionInstant();
1124
1125   // hide the dragged piece
1126   // FIXME: support this for non-jquery
1127   //$(draggedPieceEl).fadeOut(cfg.trashSpeed);
1128
1129   // set state
1130   DRAGGING_A_PIECE = false;
1131 }
1132
1133 function dropDraggedPieceOnSquare(square) {
1134   removeSquareHighlights();
1135
1136   // update position
1137   var newPosition = deepCopy(CURRENT_POSITION);
1138   delete newPosition[DRAGGED_PIECE_SOURCE];
1139   newPosition[square] = DRAGGED_PIECE;
1140   setCurrentPosition(newPosition);
1141
1142   // get target square information
1143   var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1144
1145   // animation complete
1146   var complete = function() {
1147     drawPositionInstant();
1148     draggedPieceEl.style.display = 'none';
1149
1150     // execute their onSnapEnd function
1151     if (cfg.hasOwnProperty('onSnapEnd') === true &&
1152       typeof cfg.onSnapEnd === 'function') {
1153       requestAnimationFrame(() => {  // HACK: so that we don't add event handlers from the callback...
1154         cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1155       });
1156     }
1157   };
1158
1159   // snap the piece to the target square
1160   draggedPieceEl.addEventListener('transitionend', complete, {once: true});
1161   requestAnimationFrame(() => {
1162     draggedPieceEl.style.transitionProperty = 'top, left';
1163     draggedPieceEl.style.transitionDuration = cfg.snapSpeed + 'ms';
1164     draggedPieceEl.style.top = targetSquarePosition.top + 'px';
1165     draggedPieceEl.style.left = targetSquarePosition.left + 'px';
1166   });
1167
1168   // set state
1169   DRAGGING_A_PIECE = false;
1170 }
1171
1172 function beginDraggingPiece(source, piece, x, y) {
1173   // run their custom onDragStart function
1174   // their custom onDragStart function can cancel drag start
1175   if (typeof cfg.onDragStart === 'function' &&
1176       cfg.onDragStart(source, piece,
1177         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1178     return;
1179   }
1180
1181   // set state
1182   DRAGGING_A_PIECE = true;
1183   DRAGGED_PIECE = piece;
1184   DRAGGED_PIECE_SOURCE = source;
1185
1186   // if the piece came from spare pieces, location is offboard
1187   if (source === 'spare') {
1188     DRAGGED_PIECE_LOCATION = 'offboard';
1189   }
1190   else {
1191     DRAGGED_PIECE_LOCATION = source;
1192   }
1193
1194   // capture the x, y coords of all squares in memory
1195   captureSquareOffsets();
1196
1197   // create the dragged piece
1198   draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1199   draggedPieceEl.style.display = null;
1200   draggedPieceEl.style.position = 'absolute';
1201   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1202   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1203
1204   if (source !== 'spare') {
1205     // highlight the source square and hide the piece
1206     let square = document.getElementById(SQUARE_ELS_IDS[source]);
1207     square.classList.add(CSS.highlight1);
1208     square.querySelector('.' + CSS.piece).style.display = 'none';
1209   }
1210 }
1211
1212 function updateDraggedPiece(x, y) {
1213   // put the dragged piece over the mouse cursor
1214   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1215   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1216
1217   // get location
1218   var location = isXYOnSquare(x, y);
1219
1220   // do nothing if the location has not changed
1221   if (location === DRAGGED_PIECE_LOCATION) return;
1222
1223   // remove highlight from previous square
1224   if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1225     document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1226       .classList.remove(CSS.highlight2);
1227   }
1228
1229   // add highlight to new square
1230   if (validSquare(location) === true) {
1231     document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1232   }
1233
1234   // run onDragMove
1235   if (typeof cfg.onDragMove === 'function') {
1236     cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1237       DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1238       deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1239   }
1240
1241   // update state
1242   DRAGGED_PIECE_LOCATION = location;
1243 }
1244
1245 function stopDraggedPiece(location) {
1246   // determine what the action should be
1247   var action = 'drop';
1248   if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1249     action = 'snapback';
1250   }
1251   if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1252     action = 'trash';
1253   }
1254
1255   // run their onDrop function, which can potentially change the drop action
1256   if (cfg.hasOwnProperty('onDrop') === true &&
1257     typeof cfg.onDrop === 'function') {
1258     var newPosition = deepCopy(CURRENT_POSITION);
1259
1260     // source piece is a spare piece and position is off the board
1261     //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1262     // position has not changed; do nothing
1263
1264     // source piece is a spare piece and position is on the board
1265     if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1266       // add the piece to the board
1267       newPosition[location] = DRAGGED_PIECE;
1268     }
1269
1270     // source piece was on the board and position is off the board
1271     if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1272       // remove the piece from the board
1273       delete newPosition[DRAGGED_PIECE_SOURCE];
1274     }
1275
1276     // source piece was on the board and position is on the board
1277     if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1278       validSquare(location) === true) {
1279       // move the piece
1280       delete newPosition[DRAGGED_PIECE_SOURCE];
1281       newPosition[location] = DRAGGED_PIECE;
1282     }
1283
1284     var oldPosition = deepCopy(CURRENT_POSITION);
1285
1286     var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1287       newPosition, oldPosition, CURRENT_ORIENTATION);
1288     if (result === 'snapback' || result === 'trash') {
1289       action = result;
1290     }
1291   }
1292
1293   // do it!
1294   if (action === 'snapback') {
1295     snapbackDraggedPiece();
1296   }
1297   else if (action === 'trash') {
1298     trashDraggedPiece();
1299   }
1300   else if (action === 'drop') {
1301     dropDraggedPieceOnSquare(location);
1302   }
1303 }
1304
1305 //------------------------------------------------------------------------------
1306 // Public Methods
1307 //------------------------------------------------------------------------------
1308
1309 // clear the board
1310 widget.clear = function(useAnimation) {
1311   widget.position({}, useAnimation);
1312 };
1313
1314 /*
1315 // get or set config properties
1316 // TODO: write this, GitHub Issue #1
1317 widget.config = function(arg1, arg2) {
1318   // get the current config
1319   if (arguments.length === 0) {
1320     return deepCopy(cfg);
1321   }
1322 };
1323 */
1324
1325 // remove the widget from the page
1326 widget.destroy = function() {
1327   // remove markup
1328   containerEl.innerHTML = '';
1329   draggedPieceEl.remove();
1330 };
1331
1332 // shorthand method to get the current FEN
1333 widget.fen = function() {
1334   return widget.position('fen');
1335 };
1336
1337 // flip orientation
1338 widget.flip = function() {
1339   widget.orientation('flip');
1340 };
1341
1342 /*
1343 // TODO: write this, GitHub Issue #5
1344 widget.highlight = function() {
1345
1346 };
1347 */
1348
1349 // move pieces
1350 widget.move = function() {
1351   // no need to throw an error here; just do nothing
1352   if (arguments.length === 0) return;
1353
1354   var useAnimation = true;
1355
1356   // collect the moves into an object
1357   var moves = {};
1358   for (var i = 0; i < arguments.length; i++) {
1359     // any "false" to this function means no animations
1360     if (arguments[i] === false) {
1361       useAnimation = false;
1362       continue;
1363     }
1364
1365     // skip invalid arguments
1366     if (validMove(arguments[i]) !== true) {
1367       error(2826, 'Invalid move passed to the move method.', arguments[i]);
1368       continue;
1369     }
1370
1371     var tmp = arguments[i].split('-');
1372     moves[tmp[0]] = tmp[1];
1373   }
1374
1375   // calculate position from moves
1376   var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1377
1378   // update the board
1379   widget.position(newPos, useAnimation);
1380
1381   // return the new position object
1382   return newPos;
1383 };
1384
1385 widget.orientation = function(arg) {
1386   // no arguments, return the current orientation
1387   if (arguments.length === 0) {
1388     return CURRENT_ORIENTATION;
1389   }
1390
1391   // set to white or black
1392   if (arg === 'white' || arg === 'black') {
1393     CURRENT_ORIENTATION = arg;
1394     drawBoard();
1395     return;
1396   }
1397
1398   // flip orientation
1399   if (arg === 'flip') {
1400     CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1401     drawBoard();
1402     return;
1403   }
1404
1405   error(5482, 'Invalid value passed to the orientation method.', arg);
1406 };
1407
1408 /**
1409  * @param {!string|!Object} position
1410  * @param {boolean=} useAnimation
1411  */
1412 widget.position = function(position, useAnimation) {
1413   // no arguments, return the current position
1414   if (arguments.length === 0) {
1415     return deepCopy(CURRENT_POSITION);
1416   }
1417
1418   // get position as FEN
1419   if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1420     return objToFen(CURRENT_POSITION);
1421   }
1422
1423   // default for useAnimations is true
1424   if (useAnimation !== false) {
1425     useAnimation = true;
1426   }
1427
1428   // start position
1429   if (typeof position === 'string' && position.toLowerCase() === 'start') {
1430     position = deepCopy(START_POSITION);
1431   }
1432
1433   // convert FEN to position object
1434   if (validFen(position) === true) {
1435     position = fenToObj(position);
1436   }
1437
1438   // validate position object
1439   if (validPositionObject(position) !== true) {
1440     error(6482, 'Invalid value passed to the position method.', position);
1441     return;
1442   }
1443
1444   if (useAnimation === true) {
1445     // start the animations
1446     doAnimations(calculateAnimations(CURRENT_POSITION, position),
1447       CURRENT_POSITION, position);
1448
1449     // set the new position
1450     setCurrentPosition(position);
1451   }
1452   // instant update
1453   else {
1454     setCurrentPosition(position);
1455     drawPositionInstant();
1456   }
1457 };
1458
1459 widget.resize = function() {
1460   // calulate the new square size
1461   SQUARE_SIZE = calculateSquareSize();
1462
1463   // set board width
1464   boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1465
1466   // set drag piece size
1467   if (draggedPieceEl !== null) {
1468     draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1469     draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1470   }
1471
1472   // spare pieces
1473   if (cfg.sparePieces === true) {
1474     containerEl.querySelector('.' + CSS.sparePieces)
1475       .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1476   }
1477
1478   // redraw the board
1479   drawBoard();
1480 };
1481
1482 // set the starting position
1483 widget.start = function(useAnimation) {
1484   widget.position('start', useAnimation);
1485 };
1486
1487 //------------------------------------------------------------------------------
1488 // Browser Events
1489 //------------------------------------------------------------------------------
1490
1491 function isTouchDevice() {
1492   return ('ontouchstart' in document.documentElement);
1493 }
1494
1495 function mousedownSquare(e) {
1496   let target = e.target.closest('.' + CSS.square);
1497   if (!target) {
1498     return;
1499   }
1500
1501   // do nothing if we're not draggable
1502   if (cfg.draggable !== true) return;
1503
1504   var square = target.getAttribute('data-square');
1505
1506   // no piece on this square
1507   if (validSquare(square) !== true ||
1508       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1509     return;
1510   }
1511
1512   beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1513 }
1514
1515 function touchstartSquare(e) {
1516   let target = e.target.closest('.' + CSS.square);
1517   if (!target) {
1518     return;
1519   }
1520
1521   // do nothing if we're not draggable
1522   if (cfg.draggable !== true) return;
1523
1524   var square = target.getAttribute('data-square');
1525
1526   // no piece on this square
1527   if (validSquare(square) !== true ||
1528       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1529     return;
1530   }
1531
1532   beginDraggingPiece(square, CURRENT_POSITION[square],
1533     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1534 }
1535
1536 function mousedownSparePiece(e) {
1537   if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1538     return;
1539   }
1540
1541   // do nothing if sparePieces is not enabled
1542   if (cfg.sparePieces !== true) return;
1543
1544   var piece = e.target.getAttribute('data-piece');
1545
1546   beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1547 }
1548
1549 function touchstartSparePiece(e) {
1550   if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1551     return;
1552   }
1553
1554   // do nothing if sparePieces is not enabled
1555   if (cfg.sparePieces !== true) return;
1556
1557   var piece = e.target.getAttribute('data-piece');
1558
1559   beginDraggingPiece('spare', piece,
1560     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1561 }
1562
1563 function mousemoveWindow(e) {
1564   // do nothing if we are not dragging a piece
1565   if (DRAGGING_A_PIECE !== true) return;
1566
1567   updateDraggedPiece(e.pageX, e.pageY);
1568 }
1569
1570 function touchmoveWindow(e) {
1571   // do nothing if we are not dragging a piece
1572   if (DRAGGING_A_PIECE !== true) return;
1573
1574   // prevent screen from scrolling
1575   e.preventDefault();
1576
1577   updateDraggedPiece(e.changedTouches[0].pageX,
1578     e.changedTouches[0].pageY);
1579 }
1580
1581 function mouseupWindow(e) {
1582   // do nothing if we are not dragging a piece
1583   if (DRAGGING_A_PIECE !== true) return;
1584
1585   // get the location
1586   var location = isXYOnSquare(e.pageX, e.pageY);
1587
1588   stopDraggedPiece(location);
1589 }
1590
1591 function touchendWindow(e) {
1592   // do nothing if we are not dragging a piece
1593   if (DRAGGING_A_PIECE !== true) return;
1594
1595   // get the location
1596   var location = isXYOnSquare(e.changedTouches[0].pageX,
1597     e.changedTouches[0].pageY);
1598
1599   stopDraggedPiece(location);
1600 }
1601
1602 function mouseenterSquare(e) {
1603   let target = e.target.closest('.' + CSS.square);
1604   if (!target) {
1605     return;
1606   }
1607
1608   // do not fire this event if we are dragging a piece
1609   // NOTE: this should never happen, but it's a safeguard
1610   if (DRAGGING_A_PIECE !== false) return;
1611
1612   if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1613     typeof cfg.onMouseoverSquare !== 'function') return;
1614
1615   // get the square
1616   var square = target.getAttribute('data-square');
1617
1618   // NOTE: this should never happen; defensive
1619   if (validSquare(square) !== true) return;
1620
1621   // get the piece on this square
1622   var piece = false;
1623   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1624     piece = CURRENT_POSITION[square];
1625   }
1626
1627   // execute their function
1628   cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1629     CURRENT_ORIENTATION);
1630 }
1631
1632 function mouseleaveSquare(e) {
1633   let target = e.target.closest('.' + CSS.square);
1634   if (!target) {
1635     return;
1636   }
1637
1638   // do not fire this event if we are dragging a piece
1639   // NOTE: this should never happen, but it's a safeguard
1640   if (DRAGGING_A_PIECE !== false) return;
1641
1642   if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1643     typeof cfg.onMouseoutSquare !== 'function') return;
1644
1645   // get the square
1646   var square = target.getAttribute('data-square');
1647
1648   // NOTE: this should never happen; defensive
1649   if (validSquare(square) !== true) return;
1650
1651   // get the piece on this square
1652   var piece = false;
1653   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1654     piece = CURRENT_POSITION[square];
1655   }
1656
1657   // execute their function
1658   cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1659     CURRENT_ORIENTATION);
1660 }
1661
1662 //------------------------------------------------------------------------------
1663 // Initialization
1664 //------------------------------------------------------------------------------
1665
1666 function addEvents() {
1667   // prevent browser "image drag"
1668   let stopDefault = (e) => {
1669     if (e.target.matches('.' + CSS.piece)) {
1670       e.preventDefault();
1671     }
1672   };
1673   document.body.addEventListener('mousedown', stopDefault);
1674   document.body.addEventListener('mousemove', stopDefault);
1675
1676   // mouse drag pieces
1677   boardEl.addEventListener('mousedown', mousedownSquare);
1678   containerEl.addEventListener('mousedown', mousedownSparePiece);
1679
1680   // mouse enter / leave square
1681   boardEl.addEventListener('mouseenter', mouseenterSquare);
1682   boardEl.addEventListener('mouseleave', mouseleaveSquare);
1683
1684   window.addEventListener('mousemove', mousemoveWindow);
1685   window.addEventListener('mouseup', mouseupWindow);
1686
1687   // touch drag pieces
1688   if (isTouchDevice() === true) {
1689     boardEl.addEventListener('touchstart', touchstartSquare);
1690     containerEl.addEventListener('touchstart', touchstartSparePiece);
1691     window.addEventListener('touchmove', touchmoveWindow);
1692     window.addEventListener('touchend', touchendWindow);
1693   }
1694 }
1695
1696 function initDom() {
1697   // build board and save it in memory
1698   containerEl.innerHTML = buildBoardContainer();
1699   boardEl = containerEl.querySelector('.' + CSS.board);
1700
1701   if (cfg.sparePieces === true) {
1702     sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1703     sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1704   }
1705
1706   // create the drag piece
1707   var draggedPieceId = createId();
1708   document.body.append(buildPiece('wP', true, draggedPieceId));
1709   draggedPieceEl = document.getElementById(draggedPieceId);
1710
1711   // get the border size
1712   BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1713
1714   // set the size and draw the board
1715   widget.resize();
1716 }
1717
1718 function init() {
1719   if (checkDeps() !== true ||
1720       expandConfig() !== true) return;
1721
1722   // create unique IDs for all the elements we will create
1723   createElIds();
1724
1725   initDom();
1726   addEvents();
1727 }
1728
1729 // go time
1730 init();
1731
1732 // return the widget object
1733 return widget;
1734
1735 }; // end window.ChessBoard
1736
1737 // expose util functions
1738 window.ChessBoard.fenToObj = fenToObj;
1739 window.ChessBoard.objToFen = objToFen;
1740
1741 })(); // end anonymous wrapper