]> git.sesse.net Git - remoteglot/blob - www/js/chessboard-0.3.0.js
Remove all jQuery from chessboard.js that does not involve animations.
[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 = '';
720   animatedPieceEl.style.position = 'absolute';
721   animatedPieceEl.style.top = srcSquarePosition.top;
722   animatedPieceEl.style.left = srcSquarePosition.left;
723
724   // remove original piece from source square
725   srcSquareEl.querySelector('.' + CSS.piece).remove();
726
727   // on complete
728   var complete = function() {
729     // add the "real" piece to the destination square
730     destSquareEl.append(buildPiece(piece));
731
732     // remove the animated piece
733     animatedPieceEl.remove();
734
735     // run complete function
736     if (typeof completeFn === 'function') {
737       completeFn();
738     }
739   };
740
741   // animate the piece to the destination square
742   var opts = {
743     duration: cfg.moveSpeed,
744     complete: complete
745   };
746   $(animatedPieceEl).animate(destSquarePosition, opts);
747 }
748
749 function animateSparePieceToSquare(piece, dest, completeFn) {
750   var srcOffset = offset(document.getelementById(SPARE_PIECE_ELS_IDS[piece]));
751   var destSquareEl = document.getElementById(SQUARE_ELS_IDS[dest]);
752   var destOffset = offset(destSquareEl);
753
754   // create the animate piece
755   var pieceId = createId();
756   document.body.append(buildPiece(piece, true, pieceId));
757   var animatedPieceEl = document.getElementById(pieceId);
758   animatedPieceEl.style.display = '';
759   animatedPieceEl.style.position = 'absolute';
760   animatedPieceEl.style.left = srcOffset.left;
761   animatedPieceEl.style.top = srcOffset.top;
762
763   // on complete
764   var complete = function() {
765     // add the "real" piece to the destination square
766     destSquareEl.querySelector('.' + CSS.piece).remove();
767     destSquareEl.append(buildPiece(piece));
768
769     // remove the animated piece
770     animatedPieceEl.remove();
771
772     // run complete function
773     if (typeof completeFn === 'function') {
774       completeFn();
775     }
776   };
777
778   // animate the piece to the destination square
779   var opts = {
780     duration: cfg.moveSpeed,
781     complete: complete
782   };
783   $(animatedPieceEl).animate(destOffset, opts);
784 }
785
786 // execute an array of animations
787 function doAnimations(a, oldPos, newPos) {
788   ANIMATION_HAPPENING = true;
789
790   var numFinished = 0;
791   function onFinish() {
792     numFinished++;
793
794     // exit if all the animations aren't finished
795     if (numFinished !== a.length) return;
796
797     drawPositionInstant();
798     ANIMATION_HAPPENING = false;
799
800     // run their onMoveEnd function
801     if (cfg.hasOwnProperty('onMoveEnd') === true &&
802       typeof cfg.onMoveEnd === 'function') {
803       cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
804     }
805   }
806
807   for (var i = 0; i < a.length; i++) {
808     // clear a piece
809     if (a[i].type === 'clear') {
810       $('#' + SQUARE_ELS_IDS[a[i].square] + ' .' + CSS.piece)
811         .fadeOut(cfg.trashSpeed, onFinish);
812     }
813
814     // add a piece (no spare pieces)
815     if (a[i].type === 'add' && cfg.sparePieces !== true) {
816       $('#' + SQUARE_ELS_IDS[a[i].square])
817         .append(buildPiece(a[i].piece, true))
818         .find('.' + CSS.piece)
819         .fadeIn(cfg.appearSpeed, onFinish);
820     }
821
822     // add a piece from a spare piece
823     if (a[i].type === 'add' && cfg.sparePieces === true) {
824       animateSparePieceToSquare(a[i].piece, a[i].square, onFinish);
825     }
826
827     // move a piece
828     if (a[i].type === 'move') {
829       animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
830         onFinish);
831     }
832   }
833 }
834
835 // returns the distance between two squares
836 function squareDistance(s1, s2) {
837   s1 = s1.split('');
838   var s1x = COLUMNS.indexOf(s1[0]) + 1;
839   var s1y = parseInt(s1[1], 10);
840
841   s2 = s2.split('');
842   var s2x = COLUMNS.indexOf(s2[0]) + 1;
843   var s2y = parseInt(s2[1], 10);
844
845   var xDelta = Math.abs(s1x - s2x);
846   var yDelta = Math.abs(s1y - s2y);
847
848   if (xDelta >= yDelta) return xDelta;
849   return yDelta;
850 }
851
852 // returns an array of closest squares from square
853 function createRadius(square) {
854   var squares = [];
855
856   // calculate distance of all squares
857   for (var i = 0; i < 8; i++) {
858     for (var j = 0; j < 8; j++) {
859       var s = COLUMNS[i] + (j + 1);
860
861       // skip the square we're starting from
862       if (square === s) continue;
863
864       squares.push({
865         square: s,
866         distance: squareDistance(square, s)
867       });
868     }
869   }
870
871   // sort by distance
872   squares.sort(function(a, b) {
873     return a.distance - b.distance;
874   });
875
876   // just return the square code
877   var squares2 = [];
878   for (var i = 0; i < squares.length; i++) {
879     squares2.push(squares[i].square);
880   }
881
882   return squares2;
883 }
884
885 // returns the square of the closest instance of piece
886 // returns false if no instance of piece is found in position
887 function findClosestPiece(position, piece, square) {
888   // create array of closest squares from square
889   var closestSquares = createRadius(square);
890
891   // search through the position in order of distance for the piece
892   for (var i = 0; i < closestSquares.length; i++) {
893     var s = closestSquares[i];
894
895     if (position.hasOwnProperty(s) === true && position[s] === piece) {
896       return s;
897     }
898   }
899
900   return false;
901 }
902
903 // calculate an array of animations that need to happen in order to get
904 // from pos1 to pos2
905 function calculateAnimations(pos1, pos2) {
906   // make copies of both
907   pos1 = deepCopy(pos1);
908   pos2 = deepCopy(pos2);
909
910   var animations = [];
911   var squaresMovedTo = {};
912
913   // remove pieces that are the same in both positions
914   for (var i in pos2) {
915     if (pos2.hasOwnProperty(i) !== true) continue;
916
917     if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
918       delete pos1[i];
919       delete pos2[i];
920     }
921   }
922
923   // find all the "move" animations
924   for (var i in pos2) {
925     if (pos2.hasOwnProperty(i) !== true) continue;
926
927     var closestPiece = findClosestPiece(pos1, pos2[i], i);
928     if (closestPiece !== false) {
929       animations.push({
930         type: 'move',
931         source: closestPiece,
932         destination: i,
933         piece: pos2[i]
934       });
935
936       delete pos1[closestPiece];
937       delete pos2[i];
938       squaresMovedTo[i] = true;
939     }
940   }
941
942   // add pieces to pos2
943   for (var i in pos2) {
944     if (pos2.hasOwnProperty(i) !== true) continue;
945
946     animations.push({
947       type: 'add',
948       square: i,
949       piece: pos2[i]
950     })
951
952     delete pos2[i];
953   }
954
955   // clear pieces from pos1
956   for (var i in pos1) {
957     if (pos1.hasOwnProperty(i) !== true) continue;
958
959     // do not clear a piece if it is on a square that is the result
960     // of a "move", ie: a piece capture
961     if (squaresMovedTo.hasOwnProperty(i) === true) continue;
962
963     animations.push({
964       type: 'clear',
965       square: i,
966       piece: pos1[i]
967     });
968
969     delete pos1[i];
970   }
971
972   return animations;
973 }
974
975 //------------------------------------------------------------------------------
976 // Control Flow
977 //------------------------------------------------------------------------------
978
979 function drawPositionInstant() {
980   // clear the board
981   boardEl.querySelectorAll('.' + CSS.piece).forEach((piece) => piece.remove());
982
983   // add the pieces
984   for (var i in CURRENT_POSITION) {
985     if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
986
987     document.getElementById(SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
988   }
989 }
990
991 function drawBoard() {
992   boardEl.innerHTML = buildBoard(CURRENT_ORIENTATION);
993   drawPositionInstant();
994
995   if (cfg.sparePieces === true) {
996     if (CURRENT_ORIENTATION === 'white') {
997       sparePiecesTopEl.innerHTML = buildSparePieces('black');
998       sparePiecesBottomEl.innerHTML = buildSparePieces('white');
999     }
1000     else {
1001       sparePiecesTopEl.innerHTML = buildSparePieces('white');
1002       sparePiecesBottomEl.innerHTML = buildSparePieces('black');
1003     }
1004   }
1005 }
1006
1007 // given a position and a set of moves, return a new position
1008 // with the moves executed
1009 function calculatePositionFromMoves(position, moves) {
1010   position = deepCopy(position);
1011
1012   for (var i in moves) {
1013     if (moves.hasOwnProperty(i) !== true) continue;
1014
1015     // skip the move if the position doesn't have a piece on the source square
1016     if (position.hasOwnProperty(i) !== true) continue;
1017
1018     var piece = position[i];
1019     delete position[i];
1020     position[moves[i]] = piece;
1021   }
1022
1023   return position;
1024 }
1025
1026 function setCurrentPosition(position) {
1027   var oldPos = deepCopy(CURRENT_POSITION);
1028   var newPos = deepCopy(position);
1029   var oldFen = objToFen(oldPos);
1030   var newFen = objToFen(newPos);
1031
1032   // do nothing if no change in position
1033   if (oldFen === newFen) return;
1034
1035   // run their onChange function
1036   if (cfg.hasOwnProperty('onChange') === true &&
1037     typeof cfg.onChange === 'function') {
1038     cfg.onChange(oldPos, newPos);
1039   }
1040
1041   // update state
1042   CURRENT_POSITION = position;
1043 }
1044
1045 function isXYOnSquare(x, y) {
1046   for (var i in SQUARE_ELS_OFFSETS) {
1047     if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
1048
1049     var s = SQUARE_ELS_OFFSETS[i];
1050     if (x >= s.left && x < s.left + SQUARE_SIZE &&
1051         y >= s.top && y < s.top + SQUARE_SIZE) {
1052       return i;
1053     }
1054   }
1055
1056   return 'offboard';
1057 }
1058
1059 // records the XY coords of every square into memory
1060 function captureSquareOffsets() {
1061   SQUARE_ELS_OFFSETS = {};
1062
1063   for (var i in SQUARE_ELS_IDS) {
1064     if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1065
1066     SQUARE_ELS_OFFSETS[i] = offset(document.getElementById(SQUARE_ELS_IDS[i]));
1067   }
1068 }
1069
1070 function removeSquareHighlights() {
1071   boardEl.querySelectorAll('.' + CSS.square).forEach((piece) => {
1072     piece.classList.remove(CSS.highlight1);
1073     piece.classList.remove(CSS.highlight2);
1074   });
1075 }
1076
1077 function snapbackDraggedPiece() {
1078   // there is no "snapback" for spare pieces
1079   if (DRAGGED_PIECE_SOURCE === 'spare') {
1080     trashDraggedPiece();
1081     return;
1082   }
1083
1084   removeSquareHighlights();
1085
1086   // animation complete
1087   function complete() {
1088     drawPositionInstant();
1089     draggedPieceEl.style.display = 'none';
1090
1091     // run their onSnapbackEnd function
1092     if (cfg.hasOwnProperty('onSnapbackEnd') === true &&
1093       typeof cfg.onSnapbackEnd === 'function') {
1094       cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE,
1095         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1096     }
1097   }
1098
1099   // get source square position
1100   var sourceSquarePosition =
1101     offset(document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]));
1102
1103   // animate the piece to the target square
1104   var opts = {
1105     duration: cfg.snapbackSpeed,
1106     complete: complete
1107   };
1108   $(draggedPieceEl).animate(sourceSquarePosition, opts);
1109
1110   // set state
1111   DRAGGING_A_PIECE = false;
1112 }
1113
1114 function trashDraggedPiece() {
1115   removeSquareHighlights();
1116
1117   // remove the source piece
1118   var newPosition = deepCopy(CURRENT_POSITION);
1119   delete newPosition[DRAGGED_PIECE_SOURCE];
1120   setCurrentPosition(newPosition);
1121
1122   // redraw the position
1123   drawPositionInstant();
1124
1125   // hide the dragged piece
1126   $(draggedPieceEl).fadeOut(cfg.trashSpeed);
1127
1128   // set state
1129   DRAGGING_A_PIECE = false;
1130 }
1131
1132 function dropDraggedPieceOnSquare(square) {
1133   removeSquareHighlights();
1134
1135   // update position
1136   var newPosition = deepCopy(CURRENT_POSITION);
1137   delete newPosition[DRAGGED_PIECE_SOURCE];
1138   newPosition[square] = DRAGGED_PIECE;
1139   setCurrentPosition(newPosition);
1140
1141   // get target square information
1142   var targetSquarePosition = offset(document.getElementById(SQUARE_ELS_IDS[square]));
1143
1144   // animation complete
1145   var complete = function() {
1146     drawPositionInstant();
1147     draggedPieceEl.style.display = 'none';
1148
1149     // execute their onSnapEnd function
1150     if (cfg.hasOwnProperty('onSnapEnd') === true &&
1151       typeof cfg.onSnapEnd === 'function') {
1152       cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE);
1153     }
1154   };
1155
1156   // snap the piece to the target square
1157   var opts = {
1158     duration: cfg.snapSpeed,
1159     complete: complete
1160   };
1161   $(draggedPieceEl).animate(targetSquarePosition, opts);
1162
1163   // set state
1164   DRAGGING_A_PIECE = false;
1165 }
1166
1167 function beginDraggingPiece(source, piece, x, y) {
1168   // run their custom onDragStart function
1169   // their custom onDragStart function can cancel drag start
1170   if (typeof cfg.onDragStart === 'function' &&
1171       cfg.onDragStart(source, piece,
1172         deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) {
1173     return;
1174   }
1175
1176   // set state
1177   DRAGGING_A_PIECE = true;
1178   DRAGGED_PIECE = piece;
1179   DRAGGED_PIECE_SOURCE = source;
1180
1181   // if the piece came from spare pieces, location is offboard
1182   if (source === 'spare') {
1183     DRAGGED_PIECE_LOCATION = 'offboard';
1184   }
1185   else {
1186     DRAGGED_PIECE_LOCATION = source;
1187   }
1188
1189   // capture the x, y coords of all squares in memory
1190   captureSquareOffsets();
1191
1192   // create the dragged piece
1193   draggedPieceEl.setAttribute('src', buildPieceImgSrc(piece));
1194   draggedPieceEl.style.display = null;
1195   draggedPieceEl.style.position = 'absolute';
1196   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1197   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1198
1199   if (source !== 'spare') {
1200     // highlight the source square and hide the piece
1201     let square = document.getElementById(SQUARE_ELS_IDS[source]);
1202     square.classList.add(CSS.highlight1);
1203     square.querySelector('.' + CSS.piece).style.display = 'none';
1204   }
1205 }
1206
1207 function updateDraggedPiece(x, y) {
1208   // put the dragged piece over the mouse cursor
1209   draggedPieceEl.style.left = (x - (SQUARE_SIZE / 2)) + 'px';
1210   draggedPieceEl.style.top = (y - (SQUARE_SIZE / 2)) + 'px';
1211
1212   // get location
1213   var location = isXYOnSquare(x, y);
1214
1215   // do nothing if the location has not changed
1216   if (location === DRAGGED_PIECE_LOCATION) return;
1217
1218   // remove highlight from previous square
1219   if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1220     document.getElementById(SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1221       .classList.remove(CSS.highlight2);
1222   }
1223
1224   // add highlight to new square
1225   if (validSquare(location) === true) {
1226     document.getElementById(SQUARE_ELS_IDS[location]).classList.add(CSS.highlight2);
1227   }
1228
1229   // run onDragMove
1230   if (typeof cfg.onDragMove === 'function') {
1231     cfg.onDragMove(location, DRAGGED_PIECE_LOCATION,
1232       DRAGGED_PIECE_SOURCE, DRAGGED_PIECE,
1233       deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION);
1234   }
1235
1236   // update state
1237   DRAGGED_PIECE_LOCATION = location;
1238 }
1239
1240 function stopDraggedPiece(location) {
1241   // determine what the action should be
1242   var action = 'drop';
1243   if (location === 'offboard' && cfg.dropOffBoard === 'snapback') {
1244     action = 'snapback';
1245   }
1246   if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
1247     action = 'trash';
1248   }
1249
1250   // run their onDrop function, which can potentially change the drop action
1251   if (cfg.hasOwnProperty('onDrop') === true &&
1252     typeof cfg.onDrop === 'function') {
1253     var newPosition = deepCopy(CURRENT_POSITION);
1254
1255     // source piece is a spare piece and position is off the board
1256     //if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...}
1257     // position has not changed; do nothing
1258
1259     // source piece is a spare piece and position is on the board
1260     if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) {
1261       // add the piece to the board
1262       newPosition[location] = DRAGGED_PIECE;
1263     }
1264
1265     // source piece was on the board and position is off the board
1266     if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') {
1267       // remove the piece from the board
1268       delete newPosition[DRAGGED_PIECE_SOURCE];
1269     }
1270
1271     // source piece was on the board and position is on the board
1272     if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1273       validSquare(location) === true) {
1274       // move the piece
1275       delete newPosition[DRAGGED_PIECE_SOURCE];
1276       newPosition[location] = DRAGGED_PIECE;
1277     }
1278
1279     var oldPosition = deepCopy(CURRENT_POSITION);
1280
1281     var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1282       newPosition, oldPosition, CURRENT_ORIENTATION);
1283     if (result === 'snapback' || result === 'trash') {
1284       action = result;
1285     }
1286   }
1287
1288   // do it!
1289   if (action === 'snapback') {
1290     snapbackDraggedPiece();
1291   }
1292   else if (action === 'trash') {
1293     trashDraggedPiece();
1294   }
1295   else if (action === 'drop') {
1296     dropDraggedPieceOnSquare(location);
1297   }
1298 }
1299
1300 //------------------------------------------------------------------------------
1301 // Public Methods
1302 //------------------------------------------------------------------------------
1303
1304 // clear the board
1305 widget.clear = function(useAnimation) {
1306   widget.position({}, useAnimation);
1307 };
1308
1309 /*
1310 // get or set config properties
1311 // TODO: write this, GitHub Issue #1
1312 widget.config = function(arg1, arg2) {
1313   // get the current config
1314   if (arguments.length === 0) {
1315     return deepCopy(cfg);
1316   }
1317 };
1318 */
1319
1320 // remove the widget from the page
1321 widget.destroy = function() {
1322   // remove markup
1323   containerEl.innerHTML = '';
1324   draggedPieceEl.remove();
1325 };
1326
1327 // shorthand method to get the current FEN
1328 widget.fen = function() {
1329   return widget.position('fen');
1330 };
1331
1332 // flip orientation
1333 widget.flip = function() {
1334   widget.orientation('flip');
1335 };
1336
1337 /*
1338 // TODO: write this, GitHub Issue #5
1339 widget.highlight = function() {
1340
1341 };
1342 */
1343
1344 // move pieces
1345 widget.move = function() {
1346   // no need to throw an error here; just do nothing
1347   if (arguments.length === 0) return;
1348
1349   var useAnimation = true;
1350
1351   // collect the moves into an object
1352   var moves = {};
1353   for (var i = 0; i < arguments.length; i++) {
1354     // any "false" to this function means no animations
1355     if (arguments[i] === false) {
1356       useAnimation = false;
1357       continue;
1358     }
1359
1360     // skip invalid arguments
1361     if (validMove(arguments[i]) !== true) {
1362       error(2826, 'Invalid move passed to the move method.', arguments[i]);
1363       continue;
1364     }
1365
1366     var tmp = arguments[i].split('-');
1367     moves[tmp[0]] = tmp[1];
1368   }
1369
1370   // calculate position from moves
1371   var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1372
1373   // update the board
1374   widget.position(newPos, useAnimation);
1375
1376   // return the new position object
1377   return newPos;
1378 };
1379
1380 widget.orientation = function(arg) {
1381   // no arguments, return the current orientation
1382   if (arguments.length === 0) {
1383     return CURRENT_ORIENTATION;
1384   }
1385
1386   // set to white or black
1387   if (arg === 'white' || arg === 'black') {
1388     CURRENT_ORIENTATION = arg;
1389     drawBoard();
1390     return;
1391   }
1392
1393   // flip orientation
1394   if (arg === 'flip') {
1395     CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1396     drawBoard();
1397     return;
1398   }
1399
1400   error(5482, 'Invalid value passed to the orientation method.', arg);
1401 };
1402
1403 /**
1404  * @param {!string|!Object} position
1405  * @param {boolean=} useAnimation
1406  */
1407 widget.position = function(position, useAnimation) {
1408   // no arguments, return the current position
1409   if (arguments.length === 0) {
1410     return deepCopy(CURRENT_POSITION);
1411   }
1412
1413   // get position as FEN
1414   if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1415     return objToFen(CURRENT_POSITION);
1416   }
1417
1418   // default for useAnimations is true
1419   if (useAnimation !== false) {
1420     useAnimation = true;
1421   }
1422
1423   // start position
1424   if (typeof position === 'string' && position.toLowerCase() === 'start') {
1425     position = deepCopy(START_POSITION);
1426   }
1427
1428   // convert FEN to position object
1429   if (validFen(position) === true) {
1430     position = fenToObj(position);
1431   }
1432
1433   // validate position object
1434   if (validPositionObject(position) !== true) {
1435     error(6482, 'Invalid value passed to the position method.', position);
1436     return;
1437   }
1438
1439   if (useAnimation === true) {
1440     // start the animations
1441     doAnimations(calculateAnimations(CURRENT_POSITION, position),
1442       CURRENT_POSITION, position);
1443
1444     // set the new position
1445     setCurrentPosition(position);
1446   }
1447   // instant update
1448   else {
1449     setCurrentPosition(position);
1450     drawPositionInstant();
1451   }
1452 };
1453
1454 widget.resize = function() {
1455   // calulate the new square size
1456   SQUARE_SIZE = calculateSquareSize();
1457
1458   // set board width
1459   boardEl.style.width = (SQUARE_SIZE * 8) + 'px';
1460
1461   // set drag piece size
1462   if (draggedPieceEl !== null) {
1463     draggedPieceEl.style.height = SQUARE_SIZE + 'px';
1464     draggedPieceEl.style.width = SQUARE_SIZE + 'px';
1465   }
1466
1467   // spare pieces
1468   if (cfg.sparePieces === true) {
1469     containerEl.querySelector('.' + CSS.sparePieces)
1470       .style.paddingLeft = (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px';
1471   }
1472
1473   // redraw the board
1474   drawBoard();
1475 };
1476
1477 // set the starting position
1478 widget.start = function(useAnimation) {
1479   widget.position('start', useAnimation);
1480 };
1481
1482 //------------------------------------------------------------------------------
1483 // Browser Events
1484 //------------------------------------------------------------------------------
1485
1486 function isTouchDevice() {
1487   return ('ontouchstart' in document.documentElement);
1488 }
1489
1490 function mousedownSquare(e) {
1491   let target = e.target.closest('.' + CSS.square);
1492   if (!target) {
1493     return;
1494   }
1495
1496   // do nothing if we're not draggable
1497   if (cfg.draggable !== true) return;
1498
1499   var square = target.getAttribute('data-square');
1500
1501   // no piece on this square
1502   if (validSquare(square) !== true ||
1503       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1504     return;
1505   }
1506
1507   beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1508 }
1509
1510 function touchstartSquare(e) {
1511   let target = e.target.closest('.' + CSS.square);
1512   if (!target) {
1513     return;
1514   }
1515
1516   // do nothing if we're not draggable
1517   if (cfg.draggable !== true) return;
1518
1519   var square = target.getAttribute('data-square');
1520
1521   // no piece on this square
1522   if (validSquare(square) !== true ||
1523       CURRENT_POSITION.hasOwnProperty(square) !== true) {
1524     return;
1525   }
1526
1527   e = e.originalEvent;
1528   beginDraggingPiece(square, CURRENT_POSITION[square],
1529     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1530 }
1531
1532 function mousedownSparePiece(e) {
1533   if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1534     return;
1535   }
1536
1537   // do nothing if sparePieces is not enabled
1538   if (cfg.sparePieces !== true) return;
1539
1540   var piece = e.target.getAttribute('data-piece');
1541
1542   beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1543 }
1544
1545 function touchstartSparePiece(e) {
1546   if (!e.target.matches('.' + CSS.sparePieces + ' .' + CSS.piece)) {
1547     return;
1548   }
1549
1550   // do nothing if sparePieces is not enabled
1551   if (cfg.sparePieces !== true) return;
1552
1553   var piece = e.target.getAttribute('data-piece');
1554
1555   e = e.originalEvent;
1556   beginDraggingPiece('spare', piece,
1557     e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1558 }
1559
1560 function mousemoveWindow(e) {
1561   // do nothing if we are not dragging a piece
1562   if (DRAGGING_A_PIECE !== true) return;
1563
1564   updateDraggedPiece(e.pageX, e.pageY);
1565 }
1566
1567 function touchmoveWindow(e) {
1568   // do nothing if we are not dragging a piece
1569   if (DRAGGING_A_PIECE !== true) return;
1570
1571   // prevent screen from scrolling
1572   e.preventDefault();
1573
1574   updateDraggedPiece(e.originalEvent.changedTouches[0].pageX,
1575     e.originalEvent.changedTouches[0].pageY);
1576 }
1577
1578 function mouseupWindow(e) {
1579   // do nothing if we are not dragging a piece
1580   if (DRAGGING_A_PIECE !== true) return;
1581
1582   // get the location
1583   var location = isXYOnSquare(e.pageX, e.pageY);
1584
1585   stopDraggedPiece(location);
1586 }
1587
1588 function touchendWindow(e) {
1589   // do nothing if we are not dragging a piece
1590   if (DRAGGING_A_PIECE !== true) return;
1591
1592   // get the location
1593   var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX,
1594     e.originalEvent.changedTouches[0].pageY);
1595
1596   stopDraggedPiece(location);
1597 }
1598
1599 function mouseenterSquare(e) {
1600   let target = e.target.closest('.' + CSS.square);
1601   if (!target) {
1602     return;
1603   }
1604
1605   // do not fire this event if we are dragging a piece
1606   // NOTE: this should never happen, but it's a safeguard
1607   if (DRAGGING_A_PIECE !== false) return;
1608
1609   if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1610     typeof cfg.onMouseoverSquare !== 'function') return;
1611
1612   // get the square
1613   var square = target.getAttribute('data-square');
1614
1615   // NOTE: this should never happen; defensive
1616   if (validSquare(square) !== true) return;
1617
1618   // get the piece on this square
1619   var piece = false;
1620   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1621     piece = CURRENT_POSITION[square];
1622   }
1623
1624   // execute their function
1625   cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1626     CURRENT_ORIENTATION);
1627 }
1628
1629 function mouseleaveSquare(e) {
1630   let target = e.target.closest('.' + CSS.square);
1631   if (!target) {
1632     return;
1633   }
1634
1635   // do not fire this event if we are dragging a piece
1636   // NOTE: this should never happen, but it's a safeguard
1637   if (DRAGGING_A_PIECE !== false) return;
1638
1639   if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1640     typeof cfg.onMouseoutSquare !== 'function') return;
1641
1642   // get the square
1643   var square = target.getAttribute('data-square');
1644
1645   // NOTE: this should never happen; defensive
1646   if (validSquare(square) !== true) return;
1647
1648   // get the piece on this square
1649   var piece = false;
1650   if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1651     piece = CURRENT_POSITION[square];
1652   }
1653
1654   // execute their function
1655   cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1656     CURRENT_ORIENTATION);
1657 }
1658
1659 //------------------------------------------------------------------------------
1660 // Initialization
1661 //------------------------------------------------------------------------------
1662
1663 function addEvents() {
1664   // prevent browser "image drag"
1665   let stopDefault = (e) => {
1666     if (e.target.matches('.' + CSS.piece)) {
1667       e.preventDefault();
1668     }
1669   };
1670   document.body.addEventListener('mousedown', stopDefault);
1671   document.body.addEventListener('mousemove', stopDefault);
1672
1673   // mouse drag pieces
1674   boardEl.addEventListener('mousedown', mousedownSquare);
1675   containerEl.addEventListener('mousedown', mousedownSparePiece);
1676
1677   // mouse enter / leave square
1678   boardEl.addEventListener('mouseenter', mouseenterSquare);
1679   boardEl.addEventListener('mouseleave', mouseleaveSquare);
1680
1681   window.addEventListener('mousemove', mousemoveWindow);
1682   window.addEventListener('mouseup', mouseupWindow);
1683
1684   // touch drag pieces
1685   if (isTouchDevice() === true) {
1686     boardEl.addEventListener('touchstart', touchstartSquare);
1687     containerEl.addEventListener('touchstart', touchstartSparePiece);
1688     window.addEventListener('touchmove', touchmoveWindow);
1689     window.addEventListener('touchend', touchendWindow);
1690   }
1691 }
1692
1693 function initDom() {
1694   // build board and save it in memory
1695   containerEl.innerHTML = buildBoardContainer();
1696   boardEl = containerEl.querySelector('.' + CSS.board);
1697
1698   if (cfg.sparePieces === true) {
1699     sparePiecesTopEl = containerEl.querySelector('.' + CSS.sparePiecesTop);
1700     sparePiecesBottomEl = containerEl.querySelector('.' + CSS.sparePiecesBottom);
1701   }
1702
1703   // create the drag piece
1704   var draggedPieceId = createId();
1705   document.body.append(buildPiece('wP', true, draggedPieceId));
1706   draggedPieceEl = document.getElementById(draggedPieceId);
1707
1708   // get the border size
1709   BOARD_BORDER_SIZE = parseInt(boardEl.style.borderLeftWidth, 10);
1710
1711   // set the size and draw the board
1712   widget.resize();
1713 }
1714
1715 function init() {
1716   if (checkDeps() !== true ||
1717       expandConfig() !== true) return;
1718
1719   // create unique IDs for all the elements we will create
1720   createElIds();
1721
1722   initDom();
1723   addEvents();
1724 }
1725
1726 // go time
1727 init();
1728
1729 // return the widget object
1730 return widget;
1731
1732 }; // end window.ChessBoard
1733
1734 // expose util functions
1735 window.ChessBoard.fenToObj = fenToObj;
1736 window.ChessBoard.objToFen = objToFen;
1737
1738 })(); // end anonymous wrapper