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