var autoLogout = 60;
var outOfSync = "N";
function startGame()
{
	//showDebug();
	debug("Starting Game");
	attackWaitTime = document.getElementById("attackWaitTime").value;
	movementWaitTime = document.getElementById("movementWaitTime").value;
	autoLogout = getGameVariable("autoLogout"); 
	//setChatLocation(getGameVariable("chatX"), getGameVariable("chatY"));	
	
	play();
}

//
// Call this once the entire page loads
//
function play()
{
	//debug("Play Loop:" + step + " Logout in " + autoLogout + " secs");
	
	if(autoLogout <= 0)
	{
		window.location.href="./";
	}
	
	if(outOfSync == 'Y')
	{
		showGameMsg("Syncing....");
		window.location.href = "play.php";
	}
	
	autoLogout--;
	
	if(step == 0)
	{
		debug("Initial Map Setup");
		updateMap();
		if(selectedUnitID > 0)
		{
			url="newUnit.php?newUnitAction=refresh&unitID=" + selectedUnitID;
			requestData(url, refreshUnitInfo);
		}
		
	}
	
	if(step%(gameRefreshRate/1000) == 0 && step !=0)
	{
		debug("Step:" + step + " Refresh Rate:" + gameRefreshRate);
		updateMap();
		runAI();	
	}
	
	if(step%25 == 0)
	{
		document.getElementById("debugPanel").innerHTML = "";
	}
	updateWaitTime(1);
	
	
	//
	// update the wait time counter
	//
	
	step++;
	
	setTimeout("play()", 1000);

}



lastAi = 0;
function runAI()
{
	//showDebug();
	debug("Running AI");
	//
	//check newly added units
	//
	var unitIDArray = getUnitIDs().split(",");
	
	aiID = 0;
	for(i=lastAi;i<unitIDArray.length;i++)
	{
		newU = document.getElementById("unit_" + unitIDArray[i]);
		if(newU != null)
		{
			if(newU.getAttribute("usesAi") == 'Y' 
				&& newU.getAttribute("life") > 0
				&& newU.getAttribute("waitTime") <= 0)
			{
				lastAi = i;
				aiID = unitIDArray[i];
				debug("Running AI for " + aiID);
				break;
			}
		}

	}

	if(aiID == 0)
	{
		lastAi =0;
		return;
	}
	
	aiObj = document.getElementById("unit_" + aiID);
	
	if(aiObj == null)
	{
		return;
	}
	
	if(aiObj.getAttribute("waitTime") <= 0)
	{
		debug("AI: target");
		targetID = attackNearestEnemyWithinRange(aiID, aiObj.getAttribute("range"));

		if(targetID == 0)
		{
			//
			// no one to attack, move to nearest enemy
			//
			moveToNearestEnemy(aiID);
			debug("AI: moving");
			setWaitTime(aiID, movementWaitTime);
		}
		else
		{
			setWaitTime(aiID, attackWaitTime);
		}
	}
	
	lastAi++;
}

