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