4 * Copyright 2013 Chris Oakman
5 * Released under the MIT license
6 * http://chessboardjs.com/license
11 // start anonymous scope
15 //------------------------------------------------------------------------------
16 // Chess Util Functions
17 //------------------------------------------------------------------------------
18 var COLUMNS = 'abcdefgh'.split('');
20 function validMove(move) {
21 // move should be a string
22 if (typeof move !== 'string') return false;
24 // move should be in the form of "e2-e4", "f6-d5"
25 var tmp = move.split('-');
26 if (tmp.length !== 2) return false;
28 return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true);
31 function validSquare(square) {
32 if (typeof square !== 'string') return false;
33 return (square.search(/^[a-h][1-8]$/) !== -1);
36 function validPieceCode(code) {
37 if (typeof code !== 'string') return false;
38 return (code.search(/^[bw][KQRNBP]$/) !== -1);
41 // TODO: this whole function could probably be replaced with a single regex
42 function validFen(fen) {
43 if (typeof fen !== 'string') return false;
45 // cut off any move, castling, etc info from the end
46 // we're only interested in position information
47 fen = fen.replace(/ .+$/, '');
49 // FEN should be 8 sections separated by slashes
50 var chunks = fen.split('/');
51 if (chunks.length !== 8) return false;
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) {
65 function validPositionObject(pos) {
66 if (typeof pos !== 'object') return false;
69 if (pos.hasOwnProperty(i) !== true) continue;
71 if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) {
79 // convert FEN piece code to bP, wK, etc
80 function fenToPieceCode(piece) {
82 if (piece.toLowerCase() === piece) {
83 return 'b' + piece.toUpperCase();
87 return 'w' + piece.toUpperCase();
90 // convert bP, wK, etc code to FEN structure
91 function pieceCodeToFen(piece) {
92 var tmp = piece.split('');
96 return tmp[1].toUpperCase();
100 return tmp[1].toLowerCase();
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) {
110 // cut off any move, castling, etc info from the end
111 // we're only interested in position information
112 fen = fen.replace(/ .+$/, '');
114 var rows = fen.split('/');
118 for (var i = 0; i < 8; i++) {
119 var row = rows[i].split('');
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;
131 var square = COLUMNS[colIndex] + currentRow;
132 position[square] = fenToPieceCode(row[j]);
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) {
153 for (var i = 0; i < 8; i++) {
154 for (var j = 0; j < 8; j++) {
155 var square = COLUMNS[j] + currentRow;
158 if (obj.hasOwnProperty(square) === true) {
159 fen += pieceCodeToFen(obj[square]);
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');
188 window.ChessBoard = window.ChessBoard || function(containerElOrId, cfg) {
193 //------------------------------------------------------------------------------
195 //------------------------------------------------------------------------------
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);
201 // use unique class names to prevent clashing with anything else on the page
202 // and simplify selectors
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',
214 sparePieces: 'spare-pieces-7492f',
215 sparePiecesBottom: 'spare-pieces-bottom-ae20f',
216 sparePiecesTop: 'spare-pieces-top-4028b',
217 square: 'square-55d63'
220 CSSColor['white'] = 'white-1e1d7';
221 CSSColor['black'] = 'black-3c85d';
223 //------------------------------------------------------------------------------
224 // Module Scope Variables
225 //------------------------------------------------------------------------------
234 // constructor return object
237 //------------------------------------------------------------------------------
239 //------------------------------------------------------------------------------
241 var ANIMATION_HAPPENING = false,
242 BOARD_BORDER_SIZE = 2,
243 CURRENT_ORIENTATION = 'white',
244 CURRENT_POSITION = {},
247 DRAGGED_PIECE_LOCATION,
248 DRAGGED_PIECE_SOURCE,
249 DRAGGING_A_PIECE = false,
250 SPARE_PIECE_ELS_IDS = {},
254 //------------------------------------------------------------------------------
256 //------------------------------------------------------------------------------
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);
266 function deepCopy(thing) {
267 return JSON.parse(JSON.stringify(thing));
270 function parseSemVer(version) {
271 var tmp = version.split('.');
273 major: parseInt(tmp[0], 10),
274 minor: parseInt(tmp[1], 10),
275 patch: parseInt(tmp[2], 10)
279 // returns true if version is >= minimum
280 function compareSemVer(version, minimum) {
281 version = parseSemVer(version);
282 minimum = parseSemVer(minimum);
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;
289 return (versionNum >= minimumNum);
292 //------------------------------------------------------------------------------
293 // Validation / Errors
294 //------------------------------------------------------------------------------
296 function error(code, msg, obj) {
297 // do nothing if showErrors is not set
298 if (cfg.hasOwnProperty('showErrors') !== true ||
299 cfg.showErrors === false) {
303 var errorText = 'ChessBoard Error ' + code + ': ' + msg;
306 if (cfg.showErrors === 'console' &&
307 typeof console === 'object' &&
308 typeof console.log === 'function') {
309 console.log(errorText);
310 if (arguments.length >= 2) {
317 if (cfg.showErrors === 'alert') {
319 errorText += '\n\n' + JSON.stringify(obj);
321 window.alert(errorText);
326 if (typeof cfg.showErrors === 'function') {
327 cfg.showErrors(code, msg, obj);
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') {
336 if (containerElOrId === '') {
337 window.alert('ChessBoard Error 1001: ' +
338 'The first argument to ChessBoard() cannot be an empty string.' +
343 // make sure the container element exists in the DOM
344 var el = document.getElementById(containerElOrId);
346 window.alert('ChessBoard Error 1002: Element with id "' +
347 containerElOrId + '" does not exist in the DOM.' +
352 // set the containerEl
356 // else it must be something that becomes a jQuery collection
358 // ie: a single DOM node or jQuery object
360 containerEl = $(containerElOrId);
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.' +
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...');
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...');
391 function validAnimationSpeed(speed) {
392 if (speed === 'fast' || speed === 'slow') {
396 if ((parseInt(speed, 10) + '') !== (speed + '')) {
403 // validate config / set default options
404 function expandConfig() {
405 if (typeof cfg === 'string' || validPositionObject(cfg) === true) {
411 // default for orientation is white
412 if (cfg.orientation !== 'black') {
413 cfg.orientation = 'white';
415 CURRENT_ORIENTATION = cfg.orientation;
417 // default for showNotation is true
418 if (cfg.showNotation !== false) {
419 cfg.showNotation = true;
422 // default for draggable is false
423 if (cfg.draggable !== true) {
424 cfg.draggable = false;
427 // default for dropOffBoard is 'snapback'
428 if (cfg.dropOffBoard !== 'trash') {
429 cfg.dropOffBoard = 'snapback';
432 // default for sparePieces is false
433 if (cfg.sparePieces !== true) {
434 cfg.sparePieces = false;
437 // draggable must be true if sparePieces is enabled
438 if (cfg.sparePieces === true) {
439 cfg.draggable = true;
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';
450 if (cfg.hasOwnProperty('appearSpeed') !== true ||
451 validAnimationSpeed(cfg.appearSpeed) !== true) {
452 cfg.appearSpeed = 200;
454 if (cfg.hasOwnProperty('moveSpeed') !== true ||
455 validAnimationSpeed(cfg.moveSpeed) !== true) {
458 if (cfg.hasOwnProperty('snapbackSpeed') !== true ||
459 validAnimationSpeed(cfg.snapbackSpeed) !== true) {
460 cfg.snapbackSpeed = 50;
462 if (cfg.hasOwnProperty('snapSpeed') !== true ||
463 validAnimationSpeed(cfg.snapSpeed) !== true) {
466 if (cfg.hasOwnProperty('trashSpeed') !== true ||
467 validAnimationSpeed(cfg.trashSpeed) !== true) {
468 cfg.trashSpeed = 100;
471 // make sure position is valid
472 if (cfg.hasOwnProperty('position') === true) {
473 if (cfg.position === 'start') {
474 CURRENT_POSITION = deepCopy(START_POSITION);
477 else if (validFen(cfg.position) === true) {
478 CURRENT_POSITION = fenToObj(cfg.position);
481 else if (validPositionObject(cfg.position) === true) {
482 CURRENT_POSITION = deepCopy(cfg.position);
486 error(7263, 'Invalid value passed to config.position.', cfg.position);
493 //------------------------------------------------------------------------------
495 //------------------------------------------------------------------------------
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
502 function calculateSquareSize() {
503 var containerWidth = parseInt(containerEl.css('width'), 10);
505 // defensive, prevent infinite loop
506 if (! containerWidth || containerWidth <= 0) {
511 var boardWidth = containerWidth - 1;
513 while (boardWidth % 8 !== 0 && boardWidth > 0) {
517 return (boardWidth / 8);
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();
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();
540 //------------------------------------------------------------------------------
542 //------------------------------------------------------------------------------
544 function buildBoardContainer() {
545 var html = '<div class="' + CSS.chessboard + '">';
547 if (cfg.sparePieces === true) {
548 html += '<div class="' + CSS.sparePieces + ' ' +
549 CSS.sparePiecesTop + '"></div>';
552 html += '<div class="' + CSS.board + '"></div>';
554 if (cfg.sparePieces === true) {
555 html += '<div class="' + CSS.sparePieces + ' ' +
556 CSS.sparePiecesBottom + '"></div>';
565 var buildSquare = function(color, size, id) {
566 var html = '<div class="' + CSS.square + ' ' + CSSColor[color] + '" ' +
567 'style="width: ' + size + 'px; height: ' + size + 'px" ' +
570 if (cfg.showNotation === true) {
580 function buildBoard(orientation) {
581 if (orientation !== 'black') {
582 orientation = 'white';
587 // algebraic notation / orientation
588 var alpha = deepCopy(COLUMNS);
590 if (orientation === 'black') {
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;
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 + '">';
607 if (cfg.showNotation === true) {
609 if ((orientation === 'white' && row === 1) ||
610 (orientation === 'black' && row === 8)) {
611 html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' +
617 html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' +
622 html += '</div>'; // end .square
624 squareColor = (squareColor === 'white' ? 'black' : 'white');
626 html += '<div class="' + CSS.clearfix + '"></div></div>';
628 squareColor = (squareColor === 'white' ? 'black' : 'white');
630 if (orientation === 'white') {
641 function buildPieceImgSrc(piece) {
642 if (typeof cfg.pieceTheme === 'function') {
643 return cfg.pieceTheme(piece);
646 if (typeof cfg.pieceTheme === 'string') {
647 return cfg.pieceTheme.replace(/{piece}/g, piece);
650 // NOTE: this should never happen
651 error(8272, 'Unable to build image source for cfg.pieceTheme.');
655 function buildPiece(piece, hidden, id) {
656 var html = '<img src="' + buildPieceImgSrc(piece) + '" ';
657 if (id && typeof id === 'string') {
658 html += 'id="' + id + '" ';
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;';
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'];
680 for (var i = 0; i < pieces.length; i++) {
681 html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]);
687 //------------------------------------------------------------------------------
689 //------------------------------------------------------------------------------
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();
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({
705 position: 'absolute',
706 top: srcSquarePosition.top,
707 left: srcSquarePosition.left
710 // remove original piece from source square
711 srcSquareEl.find('.' + CSS.piece).remove();
714 var complete = function() {
715 // add the "real" piece to the destination square
716 destSquareEl.append(buildPiece(piece));
718 // remove the animated piece
719 animatedPieceEl.remove();
721 // run complete function
722 if (typeof completeFn === 'function') {
727 // animate the piece to the destination square
729 duration: cfg.moveSpeed,
732 animatedPieceEl.animate(destSquarePosition, opts);
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();
740 // create the animate piece
741 var pieceId = createId();
742 $('body').append(buildPiece(piece, true, pieceId));
743 var animatedPieceEl = $('#' + pieceId);
744 animatedPieceEl.css({
746 position: 'absolute',
747 left: srcOffset.left,
752 var complete = function() {
753 // add the "real" piece to the destination square
754 destSquareEl.find('.' + CSS.piece).remove();
755 destSquareEl.append(buildPiece(piece));
757 // remove the animated piece
758 animatedPieceEl.remove();
760 // run complete function
761 if (typeof completeFn === 'function') {
766 // animate the piece to the destination square
768 duration: cfg.moveSpeed,
771 animatedPieceEl.animate(destOffset, opts);
774 // execute an array of animations
775 function doAnimations(a, oldPos, newPos) {
776 ANIMATION_HAPPENING = true;
779 function onFinish() {
782 // exit if all the animations aren't finished
783 if (numFinished !== a.length) return;
785 drawPositionInstant();
786 ANIMATION_HAPPENING = false;
788 // run their onMoveEnd function
789 if (cfg.hasOwnProperty('onMoveEnd') === true &&
790 typeof cfg.onMoveEnd === 'function') {
791 cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos));
795 for (var i = 0; i < a.length; i++) {
797 if (a[i].type === 'clear') {
798 $('#' + SQUARE_ELS_IDS[a[i].square] + ' .' + CSS.piece)
799 .fadeOut(cfg.trashSpeed, onFinish);
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);
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);
816 if (a[i].type === 'move') {
817 animateSquareToSquare(a[i].source, a[i].destination, a[i].piece,
823 // returns the distance between two squares
824 function squareDistance(s1, s2) {
826 var s1x = COLUMNS.indexOf(s1[0]) + 1;
827 var s1y = parseInt(s1[1], 10);
830 var s2x = COLUMNS.indexOf(s2[0]) + 1;
831 var s2y = parseInt(s2[1], 10);
833 var xDelta = Math.abs(s1x - s2x);
834 var yDelta = Math.abs(s1y - s2y);
836 if (xDelta >= yDelta) return xDelta;
840 // returns an array of closest squares from square
841 function createRadius(square) {
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);
849 // skip the square we're starting from
850 if (square === s) continue;
854 distance: squareDistance(square, s)
860 squares.sort(function(a, b) {
861 return a.distance - b.distance;
864 // just return the square code
866 for (var i = 0; i < squares.length; i++) {
867 squares2.push(squares[i].square);
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);
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];
883 if (position.hasOwnProperty(s) === true && position[s] === piece) {
891 // calculate an array of animations that need to happen in order to get
893 function calculateAnimations(pos1, pos2) {
894 // make copies of both
895 pos1 = deepCopy(pos1);
896 pos2 = deepCopy(pos2);
899 var squaresMovedTo = {};
901 // remove pieces that are the same in both positions
902 for (var i in pos2) {
903 if (pos2.hasOwnProperty(i) !== true) continue;
905 if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) {
911 // find all the "move" animations
912 for (var i in pos2) {
913 if (pos2.hasOwnProperty(i) !== true) continue;
915 var closestPiece = findClosestPiece(pos1, pos2[i], i);
916 if (closestPiece !== false) {
919 source: closestPiece,
924 delete pos1[closestPiece];
926 squaresMovedTo[i] = true;
930 // add pieces to pos2
931 for (var i in pos2) {
932 if (pos2.hasOwnProperty(i) !== true) continue;
943 // clear pieces from pos1
944 for (var i in pos1) {
945 if (pos1.hasOwnProperty(i) !== true) continue;
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;
963 //------------------------------------------------------------------------------
965 //------------------------------------------------------------------------------
967 function drawPositionInstant() {
969 boardEl.find('.' + CSS.piece).remove();
972 for (var i in CURRENT_POSITION) {
973 if (CURRENT_POSITION.hasOwnProperty(i) !== true) continue;
975 $('#' + SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i]));
979 function drawBoard() {
980 boardEl.html(buildBoard(CURRENT_ORIENTATION));
981 drawPositionInstant();
983 if (cfg.sparePieces === true) {
984 if (CURRENT_ORIENTATION === 'white') {
985 sparePiecesTopEl.html(buildSparePieces('black'));
986 sparePiecesBottomEl.html(buildSparePieces('white'));
989 sparePiecesTopEl.html(buildSparePieces('white'));
990 sparePiecesBottomEl.html(buildSparePieces('black'));
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);
1000 for (var i in moves) {
1001 if (moves.hasOwnProperty(i) !== true) continue;
1003 // skip the move if the position doesn't have a piece on the source square
1004 if (position.hasOwnProperty(i) !== true) continue;
1006 var piece = position[i];
1008 position[moves[i]] = piece;
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);
1020 // do nothing if no change in position
1021 if (oldFen === newFen) return;
1023 // run their onChange function
1024 if (cfg.hasOwnProperty('onChange') === true &&
1025 typeof cfg.onChange === 'function') {
1026 cfg.onChange(oldPos, newPos);
1030 CURRENT_POSITION = position;
1033 function isXYOnSquare(x, y) {
1034 for (var i in SQUARE_ELS_OFFSETS) {
1035 if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue;
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) {
1047 // records the XY coords of every square into memory
1048 function captureSquareOffsets() {
1049 SQUARE_ELS_OFFSETS = {};
1051 for (var i in SQUARE_ELS_IDS) {
1052 if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue;
1054 SQUARE_ELS_OFFSETS[i] = $('#' + SQUARE_ELS_IDS[i]).offset();
1058 function removeSquareHighlights() {
1059 boardEl.find('.' + CSS.square)
1060 .removeClass(CSS.highlight1 + ' ' + CSS.highlight2);
1063 function snapbackDraggedPiece() {
1064 // there is no "snapback" for spare pieces
1065 if (DRAGGED_PIECE_SOURCE === 'spare') {
1066 trashDraggedPiece();
1070 removeSquareHighlights();
1072 // animation complete
1073 function complete() {
1074 drawPositionInstant();
1075 draggedPieceEl.css('display', 'none');
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);
1085 // get source square position
1086 var sourceSquarePosition =
1087 $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]).offset();
1089 // animate the piece to the target square
1091 duration: cfg.snapbackSpeed,
1094 draggedPieceEl.animate(sourceSquarePosition, opts);
1097 DRAGGING_A_PIECE = false;
1100 function trashDraggedPiece() {
1101 removeSquareHighlights();
1103 // remove the source piece
1104 var newPosition = deepCopy(CURRENT_POSITION);
1105 delete newPosition[DRAGGED_PIECE_SOURCE];
1106 setCurrentPosition(newPosition);
1108 // redraw the position
1109 drawPositionInstant();
1111 // hide the dragged piece
1112 draggedPieceEl.fadeOut(cfg.trashSpeed);
1115 DRAGGING_A_PIECE = false;
1118 function dropDraggedPieceOnSquare(square) {
1119 removeSquareHighlights();
1122 var newPosition = deepCopy(CURRENT_POSITION);
1123 delete newPosition[DRAGGED_PIECE_SOURCE];
1124 newPosition[square] = DRAGGED_PIECE;
1125 setCurrentPosition(newPosition);
1127 // get target square information
1128 var targetSquarePosition = $('#' + SQUARE_ELS_IDS[square]).offset();
1130 // animation complete
1131 var complete = function() {
1132 drawPositionInstant();
1133 draggedPieceEl.css('display', 'none');
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);
1142 // snap the piece to the target square
1144 duration: cfg.snapSpeed,
1147 draggedPieceEl.animate(targetSquarePosition, opts);
1150 DRAGGING_A_PIECE = false;
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) {
1163 DRAGGING_A_PIECE = true;
1164 DRAGGED_PIECE = piece;
1165 DRAGGED_PIECE_SOURCE = source;
1167 // if the piece came from spare pieces, location is offboard
1168 if (source === 'spare') {
1169 DRAGGED_PIECE_LOCATION = 'offboard';
1172 DRAGGED_PIECE_LOCATION = source;
1175 // capture the x, y coords of all squares in memory
1176 captureSquareOffsets();
1178 // create the dragged piece
1179 draggedPieceEl.attr('src', buildPieceImgSrc(piece))
1182 position: 'absolute',
1183 left: x - (SQUARE_SIZE / 2),
1184 top: y - (SQUARE_SIZE / 2)
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');
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)
1202 var location = isXYOnSquare(x, y);
1204 // do nothing if the location has not changed
1205 if (location === DRAGGED_PIECE_LOCATION) return;
1207 // remove highlight from previous square
1208 if (validSquare(DRAGGED_PIECE_LOCATION) === true) {
1209 $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION])
1210 .removeClass(CSS.highlight2);
1213 // add highlight to new square
1214 if (validSquare(location) === true) {
1215 $('#' + SQUARE_ELS_IDS[location]).addClass(CSS.highlight2);
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);
1226 DRAGGED_PIECE_LOCATION = location;
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';
1235 if (location === 'offboard' && cfg.dropOffBoard === 'trash') {
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);
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
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;
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];
1260 // source piece was on the board and position is on the board
1261 if (validSquare(DRAGGED_PIECE_SOURCE) === true &&
1262 validSquare(location) === true) {
1264 delete newPosition[DRAGGED_PIECE_SOURCE];
1265 newPosition[location] = DRAGGED_PIECE;
1268 var oldPosition = deepCopy(CURRENT_POSITION);
1270 var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE,
1271 newPosition, oldPosition, CURRENT_ORIENTATION);
1272 if (result === 'snapback' || result === 'trash') {
1278 if (action === 'snapback') {
1279 snapbackDraggedPiece();
1281 else if (action === 'trash') {
1282 trashDraggedPiece();
1284 else if (action === 'drop') {
1285 dropDraggedPieceOnSquare(location);
1289 //------------------------------------------------------------------------------
1291 //------------------------------------------------------------------------------
1294 widget.clear = function(useAnimation) {
1295 widget.position({}, useAnimation);
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);
1309 // remove the widget from the page
1310 widget.destroy = function() {
1312 containerEl.html('');
1313 draggedPieceEl.remove();
1315 // remove event handlers
1316 containerEl.unbind();
1319 // shorthand method to get the current FEN
1320 widget.fen = function() {
1321 return widget.position('fen');
1325 widget.flip = function() {
1326 widget.orientation('flip');
1330 // TODO: write this, GitHub Issue #5
1331 widget.highlight = function() {
1337 widget.move = function() {
1338 // no need to throw an error here; just do nothing
1339 if (arguments.length === 0) return;
1341 var useAnimation = true;
1343 // collect the moves into an object
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;
1352 // skip invalid arguments
1353 if (validMove(arguments[i]) !== true) {
1354 error(2826, 'Invalid move passed to the move method.', arguments[i]);
1358 var tmp = arguments[i].split('-');
1359 moves[tmp[0]] = tmp[1];
1362 // calculate position from moves
1363 var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves);
1366 widget.position(newPos, useAnimation);
1368 // return the new position object
1372 widget.orientation = function(arg) {
1373 // no arguments, return the current orientation
1374 if (arguments.length === 0) {
1375 return CURRENT_ORIENTATION;
1378 // set to white or black
1379 if (arg === 'white' || arg === 'black') {
1380 CURRENT_ORIENTATION = arg;
1386 if (arg === 'flip') {
1387 CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white';
1392 error(5482, 'Invalid value passed to the orientation method.', arg);
1395 widget.position = function(position, useAnimation) {
1396 // no arguments, return the current position
1397 if (arguments.length === 0) {
1398 return deepCopy(CURRENT_POSITION);
1401 // get position as FEN
1402 if (typeof position === 'string' && position.toLowerCase() === 'fen') {
1403 return objToFen(CURRENT_POSITION);
1406 // default for useAnimations is true
1407 if (useAnimation !== false) {
1408 useAnimation = true;
1412 if (typeof position === 'string' && position.toLowerCase() === 'start') {
1413 position = deepCopy(START_POSITION);
1416 // convert FEN to position object
1417 if (validFen(position) === true) {
1418 position = fenToObj(position);
1421 // validate position object
1422 if (validPositionObject(position) !== true) {
1423 error(6482, 'Invalid value passed to the position method.', position);
1427 if (useAnimation === true) {
1428 // start the animations
1429 doAnimations(calculateAnimations(CURRENT_POSITION, position),
1430 CURRENT_POSITION, position);
1432 // set the new position
1433 setCurrentPosition(position);
1437 setCurrentPosition(position);
1438 drawPositionInstant();
1442 widget.resize = function() {
1443 // calulate the new square size
1444 SQUARE_SIZE = calculateSquareSize();
1447 boardEl.css('width', (SQUARE_SIZE * 8) + 'px');
1449 // set drag piece size
1450 draggedPieceEl.css({
1451 height: SQUARE_SIZE,
1456 if (cfg.sparePieces === true) {
1457 containerEl.find('.' + CSS.sparePieces)
1458 .css('paddingLeft', (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px');
1465 // set the starting position
1466 widget.start = function(useAnimation) {
1467 widget.position('start', useAnimation);
1470 //------------------------------------------------------------------------------
1472 //------------------------------------------------------------------------------
1474 function isTouchDevice() {
1475 return ('ontouchstart' in document.documentElement);
1478 // reference: http://www.quirksmode.org/js/detect.html
1480 return (navigator && navigator.userAgent &&
1481 navigator.userAgent.search(/MSIE/) !== -1);
1484 function stopDefault(e) {
1488 function mousedownSquare(e) {
1489 // do nothing if we're not draggable
1490 if (cfg.draggable !== true) return;
1492 var square = $(this).attr('data-square');
1494 // no piece on this square
1495 if (validSquare(square) !== true ||
1496 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1500 beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY);
1503 function touchstartSquare(e) {
1504 // do nothing if we're not draggable
1505 if (cfg.draggable !== true) return;
1507 var square = $(this).attr('data-square');
1509 // no piece on this square
1510 if (validSquare(square) !== true ||
1511 CURRENT_POSITION.hasOwnProperty(square) !== true) {
1515 e = e.originalEvent;
1516 beginDraggingPiece(square, CURRENT_POSITION[square],
1517 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1520 function mousedownSparePiece(e) {
1521 // do nothing if sparePieces is not enabled
1522 if (cfg.sparePieces !== true) return;
1524 var piece = $(this).attr('data-piece');
1526 beginDraggingPiece('spare', piece, e.pageX, e.pageY);
1529 function touchstartSparePiece(e) {
1530 // do nothing if sparePieces is not enabled
1531 if (cfg.sparePieces !== true) return;
1533 var piece = $(this).attr('data-piece');
1535 e = e.originalEvent;
1536 beginDraggingPiece('spare', piece,
1537 e.changedTouches[0].pageX, e.changedTouches[0].pageY);
1540 function mousemoveWindow(e) {
1541 // do nothing if we are not dragging a piece
1542 if (DRAGGING_A_PIECE !== true) return;
1544 updateDraggedPiece(e.pageX, e.pageY);
1547 function touchmoveWindow(e) {
1548 // do nothing if we are not dragging a piece
1549 if (DRAGGING_A_PIECE !== true) return;
1551 // prevent screen from scrolling
1554 updateDraggedPiece(e.originalEvent.changedTouches[0].pageX,
1555 e.originalEvent.changedTouches[0].pageY);
1558 function mouseupWindow(e) {
1559 // do nothing if we are not dragging a piece
1560 if (DRAGGING_A_PIECE !== true) return;
1563 var location = isXYOnSquare(e.pageX, e.pageY);
1565 stopDraggedPiece(location);
1568 function touchendWindow(e) {
1569 // do nothing if we are not dragging a piece
1570 if (DRAGGING_A_PIECE !== true) return;
1573 var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX,
1574 e.originalEvent.changedTouches[0].pageY);
1576 stopDraggedPiece(location);
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;
1584 if (cfg.hasOwnProperty('onMouseoverSquare') !== true ||
1585 typeof cfg.onMouseoverSquare !== 'function') return;
1588 var square = $(e.currentTarget).attr('data-square');
1590 // NOTE: this should never happen; defensive
1591 if (validSquare(square) !== true) return;
1593 // get the piece on this square
1595 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1596 piece = CURRENT_POSITION[square];
1599 // execute their function
1600 cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION),
1601 CURRENT_ORIENTATION);
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;
1609 if (cfg.hasOwnProperty('onMouseoutSquare') !== true ||
1610 typeof cfg.onMouseoutSquare !== 'function') return;
1613 var square = $(e.currentTarget).attr('data-square');
1615 // NOTE: this should never happen; defensive
1616 if (validSquare(square) !== true) return;
1618 // get the piece on this square
1620 if (CURRENT_POSITION.hasOwnProperty(square) === true) {
1621 piece = CURRENT_POSITION[square];
1624 // execute their function
1625 cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION),
1626 CURRENT_ORIENTATION);
1629 //------------------------------------------------------------------------------
1631 //------------------------------------------------------------------------------
1633 function addEvents() {
1634 // prevent browser "image drag"
1635 $('body').on('mousedown mousemove', '.' + CSS.piece, stopDefault);
1637 // mouse drag pieces
1638 boardEl.on('mousedown', '.' + CSS.square, mousedownSquare);
1639 containerEl.on('mousedown', '.' + CSS.sparePieces + ' .' + CSS.piece,
1640 mousedownSparePiece);
1642 // mouse enter / leave square
1643 boardEl.on('mouseenter', '.' + CSS.square, mouseenterSquare);
1644 boardEl.on('mouseleave', '.' + CSS.square, mouseleaveSquare);
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; };
1652 $('body').on('mousemove', mousemoveWindow);
1653 $('body').on('mouseup', mouseupWindow);
1656 $(window).on('mousemove', mousemoveWindow);
1657 $(window).on('mouseup', mouseupWindow);
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);
1670 function initDom() {
1671 // build board and save it in memory
1672 containerEl.html(buildBoardContainer());
1673 boardEl = containerEl.find('.' + CSS.board);
1675 if (cfg.sparePieces === true) {
1676 sparePiecesTopEl = containerEl.find('.' + CSS.sparePiecesTop);
1677 sparePiecesBottomEl = containerEl.find('.' + CSS.sparePiecesBottom);
1680 // create the drag piece
1681 var draggedPieceId = createId();
1682 $('body').append(buildPiece('wP', true, draggedPieceId));
1683 draggedPieceEl = $('#' + draggedPieceId);
1685 // get the border size
1686 BOARD_BORDER_SIZE = parseInt(boardEl.css('borderLeftWidth'), 10);
1688 // set the size and draw the board
1693 if (checkDeps() !== true ||
1694 expandConfig() !== true) return;
1696 // create unique IDs for all the elements we will create
1706 // return the widget object
1709 }; // end window.ChessBoard
1711 // expose util functions
1712 window.ChessBoard.fenToObj = fenToObj;
1713 window.ChessBoard.objToFen = objToFen;
1715 })(); // end anonymous wrapper