var numAliensCreated=0;
var gameOver=false;
var secs;
var timerID = null;
var timerRunning = false;
var delay = 1000;
var aliensDefeated=0;
var alienImages = new Array();
var gameInProgress=false;
var timesCalled=0;
var missedAliens=0;
var highScore=0;
var level=1;
var numAliensAllowed=0;
var disappearTime=10;
var alienSpeed=200;
var alienID = 0;
var gamePaused=false;
var gameCount=0;
var totalScore=0;

function setup(){
	showAdd();
	showIntroText();
}

function showIntroText(){
	updateMainText("You are on a space ship and have been attacked by aliens. They are boarding your ship and you must stop the transport of these aliens before they takeover your ship. Tap the aliens as they appear to capture all the aliens before the time runs out and your ship explodes!    If you capture more aliens than you miss, go on to the next Level!");
}

function hideMainText(){
	updateMainText("");
}

function newGame(){
	if (gameInProgress){
		if (gameCount % 5 == 0){
			support();
		}
		else if (!gameOver){
			gamePaused = true;
			StopTheClock();
			if (!confirm("Are you sure you want to start a new game?")){
				gamePaused=false;
				StartTheTimer();
				startPopAlien();
				return;
			}
			else{
				deleteAllAliens();
			}
		}
	}
	gamePaused=false;
	gameCount++;
	initGlobals();
	alienID = 0;
	var back = document.getElementById("shipoutline");
	back.style.backgroundImage = "url('./images/Spaceship.jpg')";
	level = 1;
	setLevelButtonText();
	newLevel();
}

function playLevelButton(){
	if (level==1){
		return;
	}
	else{
		hideLevelButton();
		newLevel();
	}
}

function initGlobals(){
	aliensDefeated=0;
	gameOver=false;
	timesCalled=0;
	numAliensCreated=0;
	for(var x=0; x <= 9; x++){
		alienImages[x]=-99;
	}
	missedAliens=0;
}

function newLevel(){
	hideMainText();
	initGlobals();
	updateStatusText("DEFEATED: "+aliensDefeated+" MISSED: "+missedAliens);
	deleteAllAliens();
	InitializeTimer();
	gameInProgress=true;
	setLevelParameters();
	deleteAllAliens();
	startPopAlien();
}

function startPopAlien(){
	if (!gameOver && timerRunning && !gamePaused){
		if (numAliensCreated<numAliensAllowed){
			createAlien();
		}
		if (timesCalled>disappearTime){
			checkForOldAliens();
			timesCalled=0;
			missedAliens++;
		}
		timesCalled++;
		//updateMainText(checkAlienCreated(0)+","+checkAlienCreated(1)+","+checkAlienCreated(2)+","+checkAlienCreated(3)+","+checkAlienCreated(4)+","+checkAlienCreated(5)+","+checkAlienCreated(6)+","+checkAlienCreated(7)+","+checkAlienCreated(8)+","+checkAlienCreated(9));
		updateStatusText("DEFEATED: "+aliensDefeated+" MISSED: "+missedAliens);
		setTimeout('startPopAlien()', alienSpeed);
	}
}

function checkForOldAliens(){
	var lowestNum = 0;
	var firstNum= false;
	var ID = -99;
	for(x=0; x<level; x++){
		var y=checkAlienCreated(x);
		if(y!=-99){
			if(!firstNum){
				if(alienImages[x] != -99){
					lowestNum=y;
					firstNum=true;
					ID=x;
				}
			}
			if(y<lowestNum){
				lowestNum=y;
				ID=x;
			}
		}
	}
	if (ID!= -99){
		deleteAlien(ID);
	}
}

function divClicked(clicked) {
	if (gameOver){
		return;
	}
	if (!timerRunning){
		return;
	}
	aliensDefeated++;
	updateStatusText("DEFEATED: "+aliensDefeated+" MISSED: "+missedAliens);
	deleteAlien(clicked.id);
	timesCalled=0;
}

function createAlien(){
	var whichAlien = numAliensCreated;
	if (whichAlien>9){
		return;
	}
	for(var x=0; x<level; x++){
		if(checkAlienCreated(x)==-99){
			whichAlien=x;
			x=10;
		}
	}
	var theContainer = document.getElementById(""+whichAlien);
	var alienPortimg = document.createElement("img");
	alienPortimg.setAttribute("src", "images/SpaceInvaderGuy.gif");
	alienPortimg.setAttribute("id", "alien"+whichAlien);
	alienPortimg.style.position="absolute";
	alienPortimg.setAttribute("width", 30);
	alienPortimg.setAttribute("height", 30);
	var alienTop=Math.random()*230;
	var alienLeft=Math.random()*230;
	alienPortimg.style.top=""+alienTop+"px";
	alienPortimg.style.left=""+alienLeft+"px";
	theContainer.appendChild(alienPortimg);
	alienID++;
	alienImages[whichAlien]=alienID;
	numAliensCreated++;
}

function checkAlienCreated(num){
	return alienImages[num];
}

function deleteAllAliens(){
	for (var x=0; x<level; x++){
		if (alienImages[x]!=-99){
			deleteAlien(x);
		}
	}
}

function deleteAlien(id){
	var theAlienContainer = document.getElementById(""+id);
	var theChild = document.getElementById("alien"+id);        
	theAlienContainer.removeChild(theChild);
	alienImages[id]=-99;
	numAliensCreated--;
}

function updateStatusText(string){
	var text = document.getElementById("status");
	text.innerHTML = "" + string;	
}

function updateTimer(){
	var canvas = document.getElementById("timercanvas");
	canvas.style.visibility="visible";
	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 updateMainText(string){
	var text = document.getElementById("maintext");
	text.innerHTML = "" + string;	
}

function setLevelParameters(){
	numAliensAllowed = level;
}

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

function setScore(){
	var text1="";
	var text2="";
	var yourScore = (aliensDefeated-missedAliens)*100;
	if (yourScore < 0){
		yourScore = 0;
	}
	totalScore+=yourScore;

	if ((aliensDefeated - missedAliens) * 100 > 0){
		if(level<10){
			level++;
			text2="Go on to LEVEL "+level+"!";
			addLevelButton();
			updateNextLevelButtonText();
		}
		else{
			gameOver=true;
			level=1;
			text2="You Won! Total Score: "+totalScore;
		}
	}
	else{
		gameOver=true;
		explosionDraw();
		text2="GAME OVER! Total Score: "+totalScore;
		level=1;
	}
	setLevelButtonText();
	text1="Your score = "+yourScore+". ";
	updateMainText("You captured "+aliensDefeated+"! "+missedAliens+" got away."+text1+text2);
}

function explosionDraw(){
	var backGroundContainer = document.getElementById("shipoutline");
	backGroundContainer.style.backgroundImage = "url('./images/Explosion.jpg')"
}

function EndGameCleanup(){
	updateTimer();
	deleteAllAliens();
	setScore();
}

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 orientationChanged(){
}

function updateNextLevelButtonText(){
	var theNextLevelButton = document.getElementById("nextLevel");
	theNextLevelButton.style.visibility="visible";
	theNextLevelButton.innerHTML="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";
}

