var numBallsCreated=0;
var gameOver=false;
var secs;
var timerID = null;
var timerRunning = false;
var delay = 1000;
var ballsCollected = 0;
var ballsCollectedThisLevel=0;
var ballImages = new Array();
var ballsNeeded = new Array();
var gameInProgress=false;
var highScore=0;
var yourScore=0;
var ballNum=0;
var ballToExplode=-99;
var timesCalled;
var congratulations=false;
var gameCount=0;
var gamePaused=false;
//these vary per level
var level=1;
var maxNumBalls=0;
var disappearTime=0;
var ballSpeed=0;

function setup(){
	showAdd();
	showIntroText();
	initBallImageArray();
	initBallsNeededArray();
	hideLevelButton();
}

function showIntroText(){
	updateText("maintext", "Tap the balls before they disappear! For level 1, blast 20 balls to advance to level 2. Each level requires more balls to advance to the next level. See if you can complete all 10 levels!");
}

function initBallImageArray(){
	for (var x=0; x<10; x++){
		ballImages[x]=-99;
	}
}

function initBallsNeededArray(){
	ballsNeeded[1]=15;
	ballsNeeded[2]=20;
	ballsNeeded[3]=30;
	ballsNeeded[4]=40;
	ballsNeeded[5]=45;
	ballsNeeded[6]=50;
	ballsNeeded[7]=52;
	ballsNeeded[8]=53;
	ballsNeeded[9]=54;
	ballsNeeded[10]=55;
}

function hideMainText(){
	updateText("maintext", "");
}

function newGame(){
	if (gameInProgress){
//		if (gameCount % 5 == 0){
//			support();
//		}
//		else if (!gameOver){
		if (!gameOver){
			gamePaused=true;
			StopTheClock();
			if (!confirm("Are you sure you want to start a new game?")){
				gamePaused=false;
				StartTheTimer();
				startPopBall();
				return;
			}
		}
	}
	gamePaused=false;
	gameCount++;
	level=1;
	yourScore=0;
	ballsCollected=0;
	ballsCollectedThisLevel=0;
	newLevel();
}

function playLevelButton(){
	hideLevelButton();
	newLevel();
}

function initGlobals(){
	gameOver=false;
	numBallsCreated=0;
	ballNum=0;
	timesCalled=0;
	ballsCollectedThisLevel=0;
}

function newLevel(){
	clearBoard();
	hideMainText();
	initGlobals();
	updateText("status", "");
	InitializeTimer();
	setLevelParameters();
	setLevelButtonText();
	startPopBall();
}

function startPopBall(){
	if (!gameOver && timerRunning && !gamePaused){
		checkToCreateBalls();
		checkForOldBalls();
		checkForExplodedBalls();
		calculateScore();
		timesCalled++;
/*
		updateText("highscore", checkBallCreated(0)+","+checkBallCreated(1)+","+checkBallCreated(2)+","+checkBallCreated(3)+","+checkBallCreated(4)+","+checkBallCreated(5)+","+checkBallCreated(6)+","+checkBallCreated(7)+","+checkBallCreated(8)+","+checkBallCreated(9));
*/
		setTimeout('startPopBall()', ballSpeed);
	}
}

function divClicked(clicked) {
	if (gameOver){
		return;
	}
	if (!timerRunning){
		return;
	}
	ballsCollected++;
	ballsCollectedThisLevel++;
	gameInProgress=true;
	timesCalled=0;
	ballToExplode = parseInt(clicked.id);
	explodeBall(ballToExplode);
	setBallExploded(ballToExplode);
	calculateScore();
}

function createBall(){
	//we cannot make more than 10 balls at this time
	if (numBallsCreated>10){
		return;
	}
	for (var x=0; x<level; x++){
		if (checkBallCreated(x) == -99){
			var whichBall = x;
			x=level;
		}
	}
	var theContainer = document.getElementById(""+whichBall);
	var ballImg = document.createElement("img");
	ballImg.setAttribute("width", 30);
	ballImg.setAttribute("height", 30);
	ballImg.setAttribute("src", "images/ball-"+(level%5)+".png");
	ballImg.setAttribute("id", "ball"+whichBall);
	ballImg.style.position="absolute";
	var ballTop=Math.floor(Math.random()*250);
	var ballLeft=Math.floor(Math.random()*260);
	ballImg.style.top=""+ballTop+"px";
	ballImg.style.left=""+ballLeft+"px";
	theContainer.appendChild(ballImg);
	numBallsCreated++;
	setBallCreated(whichBall);
}

function checkBallCreated(num){
	return ballImages[num];
}

function setBallCreated(num){
	ballNum++;	//this is the order in which the balls are created
	ballImages[num] = ballNum;
}

function setBallExploded(num){
	ballImages[num] = -1;
}

function setBallDeleted(num){
	//set this to -99 to show that no ball exists in that place
	ballImages[num]=-99;
}

function checkToCreateBalls(){
	if (numBallsCreated < maxNumBalls){
		createBall();
	}
}

function checkForOldBalls(){
	if (timesCalled > disappearTime){
		var lowestNum=0;
		var gotFirstNum=false;
		var balltodelete=-99;
		for (var x=0; x<level; x++){
		//this checks the array of balls for the lowest number, which is the first created
			var y = checkBallCreated(x);
			if (y != -99){
				if (!gotFirstNum){
					lowestNum=y;
					gotFirstNum=true;
					balltodelete=x;
				}
				else if (y < lowestNum){
					lowestNum=y;
					balltodelete=x;
				}
			}
		}
		if (balltodelete!=-99){
			deleteBall(balltodelete);
		}
		timesCalled=0;
	}
}

function checkForExplodedBalls(){
	if (ballToExplode!=-99){
		if (checkBallCreated(ballToExplode) == -1){
			deleteBall(ballToExplode);
		}
		ballToExplode=-99;
	}
}

function explodeBall(num){
	var ballImg=document.getElementById("ball"+num);
	ballImg.setAttribute("src", "images/kaboom.png");
	ballImg.setAttribute("width", 50);
	ballImg.setAttribute("height", 50);
}

function deleteBall(id){
	var theBallContainer = document.getElementById(""+id);
	var theChild = document.getElementById("ball"+id);        
	theBallContainer.removeChild(theChild);
	setBallDeleted(id);
	numBallsCreated--;
}

function clearBoard(){
	for (var x=0; x<10; x++){
		if (checkBallCreated(x) != -99){
			deleteBall(x);
		}
	}
}

function updateText(string1, string2){
	var text = document.getElementById(string1);
	text.innerHTML = "" + string2;	
}

function updateTimer(){
    var canvas = document.getElementById("timercanvas");
    var ctx = canvas.getContext('2d');
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.fillStyle="rgb(0,0,0)";
    ctx.fillRect(0, 0, canvas.width, canvas.height*(secs/30));
}

function setLevelParameters(){
	maxNumBalls=level;
	disappearTime=60;
	ballSpeed = 60;
}

function setLevelButtonText(){
	document.getElementById("level").innerHTML="Level "+level;
}

function drawLevelButtonOutline(){
	document.getElementById("levelcanvas").style.border="thin solid white";
}

function clearLevelButtonOutline(){
	document.getElementById("levelcanvas").style.border="thin solid black";
}

function showScore(){
	var text1="";
	var text2="";
	var text3="";

	if (ballsCollectedThisLevel >= ballsNeeded[level]){
		level++;
		if (level <= 10){
			text2=" Go on to LEVEL "+level+"!";
			text3=" You need "+ ballsNeeded[level]+" balls next level to advance.";
			updateNextLevelButtonText();
			addLevelButton();
		}
		else{
			gameOver=true;
			text2=" You won! GAME OVER";
			level=1;
		}
	}
	else{
		gameOver=true;
		text2=" GAME OVER";
		level=1;
	}
	calculateScore();
	if (congratulations){
		text1=" Congratulations, you have the high score!";
	}
	updateText("maintext", "You blasted "+ballsCollectedThisLevel+" balls this level! "+text1+text2+text3);
}

function calculateScore(){
	updateText("status", "Score: "+ballsCollectedThisLevel);
	if (ballsCollected>highScore){
		highScore = ballsCollected;
		congratulations=true;
	}
	updateText("highscore", "High Score: "+highScore);
}

function EndGameCleanup(){
	clearBoard();
	showScore();
}

function InitializeTimer()
{
    // Set the length of the timer, in seconds
    secs = 30;
    StopTheClock();
    StartTheTimer();
}

function StopTheClock()
{
    if (timerRunning){
        clearTimeout(timerID);
	}
    timerRunning = false;
}

function StartTheTimer()
{
    if (secs==0)
    {
        StopTheClock();
		EndGameCleanup();
    }
    else if (gamePaused){
		return;
	}
	else
    {
		updateTimer();
		secs--;
        timerRunning = true;
        timerID = self.setTimeout("StartTheTimer()", delay);
    }
}

function updateNextLevelButtonText(){
	var theNextLevelButton = document.getElementById("nextLevel");
	theNextLevelButton.style.visibility="visible";
	updateText("nextLevel", "Level "+level);
}

function addLevelButton(){
	new Effect.Appear('nextLevel', { duration: .2 * 2.0 , from: 0.0, to: 1.0});
}

function hideLevelButton(){
	new Effect.Fade('nextLevel', { duration: .2});
}

function support() {
    showAdd();
}

function closeSupport() {
    hideAdd();
	document.getElementById("container").style.visibility="visible";
}

function orientationChanged(){
}