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