var lLevelId = 1; //by default level id is 1
var lGameMode = "Arcade"; //by default game mode is arcade
var lPuzzleId = 0; //puzzle id
var lsoccerPlacementString = "nil"
var soccerPlacement = new Array();
var occupied = new Array();
var occupiedObjectName = new Array();
var undoMain = new Array();
var undo =  new Array ();
var lIsUndoDone = false; //this variable will help in challenge mode, because we can undo the game only once in challenge mode

var soccerBallA = new Array();
var soccerBallBoxA = new Array();
var lBeginX=0; var lBeginY = 0; var lGridSize = 42;
var lStepX = 0; var lStepY = 0;
var lIndexBoxA = 0; var lPreviousBoxA = 0;
var lTimer1 ;
var lIsSelected = false; var lIsMoving = false;
var lSelectedObject;
var lPresentX = 0; var lPresentY =0;
var lNextX = 0; var lNextY = 0;
var lXDirection=0; var lYDirection=0;
var lNextPlaceToMove = 0;
var lSoccerBallSpeedPerGrid = 5;
var lIsHitted = false;
var lTotalObjects = 0;
var lRows = 8; var lColumns = 7;
var lGameFinished = false;
var lUndoIndex = 0
var lUndoIndex2 = 0
var lIsAudioPlayed = false;
var highlightTarget;
var timerText
var lTTextX, TTextY
var lTimerText1=  null;
var lTimerText2= null; 
var timerText1; //timer text: timer clock
var lClockTimer=null;;
var lBeginTimer = 90;
var lPuzzleArray = new Array();
var hurryUp 
var bg, game_upper_bar, level_hud, timer_hud, puzzle_hud, game_hud_timer, game_hud_level1, game_hud_level2, game_lower_bar, pauseBtn, pauseBtnHover, undoBtn, undoBtnHover, gameGrid

function beginTimerClock() {
	if(lGameMode=="Arcade") return true;
	lClockTimer = setInterval(function() {
		lBeginTimer--;
		if(timerText != undefined) {
			// timerText.text(lBeginTimer)
		}
		// console.log("timer is started ", lBeginTimer)
		createNumber(lBeginTimer, lTTextX, lTTextY)
        setTimerText(true);
        if(lBeginTimer==9){
            console.log('showing the zero');
    //           timerText.x = timer_hud._x+44; timerText.y = timer_hud._y+22 ;
    //          var timerText1 = Crafty.e("2D, Canvas, Text").textFont({ size:'28px', type: 'normal', family: 'Arial Black' });
    //         timerText1.text(0); timerText1.textColor('#ffffff'); timerText1.alpha = 0.5;
		 	// timerText1.x = timer_hud._x+25; timerText1.y = timer_hud._y+22 ;
                console.log('activate the zero');
           }
        else if(lBeginTimer==10){
              console.log('only 10 seconds left');
             // createAlertScreen();
             hurryUp = Crafty.e("2D, Canvas, Image").image('images/hurryup.png');
    		 hurryUp.x = bg._x+80; hurryUp.y = bg._y+210;

    		 setTimeout(function(){
			     hurryUp.destroy();
			        
			    },1500);
        }
        
        else if(lBeginTimer<0) {
			// timerText.text(00);
   //           timerText.x = timer_hud._x+32; timerText.y = timer_hud._y+28 ;

			clearInterval(lClockTimer);
			lClockTimer=null
			//change the scene now
			Crafty.scene('PuzzleLose')
		}

	}, 1000)
}

function pauseTimerClock() {
	if(lGameMode=="Arcade") return true;
	if(lClockTimer !=null)
	clearInterval(lClockTimer);
}

function endTimerClock() {
	if(lGameMode=="Arcade") return true;
	if(lClockTimer !=null)
	clearInterval(lClockTimer);
	console.log("end timer clock *******************")
	lClockTimer=null;
	lBeginTimer=90;
}

var randomCount = 0

function resetPuzzleId() {
	if(lGameMode=="Arcade") return true;
	// for (var i=0; i< lPuzzleArray.length; i++) {
		// lPuzzleArray.pop();
	// }
	// lPuzzleArray.length = 0;
	// lPuzzleArray= new Array();
	// randomCount=0;
	lPuzzleId=0;
	endTimerClock()
	lBeginTimer=90; lIsUndoDone=false;
	// if(timerText!=undefined)
	// timerText.text(lBeginTimer);

	// createNumber(lBeginTimer, lTTextX, lTTextY)
	setTimeout(function(e) {  beginTimerClock(); }, 300)
}

// function isUnqiueNumber(bLevelId) {
// 	var bResult = true;
// 	for(var i=0; i< lPuzzleArray.length; i++) {
// 		if(bLevelId== lPuzzleArray[i]) {
// 			bResult = false;
// 			break;
// 		}
// 	} 
// 	console.log("is unique number ", bLevelId, lPuzzleArray.length)
// 	return bResult
// }

function generateRandomPuzzleUniqueId() {
	//generate random puzzle unique id and save in puzzle array
	// var bPuzzleId = Crafty.math.randomInt(1, 5)
	// console.log("generate random puzzle unique id is ", bPuzzleId)
	// randomCount++;
	//now check whether the no. is existed or not in lpuzzlearray
	// if(isUnqiueNumber(bPuzzleId)) {
		// lPuzzleId = bPuzzleId
		// lPuzzleArray.push(bPuzzleId)
		// console.log("generated unique id is now ", bPuzzleId)
	// } else {  generateRandomPuzzleUniqueId();  }
	lPuzzleId++;
	// setStorageItem(lGameMode+lLevelId, lPuzzleId)
}

function setGameLevelId(pLevelId) {
	if(pLevelId) {
		
		lLevelId = pLevelId;	
		console.log("set game level id ", lLevelId);
	}
}

function setGameMode(pGameMode){
	if(pGameMode) {
		lGameMode = pGameMode;
		console.log("set game mode ", lGameMode);
		if(pGameMode == "Challenge") {
			// resetPuzzleId();
		}
	}
}

function getGameMode() {
	return lGameMode;
}

function getLevelId() {
	return lLevelId
}

function setPuzzleId(pPuzzleId) {
	if(pPuzzleId) {
		lPuzzleId = pPuzzleId;
		console.log("set puzzle id ", lPuzzleId);
	}
}

function setPuzzleId1() {
	if(lGameMode == "Arcade") {
		lPuzzleId++;
		
		if(lPuzzleId > 5) {
			lPuzzleId=1; lLevelId++;
			
			//if lLevel id == 100 can't increment
		}
	}else if(lGameMode == "Challenge") {
		//generate random unique puzzle id's

		generateRandomPuzzleUniqueId();
	}
}

function setSoccerPlacementString(pString, pBg) {
	if(pString) {
		soccerPlacement = pString.split(',');
		// alert(pString);
		lsoccerPlacementString = pString;
		// setTimeout(function () {
			placeSoccers();
		// }, 1000) 
	}
}

function initGame() {
	console.log("game initialized ");
}

function resetGame() {
	console.log("reset the game ************************")
	console.log("1occupied ", occupied)
	lStepX = lBeginX; lStepY = lBeginY;
	soccerPlacement.length = 0; lIsUndoDone=false;
	occupied.length = 0; occupiedObjectName.length = 0;
	for (var i=0; i<= undoMain.length; i++) {
		undoMain.pop();
	}
	undoMain.length = 0;
	lUndoIndex=0;
	console.log("undo length ", undoMain.length)
	soccerBallA.length=0; soccerBallBoxA.length=0;
	lTotalObjects = 0; lGameFinished=false;
	// readTextFile("levels/"+lGameMode+"/Level"+lLevelId+"/"+lPuzzleId+".txt");
	console.log("level id and puzzle id is ", lLevelId, lPuzzleId)
	readTextFile("levels/Level"+lLevelId+"/"+lPuzzleId+".txt");
}

function resetPuzzle() {
	deleteImages(soccerBallA)
	lStepX = lBeginX; lStepY = lBeginY;
	soccerPlacement.length = 0; 
	occupied.length = 0; occupiedObjectName.length = 0;
	for (var i=0; i<= undoMain.length; i++) {
		undoMain.pop();
	}
	undoMain.length = 0;
	lUndoIndex=0;
	console.log("undo length ", undoMain.length)
	soccerBallA.length=0; soccerBallBoxA.length=0;
	lTotalObjects = 0; lGameFinished=false;
	// readTextFile("levels/"+lGameMode+"/Level"+lLevelId+"/"+lPuzzleId+".txt");
	console.log("reset the puzzle ",lPuzzleId)
	readTextFile("levels/Level"+lLevelId+"/"+lPuzzleId+".txt");	
}

function deleteGameImages() {
	// deleteImages(soccerBallA)
	// deleteImages([bg, game_upper_bar, level_hud, timer_hud, puzzle_hud, game_hud_timer, game_hud_level1, game_hud_level2, game_lower_bar, pauseBtn, undoBtn, gameGrid]);
}

function checkTotalSoccerBalls() {
	console.log("check total soccer balls function called")
	
	if(lTotalObjects <= 1) {
		console.log("=======you won the game or game is finished, load the level won screen with puzzle id ", lLevelId)
		lGameFinished=true;
		if(lGameMode == "Arcade") {
			if(lPuzzleId == 5) {
				
				if(lLevelId>=10) {
					
					setTimeout(function() {
					     deleteGameImages()
					     Crafty.scene('LevelsComplete')
					 }, 500);
					setStorageItem(lGameMode+10, 1)	
				} 
				else {
					setStorageItem(lGameMode+(lLevelId+1), 1)
					setTimeout(function() {
					     deleteGameImages()
					     Crafty.scene('LevelWin')
					 }, 500);
					
				}

					
			}
			else {
				setStorageItem(lGameMode+lLevelId, lPuzzleId+1)
				
				setTimeout(function() {
					     deleteGameImages()
					     Crafty.scene('PuzzleWin')
					 }, 500);
			}
		}
		else {
			console.log("================================")
			
			console.log("================================")
			if(lPuzzleId == 5) {
				// resetPuzzleId();
				
				endTimerClock();
				if(lLevelId>=10){ 
					setTimeout(function() {
					     deleteGameImages()
					     Crafty.scene('LevelsComplete'); 
					 }, 500); 
				}
				else {
					 setTimeout(function() {
					     deleteGameImages()
					     Crafty.scene('LevelWin');
					 }, 500);
					
				}
				lLevelId++;
				setStorageItem(lGameMode+lLevelId, 1)
			}
			else {
				pauseTimerClock()
				setTimeout(function() {
					     deleteGameImages()
					     Crafty.scene('PuzzleWin')
				}, 500);
				
			}
			
		}
		
		
	}

	// Crafty.scene('PuzzleWin')
}

function debugPrintOccupiedPlaces() {
	// for (var i=0; i< occupied.length && i!=56 ; i++ ){
		console.log(" occupied index, value ", occupied);
	// }
}


function checkObjectInDirection(pDirection, pIndex){
	var bResult = false;
	if(pDirection == "east") {

		var bCount = 7-pIndex%7

		console.log("east direction index of present object ", pIndex, bCount)
		for(var i=pIndex+1; i<=pIndex+bCount; i++) {
			console.log(" object index, index, count ", pIndex, i, bCount);
			if(occupied[i-1] > 0){
				bResult = true;
				lNextPlaceToMove = i-1;
				console.log("check object in direction ", i, occupied[i-1])
				break;
			}
		}

		if(bResult == false) {
			lNextPlaceToMove = bCount;
		}
		return bResult;
	
	}
	else if(pDirection == "west") {
		var bCount = pIndex%7
		console.log("west direction b Count ", bCount)
		if(bCount==0) { bCount=7;}
		console.log("west direction, index, count ", pIndex, bCount, pIndex-1, pIndex-bCount+1);
		for(var i=pIndex-1; i>= pIndex - bCount+1; i--) {
			console.log("west direction occupied index, value ", i-1, occupied[i-1]);
			if(occupied[i-1] > 0){
				bResult = true;
				lNextPlaceToMove = i+1;
				console.log("object is in west direction ", i, occupied[i-1], lNextPlaceToMove)
				break;
			}
		} 
		console.log(" occupied ", occupied)
		if(bResult == false) { lNextPlaceToMove = bCount; }

		return bResult;
	
	}
	else if(pDirection == "north") {
			var bCount = pIndex/7
			console.log("north direction, index, count ", pIndex, bCount, floatToInt(bCount))
			for(var i=1; i <= bCount; i++) {
				console.log("north direction, index, value ", i, pIndex-1-i*7, occupied[pIndex-1-i*7] )
				if(occupied[pIndex-1-i*7] > 0) {
					bResult = true;
					lNextPlaceToMove = pIndex-(i-1)*7;
					console.log("object in north direction ", pIndex-1-i*7, occupied[pIndex-1-i*7], lNextPlaceToMove)
					break;
				}
			}
			if(bResult==false) { lNextPlaceToMove = bCount; }
		return bResult;
	}
	else if(pDirection == "south") {
		var bCount = lRows-(floatToInt(pIndex/7)) //-1
		console.log("south direction, index, count ", pIndex, bCount);
		for(var i=1; i<= bCount; i++) {
			console.log("object occupiedid, occupied value",pIndex-1+i*7, occupied[pIndex-1+i*7] )
			if(occupied[pIndex-1+i*7] > 0) {
				bResult = true;
				lNextPlaceToMove = pIndex+(i-1)*7;
				console.log("object in south direction ", pIndex-1+i*7,occupied[pIndex-1+i*7],lNextPlaceToMove)
				break;
			}
		}
		if(bResult==false) { lNextPlaceToMove = bCount; }
		return bResult;
	}
}

function setTargetObject(pOccupiedId) {
	// soccerBallA
	for(var i=0; i< soccerBallA.length; i++) {
		console.log("index, occupied id, nextoccupied id", i, soccerBallA[i].occupiedId, pOccupiedId, soccerBallA[i].isDeleted )
		if(soccerBallA[i].occupiedId == pOccupiedId ) {
			if(soccerBallA[i].isDeleted) {
				if(lLevelId==9 && lPuzzleId==4) {
					for(j=0;j< soccerBallA.length; j++) {
						if(soccerBallA[j].imageName==7) {
							lSelectedObject = soccerBallA[j]
						}
					}
				}
			}
			else {
				lSelectedObject = soccerBallA[i];
			}
			
			console.log(" set target object function with image name  ", lSelectedObject.occupiedId, lSelectedObject.puzzleId, lSelectedObject.imageName, soccerBallA[i].isDeleted )
			break;
		}
	}
}

function pushDataToUndoStack(pUndo) {
	lIsAudioPlayed=false;
	console.log("data pushed to undo stack ", pUndo)
	if(pUndo.length ==0 ) { return true }
	undoMain.push(pUndo)
	// undoMain.push(undo);	
	// lUndoIndex++;
	// lUndoIndex2=0;
	console.log("undo data is ", pUndo)
	console.log("push data to undo main stack length", undoMain.length, pUndo.length)
	console.log("undo main data ", undoMain)
	// for (var i=0; i<= undo.length; i++) {
	// 	undo.pop();
	// }
	// undo.length=0;
	pUndo = new Array();
	undo = new Array();
	console.log("undo length is ", pUndo.length)
	console.log("undo main data is ", undoMain, undoMain[0][0].length)
	// for ( var i=0; i< undoMain.length; i++) {
		// console.log(" undo main value of index i is ", i, undoMain[i]);
	// }
}

function undoTheStack() {
	if(lGameMode=="Challenge" && lIsUndoDone)return ;  
	if(lGameFinished) return ;      //in challenge mode only once the player can undo the game.
	if(undoMain.length ==0) { console.log("can't undo "); return true;}
	var undoData = undoMain.pop()
	lIsUndoDone = true;
	console.log("***************** values are ", undoData.length, undoData[0], undoData)
	for (var i=0; i< undoData.length; i++) {
		//find soccerball in array of soccerBallA
		for(var j=0; j< soccerBallA.length; j++) {
			if(undoData[i][0] == soccerBallA[j].imageName) {
				//set the position
				soccerBallA[j].x = undoData[i][1]; soccerBallA[j].y = undoData[i][2];
				//set object occupied id and puzzle id
				soccerBallA[j].occupiedId = undoData[i][3]
				soccerBallA[j].puzzleId = soccerBallA[j].occupiedId+1;
				//set occupied data as image name
				occupied[undoData[i][3]]= undoData[i][0]
				//set next occupied data as 0
				if(undoData[i][4] != "Deleted") {
					occupied[undoData[i][4]] = 0;	
				}
				
				//check if object deleted or not
				if(soccerBallA[j].isDeleted && soccerBallA[j].visible == false) {
					//increment the data
					lTotalObjects++;
					console.log("increment the objects ", lTotalObjects)
					soccerBallA[j].visible = true;
					soccerBallA[j].isDeleted = false;

				}
			}
		}
	}
	console.log("occupied", occupied)

	for (var i=0; i< undoData.length; i++) {
		undoData.pop();
	}
}

function playFlingPush() {
	if(lIsAudioPlayed) return true;
	lIsAudioPlayed=true;
	playSfxAudio("FlingPush");
}

function tweenTarget(pDirection) {
	if(pDirection == "east") {
		
		if(lSelectedObject.puzzleId%7!=0 && occupied[lSelectedObject.occupiedId+1]==0) {

				lXDirection=1; lYDirection = 0;

				if(checkObjectInDirection("east", lSelectedObject.puzzleId)) {
					console.log("east if block")
					playFlingPush();
					var bNextObjectOccupiedId = lNextPlaceToMove;
					console.log("lnextplace to move, lSelectedObject.puzzleId, next object occupied id ", lNextPlaceToMove, lSelectedObject.puzzleId, bNextObjectOccupiedId)
					lNextPlaceToMove=lNextPlaceToMove-lSelectedObject.puzzleId
					console.log("lnextplace to move, next object occupied id ", lNextPlaceToMove, bNextObjectOccupiedId)
					var bSpeed = lSoccerBallSpeedPerGrid*lNextPlaceToMove
					console.log("present place, next place, ball speed ",lSelectedObject._x, lNextPlaceToMove, bSpeed)
					lNextPlaceToMove = lSelectedObject._x + lNextPlaceToMove*lGridSize
					if(bSpeed==0) { lNextPlaceToMove = lNextPlaceToMove + 10; bSpeed = 10;}
					console.log("undo length ", undo.length)
					undo[undo.length] = new Array(lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, bNextObjectOccupiedId-1, lSelectedObject.puzzleId)
					// undo1.push(lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, bNextObjectOccupiedId-1)
					console.log("undo pushed data 1 ", undo)
					// lUndoIndex2++;
					lIsMoving=true; lIsSelected=true;
					lSelectedObject.tween({x:lNextPlaceToMove}, bSpeed);
					// console.log(" previous puzzleId, occupiedId next puzzleId, occupiedId, occupied value", lSelectedObject.puzzleId, lSelectedObject.occupiedId, bNextObjectOccupiedId, bNextObjectOccupiedId-1, occupied[lSelectedObject.occupiedId])


					occupied[lSelectedObject.occupiedId]=0
					occupied[bNextObjectOccupiedId-1]=lSelectedObject.imageName;

					// occupiedObjectName[lSelectedObject.occupiedId] =0;
					// occupiedObjectName[bNextObjectOccupiedId-1]= lSelectedObject.imageName

					lSelectedObject.puzzleId = bNextObjectOccupiedId;
					lSelectedObject.occupiedId = bNextObjectOccupiedId-1
					lIsMoving=true;
					console.log("next occupied ", occupied[lSelectedObject.occupiedId])

					// moveNextTarget(lSelectedObject, 1, 0);
					setTimeout(function() {
						console.log("tween next target with occupied Id ", bNextObjectOccupiedId)
						lIsHitted= true;
						setTargetObject(bNextObjectOccupiedId);
						tweenTarget("east")
					}, bSpeed*21)
				}
				else {
					console.log("east if-else block ")
					playFlingPush();
					var bSpeed = lSoccerBallSpeedPerGrid*lNextPlaceToMove
					var bPX = lSelectedObject._x; var bPY = lSelectedObject._y
					lNextPlaceToMove = lSelectedObject._x + lNextPlaceToMove*lGridSize
					console.log("present place, nextplace, bSpeed", lSelectedObject._x, lNextPlaceToMove, bSpeed)
					if(bSpeed == 0) { bSpeed = 10; lNextPlaceToMove = lNextPlaceToMove+lGridSize/4;}
					lIsMoving=true; lIsSelected=true;
					lSelectedObject.tween({x:lNextPlaceToMove}, bSpeed)

					setTimeout(function() {
						console.log("set previous position ")
						if(lIsHitted) {
							undo[undo.length] = new Array(lSelectedObject.imageName, bPX, bPY, lSelectedObject.occupiedId, "Deleted", lSelectedObject.puzzleId)
							console.log("undo pushed data 2 ", undo)
							
							occupied[lSelectedObject.occupiedId]=0;
							occupiedObjectName[lSelectedObject.occupiedId]=0;
							lIsHitted = false;
							lIsMoving=false;
							lIsSelected = false;
							// lSelectedObject.destroy();
							lSelectedObject.isDeleted = true; 
							lSelectedObject.visible = false
							lTotalObjects--; 
							
							debugPrintOccupiedPlaces()
							pushDataToUndoStack(undo); //push data to main undo stack array
							checkTotalSoccerBalls()
							//check if total objects ==1 then you won, load next level
							console.log("total objects now ", soccerBallA.length, lTotalObjects)
						}
						else { lIsHitted = false;
							 lSelectedObject.x= bPX; lSelectedObject.y = bPY;	
							pushDataToUndoStack(undo);
							// setTimeout(function() { },)
							 lIsMoving=false;
							lIsSelected = false;
						}
					}, bSpeed*30)
				}
		}
		else if(lIsHitted && (occupied[lSelectedObject.occupiedId+1]==0 || lSelectedObject.puzzleId%7==0)){
				playFlingPush()
				console.log("east else if block 1")
				console.log("undo length ", undo.length, undo)
				undo[undo.length] = new Array (lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, "Deleted", lSelectedObject.puzzleId)
				
				console.log("undo pushed data 3 ", undo, undo.length)
				// lUndoIndex2++;
				lIsMoving=true; lIsSelected=true;
				lSelectedObject.tween({x:lSelectedObject._x+lGridSize/4}, lSoccerBallSpeedPerGrid)
				occupied[lSelectedObject.occupiedId]=0;
				occupiedObjectName[lSelectedObject.occupiedId]=0

				pushDataToUndoStack(undo);
				setTimeout(function() {
					lIsHitted=false; lIsMoving=false; lIsSelected=false;
					lSelectedObject.isDeleted = true; lSelectedObject.visible=false;
					lTotalObjects--; checkTotalSoccerBalls();

				}, lSoccerBallSpeedPerGrid*21)
		}
		else if(lIsHitted && occupied[lSelectedObject.occupiedId+1] > 0) {
				console.log("east else if block 2")
				setTargetObject(lSelectedObject.occupiedId+1);
				tweenTarget("east")
		}
		else { console.log("east final else block")
				lIsHitted=false; lIsMoving=false; lIsSelected=false; pushDataToUndoStack(undo);
		}
	}
	else if(pDirection == "west") {
		
		if(lSelectedObject.puzzleId%7!=1 && occupied[lSelectedObject.occupiedId-1]==0){
			if(checkObjectInDirection("west", lSelectedObject.puzzleId)) {
				playFlingPush()
				console.log("west if block")
				lIsMoving=true;
				var bNextObjectOccupiedId = lNextPlaceToMove;

				lNextPlaceToMove=lSelectedObject.puzzleId-lNextPlaceToMove
				console.log("next place to move", lNextPlaceToMove)
				var bSpeed = lSoccerBallSpeedPerGrid*lNextPlaceToMove
				lNextPlaceToMove = lSelectedObject._x - lNextPlaceToMove*lGridSize
				console.log("present place, next place ",lSelectedObject._x, lNextPlaceToMove)
				undo[undo.length] = [lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, bNextObjectOccupiedId-1]
				lSelectedObject.tween({x:lNextPlaceToMove}, bSpeed);
				lIsMoving=true; lIsSelected=true;
				occupied[lSelectedObject.occupiedId]=0
				occupied[bNextObjectOccupiedId-1]=lSelectedObject.imageName;

				

				lSelectedObject.puzzleId = bNextObjectOccupiedId;
				lSelectedObject.occupiedId = bNextObjectOccupiedId-1
				console.log("lSelectedObject puzzle id occupied id", bNextObjectOccupiedId, bNextObjectOccupiedId-1)

				setTimeout(function() {
						console.log("west direction tween next target with occupied Id  ", bNextObjectOccupiedId)
						lIsHitted= true;
						setTargetObject(bNextObjectOccupiedId-1-1);
						tweenTarget("west")
				}, bSpeed*21)
			}
			else {
				    console.log("west if -else block ")
					var bPX = lSelectedObject._x; var bPY = lSelectedObject._y
					console.log("next place ", lNextPlaceToMove)
					var bSpeed= lSoccerBallSpeedPerGrid*lNextPlaceToMove
					lNextPlaceToMove = lSelectedObject._x - lNextPlaceToMove*lGridSize
					playFlingPush()
					console.log("present place, next place ", lSelectedObject._x, lBeginX-10, bSpeed)
					lSelectedObject.tween({x:lBeginX-12}, bSpeed)
					lIsMoving=true; lIsSelected=true;
					setTimeout(function() {
						console.log("west set previous position ")
						
						if(lIsHitted) {
							undo[undo.length] = [lSelectedObject.imageName, bPX, bPY, lSelectedObject.occupiedId, "Deleted"]
							occupied[lSelectedObject.occupiedId]=0;
							occupiedObjectName[lSelectedObject.occupiedId]=0;
							lIsHitted = false;
							lIsMoving=false;
							lIsSelected = false;
							// lSelectedObject.destroy();
							lSelectedObject.isDeleted = true; 
							lSelectedObject.visible = false
							lTotalObjects--; checkTotalSoccerBalls();
							debugPrintOccupiedPlaces()
							pushDataToUndoStack(undo)
							//check if total objects ==1 then you won, load next level
							console.log("west total objects now ", soccerBallA.length, lTotalObjects)
						}
						else { lIsHitted = false;
							lIsMoving=false;
							lIsSelected = false; lSelectedObject.x= bPX; lSelectedObject.y = bPY; pushDataToUndoStack(undo)	}
					}, bSpeed*21)

			}
		}
		else if(lIsHitted && (occupied[lSelectedObject.occupiedId-1]==0 || lSelectedObject.puzzleId%7==1)) {
			console.log("west else -if block 1")
			undo[undo.length] = [lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, "Deleted"]
			lIsMoving=true; lIsSelected=true;
			lSelectedObject.tween({x:lSelectedObject._x-lGridSize/4}, lSoccerBallSpeedPerGrid)
				occupied[lSelectedObject.occupiedId]=0;
				occupiedObjectName[lSelectedObject.occupiedId]=0;
				playFlingPush()
				pushDataToUndoStack(undo)
				setTimeout(function() {
					lIsHitted=false; lIsMoving=false; lIsSelected=false;
					lSelectedObject.isDeleted = true; lSelectedObject.visible=false;
					lTotalObjects--; checkTotalSoccerBalls();
				}, lSoccerBallSpeedPerGrid*21)
		}
		else if(lIsHitted && occupied[lSelectedObject.occupiedId-1]>0) {
			console.log("west else if block 2")
			setTargetObject(lSelectedObject.occupiedId-1);
			tweenTarget("west")
		}
		else { console.log("west final else block")
				lIsHitted=false; lIsMoving=false; lIsSelected=false; pushDataToUndoStack(undo)
			}
	}
	else if(pDirection == "north") {
		if(lSelectedObject.puzzleId > 7 && occupied[lSelectedObject.occupiedId-7]==0) {
			if(checkObjectInDirection("north", lSelectedObject.puzzleId)) {
				playFlingPush()
				console.log("north if block ")
				var bNextObjectOccupiedId = lNextPlaceToMove-7;
				lNextPlaceToMove=lSelectedObject.puzzleId - lNextPlaceToMove

				console.log("lnextplace to move, next object puzzleId id ", lNextPlaceToMove, bNextObjectOccupiedId)
				lNextPlaceToMove = floatToInt(lNextPlaceToMove/7);
				var bSpeed = lSoccerBallSpeedPerGrid*lNextPlaceToMove
				lNextPlaceToMove = lSelectedObject._y - lNextPlaceToMove*lGridSize
				console.log("next place of object _y, present place, bSpeed ", lNextPlaceToMove, lSelectedObject._y, bSpeed)
				undo[undo.length] = [lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, bNextObjectOccupiedId+7-1]

				lSelectedObject.tween({y:lNextPlaceToMove}, bSpeed);
				// console.log(" previous puzzleId, occupiedId next puzzleId, occupiedId, occupied value", lSelectedObject.puzzleId, lSelectedObject.occupiedId, bNextObjectOccupiedId, bNextObjectOccupiedId-1, occupied[lSelectedObject.occupiedId])
				
				occupied[lSelectedObject.occupiedId]=0
				occupied[bNextObjectOccupiedId+7-1]=lSelectedObject.imageName;

				occupiedObjectName[lSelectedObject.occupiedId]=0
				occupiedObjectName[bNextObjectOccupiedId+7-1] = lSelectedObject.imageName

				lSelectedObject.puzzleId = bNextObjectOccupiedId+7
				lSelectedObject.occupiedId = bNextObjectOccupiedId+7-1

				lIsMoving=true;
				console.log("next occupied ", occupied[lSelectedObject.occupiedId])

				// moveNextTarget(lSelectedObject, 1, 0);
				setTimeout(function() {
					console.log("north tween next target with occupied Id ", bNextObjectOccupiedId-1)
					lIsHitted= true;
					setTargetObject(bNextObjectOccupiedId-1);
					tweenTarget("north")
				}, bSpeed*21)
			}
			else {
				console.log("north if-else block ")
				playFlingPush()
				var bPX = lSelectedObject._x; var bPY = lSelectedObject._y
				lNextPlaceToMove = floatToInt(lNextPlaceToMove)
				var bSpeed = lSoccerBallSpeedPerGrid*lNextPlaceToMove
				lNextPlaceToMove = lSelectedObject._y - lNextPlaceToMove*lGridSize
				console.log("next place to move ", lNextPlaceToMove, " from ",bPY )
				lIsMoving=true; lIsSelected=true;
				lSelectedObject.tween({y:lNextPlaceToMove}, bSpeed)

				setTimeout(function() {
					console.log("north set previous position ")
					if(lIsHitted) {
						undo[undo.length] = [lSelectedObject.imageName, bPX, bPY, lSelectedObject.occupiedId, "Deleted"]
						occupied[lSelectedObject.occupiedId]=0;
						occupiedObjectName[lSelectedObject.occupiedId] = 0;
						lIsHitted = false;
						lIsMoving=false;
						lIsSelected = false;
				// 		// lSelectedObject.destroy();
						lSelectedObject.isDeleted = true; 
						lSelectedObject.visible = false
						lTotalObjects--; checkTotalSoccerBalls();
						pushDataToUndoStack(undo)
						debugPrintOccupiedPlaces()
				// 		//check if total objects ==1 then you won, load next level
						console.log("north total objects now ", soccerBallA.length, lTotalObjects)
					}
					else { lIsHitted = false;
						lIsMoving=false;
						lIsSelected = false; lSelectedObject.x= bPX; lSelectedObject.y = bPY; pushDataToUndoStack(undo)	}
				}, bSpeed*21)

			}
		}
		else if(lIsHitted && (occupied[lSelectedObject.occupiedId-7]==0 || lSelectedObject.occupiedId <7)) {
			console.log("north else if block 1")
			playFlingPush()
			undo[undo.length] = [lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, "Deleted"]
			lIsMoving=true; lIsSelected=true;
			lSelectedObject.tween({y:lSelectedObject._y-lGridSize/4}, 10)
			occupied[lSelectedObject.occupiedId]=0;
			occupiedObjectName[lSelectedObject.occupiedId]=0;
			pushDataToUndoStack(undo)
			setTimeout(function() {
				lIsHitted=false; lIsMoving=false; lIsSelected=false;
				lSelectedObject.isDeleted = true; lSelectedObject.visible=false;
				lTotalObjects--; checkTotalSoccerBalls();
			}, 20*21)

		}
		else if(lIsHitted && occupied[lSelectedObject.occupiedId-7]>0) {
			console.log("north else if block 2")
			setTargetObject(lSelectedObject.occupiedId-7);
			tweenTarget("north")
		}
		else { console.log("north final else block");
			lIsHitted = false; lIsMoving=false; lIsSelected = false; pushDataToUndoStack(undo)
		}
	}
	else if(pDirection == "south") {
		if(lSelectedObject.puzzleId <= occupied.length - 7 && occupied[lSelectedObject.occupiedId+7]==0) {
			if(checkObjectInDirection("south", lSelectedObject.puzzleId)) {
				playFlingPush()
				console.log("south if block ")
				var bNextObjectOccupiedId = lNextPlaceToMove;
				lNextPlaceToMove=lNextPlaceToMove-lSelectedObject.puzzleId 
				lNextPlaceToMove = floatToInt(lNextPlaceToMove/7)
				console.log("lnextplace to move, next object puzzleId id ", lNextPlaceToMove, bNextObjectOccupiedId)
				// lNextPlaceToMove = floatToInt(lNextPlaceToMove/7);
				var bSpeed = lSoccerBallSpeedPerGrid*lNextPlaceToMove
				lNextPlaceToMove = lSelectedObject._y + lNextPlaceToMove*lGridSize
				console.log("next place of object _y, present place, bSpeed ", lNextPlaceToMove, lSelectedObject._y, bSpeed)
				undo[undo.length] = [lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, bNextObjectOccupiedId-1]
				lIsMoving=true; lIsSelected=true;
				lSelectedObject.tween({y:lNextPlaceToMove}, bSpeed);
				// console.log(" previous puzzleId, occupiedId next puzzleId, occupiedId, occupied value", lSelectedObject.puzzleId, lSelectedObject.occupiedId, bNextObjectOccupiedId, bNextObjectOccupiedId-1, occupied[lSelectedObject.occupiedId])
				console.log("present occupiedid, , next occupiedid,  ", lSelectedObject.occupiedId, bNextObjectOccupiedId-1 )
				occupied[lSelectedObject.occupiedId]=0
				occupied[bNextObjectOccupiedId-1]=lSelectedObject.imageName;

			

				lSelectedObject.puzzleId = bNextObjectOccupiedId
				lSelectedObject.occupiedId = bNextObjectOccupiedId-1

				lIsMoving=true;
				console.log("next target object ", bNextObjectOccupiedId+7)

				// // moveNextTarget(lSelectedObject, 1, 0);
				setTimeout(function() {
					console.log("south tween next target with occupied Id ", bNextObjectOccupiedId+7-1)
					lIsHitted= true;
					setTargetObject(bNextObjectOccupiedId+7-1);
					tweenTarget("south")
				}, bSpeed*21)

			}
			else { console.log("south if - else block")
				playFlingPush()
				var bPX = lSelectedObject._x; var bPY = lSelectedObject._y
				// lNextPlaceToMove = floatToInt(lNextPlaceToMove)
				var bSpeed = lSoccerBallSpeedPerGrid*lNextPlaceToMove
				lNextPlaceToMove = lSelectedObject._y + lNextPlaceToMove*lGridSize-lGridSize/2
				console.log("next place to move ", lNextPlaceToMove, " from , bSpeed ",bPY, bSpeed )
				if(bSpeed==0) { lNextPlaceToMove = lNextPlaceToMove + 30; bSpeed = 10; }
				lIsMoving=true; lIsSelected=true;
				lSelectedObject.tween({y:lNextPlaceToMove}, bSpeed)

				setTimeout(function() {
					console.log("south set previous position ")
					if(lIsHitted) {
						undo[undo.length] = [lSelectedObject.imageName, bPX, bPY, lSelectedObject.occupiedId, "Deleted"]
						occupied[lSelectedObject.occupiedId]=0;
						occupiedObjectName[lSelectedObject.occupiedId]=0;
						lIsHitted = false;
						lIsMoving=false;
						lIsSelected = false;
				// // 		// lSelectedObject.destroy();
						lSelectedObject.isDeleted = true; 
						lSelectedObject.visible = false
						pushDataToUndoStack(undo)
						lTotalObjects--; checkTotalSoccerBalls();
						debugPrintOccupiedPlaces()
				// // 		//check if total objects ==1 then you won, load next level
						console.log("south total objects now ", soccerBallA.length, lTotalObjects)
					}
					else { lIsHitted = false;
						lIsMoving=false;
						lIsSelected = false; lSelectedObject.x= bPX; lSelectedObject.y = bPY; pushDataToUndoStack(undo)	}
				}, bSpeed*21)

			}
		}
		else if(lIsHitted && (occupied[lSelectedObject.occupiedId+7]==0 || lSelectedObject.occupiedId> 48)){
			console.log("south else if block 1")
			playFlingPush()
			undo[undo.length] = [lSelectedObject.imageName, lSelectedObject._x, lSelectedObject._y, lSelectedObject.occupiedId, "Deleted"]
			lIsMoving=true; lIsSelected=true;
			lSelectedObject.tween({y:lSelectedObject._y+lGridSize/4}, lSoccerBallSpeedPerGrid)
			occupied[lSelectedObject.occupiedId]=0;
			occupiedObjectName[lSelectedObject.occupiedId]=0;
			pushDataToUndoStack(undo)
			setTimeout(function() {
				lIsHitted=false; lIsMoving=false; lIsSelected=false;
				lSelectedObject.isDeleted = true; lSelectedObject.visible=false;
				lTotalObjects--; checkTotalSoccerBalls();
			}, lSoccerBallSpeedPerGrid*21)
		}
		else if(lIsHitted && occupied[lSelectedObject.occupiedId+7] > 0) {
			console.log("south else if block 2")
			setTargetObject(lSelectedObject.occupiedId+7);
			tweenTarget("south")
		}
		else { console.log("south final else block", lIsHitted, occupied[lSelectedObject.occupiedId+7], lSelectedObject.occupiedId)
			lIsHitted = false; lIsMoving=false; lIsSelected = false; pushDataToUndoStack(undo)
		}
	}
}

function moveTarget() {
	highlightTarget.alpha = 0.01;
	//check presentX and nextX so that you can get easily n,s,e,w directions
	//and check in particular direction whether the next or previous or upper or lower block has filled or not
	//if filled do not move  else move the selected ball
	var bDiffX = lNextX - lPresentX;
	var bDiffY = lNextY - lPresentY;
	console.log("difference X and Y ", bDiffX, bDiffY, Crafty.math.abs(bDiffX), Crafty.math.abs(bDiffY))
	// if(Crafty.math.abs(bDiffX) > Crafty.math.abs(bDiffY)) {
	if(Crafty.math.abs(Crafty.math.abs(bDiffX) - Crafty.math.abs(bDiffY))< 20) {
		lIsSelected=false;
		return true ;
	}
	if(Crafty.math.abs(bDiffX) > Crafty.math.abs(bDiffY)) {
		//x direction movement
		if(bDiffX > 0) {
			//east direction, with addition of x
			console.log("east direction")
			tweenTarget("east");
		}
		else {
			//west direction, with negation of x
			console.log("west direction")
			tweenTarget("west")
			// moveNextTarget(lSelectedObject, -1, 0);
		}
	}
	else{
			
		//y direction movement
		if(bDiffY > 0) {
			console.log("south direction")
			tweenTarget("south");
			//south direction movement
			// moveNextTarget(lSelectedObject, 0, 1);
		}
		else {
			//north direction movement
			console.log("north direction")
			tweenTarget("north");
			// moveNextTarget(lSelectedObject, 0, -1);
		}
	}
	

	// setTimeout(function() {
	// 	clearInterval(lTimer1);
	// }, 5000)
	bDiffX=null; bDiffY=null;
}

function selectTarget(pTarget, pViceVersa) {
	if(lIsSelected) { return true }
	lIsSelected=true;
	lSelectedObject=pTarget
	console.log("move target puzzle id is ", pTarget.puzzleId, pTarget.imageName);
	lPresentX = pTarget._x; lPresentY= pTarget._y;
	for (i=1; i<=soccerBallBoxA.length; i++){
		if(soccerBallBoxA[i-1].puzzleId == pTarget.puzzleId) {
			console.log("target box is matched ");
			lIndexBoxA=i-1
			break;
		}
	}
	if(pViceVersa) {
		for (i=1; i<=soccerBallA.length; i++){
		if(soccerBallBoxA[i-1].puzzleId == pTarget.puzzleId) {
			console.log("target box is matched ");
			lSelectedObject = soccerBallA[i-1];
			break;
		}
	}
	}

	highlightTarget.alpha=1.0
	highlightTarget.x=lSelectedObject._x-12; highlightTarget.y = lSelectedObject._y-12;
	highlightTarget.animate('animate1', 15, -1) 
}

function placeSoccers() {
	
	console.log("soccer placement length ", soccerPlacement.length, lsoccerPlacementString)
	for(var i=1; i<= soccerPlacement.length ; i++) {
		// if(soccerPlacement[i-1] == 0) {
			// occupied[i-1] = soccerPlacement[i-1];	
		// } else { occupied[i-1] = 1;}
		if(soccerPlacement[i-1] != undefined) {
			occupiedObjectName[i-1]= soccerPlacement[i-1];
			occupied[i-1] = soccerPlacement[i-1];	
		}
		if(soccerPlacement[i-1] != 0 && soccerPlacement[i-1] != undefined) {
			console.log(" i ", i, soccerPlacement[i-1])
			var soccerBall = Crafty.e("2D, Canvas, Image, Tween, Mouse").image("images/ball"+soccerPlacement[i-1]+".png");
	        soccerBall.puzzleId = i; soccerBall.occupiedId = i-1;
	        soccerBall.setName('soccerBall')
	        soccerBall.x= lStepX; soccerBall.y= lStepY;
	        soccerBall.imageName =  soccerPlacement[i-1];
	        soccerBall.isDeleted = false;
	        soccerBall.bind("MouseDown", function(e) { 
	        	
        		// console.log("my puzzle id is ", this.puzzleId, this.imageName)
        		if(lIsSelected==false) {
        			selectTarget(this, false);
        		}
				else if(lIsSelected && lIsMoving == false) {
		    		
		    	}
		    	
        	});
        	soccerBall.bind("MouseUp", function(e) {
        		console.log("soccer ball mouse up ", lIsSelected, lIsMoving, lIsHitted)
        		if(lIsSelected && lIsMoving == false && lIsHitted==false) {
        			lNextX = e.clientX; lNextY = e.clientY;
        			highlightTarget.stop();
		    		moveTarget();	
        		}
        	})
	        soccerBallA.push(soccerBall);
	        
		}	
		lStepX += lGridSize;
		if(i%7==0) {
			lStepX = lBeginX; lStepY += lGridSize;
			// console.log("placement ",i, soccerPlacement[i-1])
		}
	}
	lTotalObjects = soccerBallA.length;
	console.log("the length of soccerball, soccerBallBoxA", soccerBallA.length, soccerBallBoxA.length);
	console.log("occupied object name ", occupiedObjectName, occupiedObjectName.length)
	console.log("occupied object name ", occupied, occupied.length)
	console.log("total objects are ",lTotalObjects)
}



Crafty.scene('GamePlay', function() {
    setScreenScale();
	setBgMusicPlaying(); //stop the menu music here
	Crafty.audio.stop();
    Crafty.background('rgb(0,0,0)');
    console.log("GAMEPLAY SCREEN");
    // Crafty.e("2D, Canvas, Text").attr({ w: 100, h: 20, x: Crafty.viewport.width/2-50, y: Crafty.viewport.height/2-10 })
    // .text("Loading...")
    // .css({ "text-align": "center" });

    // Crafty.load(["images/game_grid.png", "images/game_bg.png", "images/game_Logo.png", "images/bg.png"],
	// function() {
	         //when loaded
	      
	bg = Crafty.e("2D, Canvas, Image").image("images/game_bg.png");
	bg.x = Crafty.viewport.width/2-320/2; bg.y = Crafty.viewport.height/2-480/2;
	lBeginX = bg._x+12; lBeginY = bg._y+71;

	lTTextX=bg._x + 160;  lTTextY=bg._y+396;

//	game_upper_bar = Crafty.e("2D, Canvas, Image").image("images/game_upper_bar.png");
//	game_upper_bar.x = bg._x ; game_upper_bar.y = bg._y;
    
    game_upper_bar = Crafty.e("2D, Canvas, Image").image("images/hud.png");
	game_upper_bar.x = bg._x ; game_upper_bar.y = bg._y+19;

	level_hud = Crafty.e("2D, Canvas, Image").image("images/game_hud_level.png");
	level_hud.x = bg._x+5; level_hud.y = bg._y+29;
	
	puzzle_hud = Crafty.e("2D, Canvas, Image").image("images/game_hud_puzzle.png");
	puzzle_hud.x = bg._x + 167; puzzle_hud.y = bg._y+29;

//	game_hud_timer = Crafty.e("2D, Canvas, Image").image("images/game_hud_timer1.png");
//	game_hud_timer.x = bg._x + 116; game_hud_timer.y = bg._y+31;

//    game_hud_level1 = Crafty.e("2D, Canvas, Image").image("images/game_hud_level1.png");
//	game_hud_level1.x = bg._x + 4.5; game_hud_level1.y = bg._y+31;
//
//	game_hud_level2 = Crafty.e("2D, Canvas, Image").image("images/game_hud_level2.png");
//	game_hud_level2.x = bg._x + 206; game_hud_level2.y = bg._y+31;

	game_lower_bar = Crafty.e("2D, Canvas, Image").image("images/game_lower_bar.png");
	game_lower_bar.x = bg._x ; game_lower_bar.y = bg._y+413;
    
    timer_hud = Crafty.e("2D, Canvas, Image").image("images/game_hud_timer.png");
	timer_hud.x = bg._x + 73; timer_hud.y = bg._y+424;
    
//    pauseBtnHover = Crafty.e("2D, Canvas, Image, Mouse").image("images/onclick_ingame.png");
//    pauseBtnHover.x = bg._x+4; pauseBtnHover.y = bg._y + 415;

	pauseBtn = Crafty.e("2D, Canvas, Image, Mouse").image("images/pause_btn.png");
	pauseBtn.x = bg._x+8; pauseBtn.y = bg._y + 420;
	
//    undoBtnHover = Crafty.e("2D, Canvas, Image, Mouse").image("images/onclick_ingame1.png");
//    undoBtnHover.x = bg._x+261; undoBtnHover.y = bg._y + 415;

	undoBtn = Crafty.e("2D, Canvas, Image, Mouse").image("images/undo_btn.png");
	undoBtn.x = bg._x +265; undoBtn.y = bg._y + 420;
    
    gameGrid=Crafty.e("2D, Canvas, Image, Mouse").image("images/game_grid.png");
	gameGrid.x = bg._x+12; gameGrid.y = bg._y+71;

	highlightTarget = Crafty.e("2D, Canvas, SpriteAnimation, targetSelectedBall");
	highlightTarget.alpha = 0.01;
	highlightTarget.animate('animate1', 0, 0, 2) //setup animation

		    
	// highlightTarget.w=1; highlightTarget.h=1;
	// highlightTarget.tween({w:44, h:44}, 2000)

	// var levelName = Crafty.e("2D, Canvas, Text, Mouse").textFont({ size:'25px', type: 'normal', family: 'Clubland' });
	// levelName.text(lLevelId); levelName.textColor('#ffffff'); levelName.alpha=0.7
		 	// levelName.x = level_hud._x+50; levelName.y = level_hud._y+25
		 	// levelName.css({'-moz-user-select': 'none', '-moz-user-drag': 'none', '-webkit-user-select': 'none'}); //user-select: none;

		 	// var puzzleName = Crafty.e("2D, Canvas, Text, Mouse").textFont({ size:'25px', type: 'normal', family: 'Clubland' });
		 	// puzzleName.css({'-moz-user-select': 'none', '-moz-user-drag': 'none', '-webkit-user-select': 'none'}); //user-select: none;
		 	// // puzzleName.css({'-webkit-user-drag': 'none'})
		 	// puzzleName.text(lPuzzleId); puzzleName.textColor('#ffffff'); puzzleName.alpha = 0.7
		 	// puzzleName.x = puzzle_hud._x+45; puzzleName.y = puzzle_hud._y+25

		 	// puzzleName.bind("MouseMove", function(e) { e.preventDefault(); return true ;})
		 	// levelName.bind("MouseMove", function(e) { e.preventDefault(); return true ;})
		 	
	
	if(lLevelId!=10)
		var levelName = Crafty.e("2D, Canvas, number"+lLevelId).attr({x:level_hud._x+117, y:puzzle_hud._y+5});
    
	 	
	else{
		var levelName1 = Crafty.e("2D, Canvas, number1").attr({x:level_hud._x+110, y:puzzle_hud._y+5});
		var levelName2 = Crafty.e("2D, Canvas, number0").attr({x:level_hud._x+125, y:puzzle_hud._y+5});
	}

		 	// var puzzleName = 
	console.log("l puzzle id is ", lPuzzleId, (lPuzzleId-1))
	var puzzleName = Crafty.e("2D, Canvas, number"+lPuzzleId).attr({x:puzzle_hud._x+15, y:puzzle_hud._y+5});
		    // lEntity.x=puzzle_hud._x+45; lEntity.y=puzzle_hud._y+55;
		    // puzzleName.x=300; puzzleName.y=300;
		 	// createNumber(lPuzzleId, puzzle_hud._x+45, puzzle_hud._y+25)
		 	// puzzleName.x = puzzle_hud._x+45; puzzleName.y = puzzle_hud._y+25

		 	// disableSelection(puzzleName)
		 	// puzzleName.
		 	// Crafty.settings.register("stageSelectable", puzzleName)
		 	// Crafty.settings.modify("stageSelectable", true);

		 	// Crafty.stage.elem.onselectstart = function(e) { return true;}
		 	// console.log("get element ", document.getElementById('cr-stage')) 
		 	// var myCraftyObject = document.getElementById('cr-stage')



		 	// myCraftyObject.addEventListener('MouseMove', onCraftyMouseDown)

           
            
    //         timerText = Crafty.e("2D, Canvas, Text").textFont({ size:'28px', type: 'normal', family: 'Arial Black' });
		 	// timerText.text(lBeginTimer); timerText.textColor('#ffffff'); timerText.alpha = 0.5;
		 	// timerText.x = timer_hud._x+25; timerText.y = timer_hud._y+22 ;
		 	
		 	
       
              //timerText1.alpha = 0.01;
            
	gameGrid.bind("MouseDown", function() {
	   	console.log("grid mouse down moving, selected, hitted", lIsMoving, lIsSelected, lIsHitted);
	});



	if(lGameMode=="Arcade") {
	   	// timerText.alpha = 0.01;
	   	timer_hud.alpha = 0.01;
	   	//game_hud_timer.alpha=0.01;
	}
	else {
	   	createNumber(lBeginTimer, lTTextX, lTTextY)
	}

	
	undoBtn.bind("MouseDown", function() {
	   	if(!lIsMoving && !lIsSelected) {
	   		console.log("undo button clicked")
	   		//call undo stack function here
	   		undoTheStack();
        }
        if(lGameMode=="Challenge" && lIsUndoDone){
            restartBtn = Crafty.e("2D, Canvas, Image, Mouse").image("images/restart_btn_ingame.png");
		    restartBtn.x = bg._x +265; restartBtn.y = bg._y + 420;

		    
			restartBtn.bind("MouseDown", function(e) {
		       	lIsUndoDone=false;
		       	restartBtn.destroy();
		      	resetPuzzle();	
		    })
		     
		}
		
	});
               
            
		    
    pauseBtn.bind("MouseDown", function(e) {
	   	console.log("pause button clicked")
	   	if(lGameFinished) return ;
	    	setTimerText(false)
	    	createPauseScreen();
	    })

	    gameGrid.bind("MouseUp", function(event) {
	    	console.log("grid mouse up moving, selected, hitted", lIsMoving, lIsSelected, lIsHitted);
	    	if(lIsMoving || lIsSelected==false || lIsHitted==true) { return true; }
		    	lNextX = event.clientX; lNextY = event.clientY;
		    	highlightTarget.stop();
		    	moveTarget();
		    });
		    // readTextFile("levels/"+lGameMode+"/Level"+lLevelId+"/"+lPuzzleId+".txt", bg);
		    resetGame();
		    // initGame();

		    playBgMusic("GameMusic")
	        
	     // }
	 // );
			
    
});


Crafty.c("Box", {
    init: function() {
		this.addComponent("2D, Canvas, Color");
	},
    
    makeBox: function(color, x1, y1, W1, H1){  
        this.attr({x: x1, y: y1, w: W1, h: H1});
        this.color(color);
        this.alpha=0.5;
        return this;  
    }

});


Crafty.c("SoccerBallBox", {
    init: function(){
        this.addComponent("Box, Collision");
      
        this.collision();
    } 

});

// function onCraftyMouseDown(evt) {
// 	evt.preventDefault();
// }

// this function disables text select on a perticular dom object
// function disableSelection(target)
// {
//     if (typeof target.onselectstart!="undefined") //IE route
//         target.onselectstart=function(){return false}
//     else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
//         target.style.MozUserSelect="none"
//     else //All other route (ie: Opera)
//         target.onmousedown=function(){return false}
//     target.style.cursor = "default"
// }

