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