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