function getMapID() { return parseInt(document.getElementById("mapID").value); }
function getMapWidth() { return parseInt(document.getElementById("boardWidth").value); }
function getMapHeight() { return parseInt(document.getElementById("boardHeight").value); }

function showGameMsg(msg)
{
	var d = document.getElementById("gameMsg");
	d.innerHTML = msg;
	d.style.visibility = "visible";

}

function hideGameMsg()
{
	var d = document.getElementById("gameMsg");
	d.innerHTML = "";
	d.style.visibility = "hidden";
}


function removeObject(objectID)
{
	d = document.getElementById("obj_" + objectID);
	d.style.top = "-1000px";
	d.style.visibility = "hidden";
	d.setAttribute("tileX",-1);
	d.setAttribute("tileY",-1);
}


function getRandomNumber(min, max)
{
	return min + Math.floor(Math.random()* (max - min));
}


function getRandomEmptyPositionBetween(minX, maxX, maxY, minY)
{
	var pos = new Array(2);
	x = minX + Math.floor(Math.random()* (maxX - minX));
	y = minY + Math.floor(Math.random()* (maxY - minY));
	
	numTries =0;
	
	while(isWalkable(x, y) != 'Y' && numTries < 20)
	{	
		x = minX + Math.floor(Math.random()* (maxX - minX));
		y = minY + Math.floor(Math.random()* (maxY - minY));
		numTries++;	
	}
	
	pos[0] = x;
	pos[1] = y;

	return pos;
}

function errorHandler(msg)
{
	alert(msg);
	debug(msg);
}

function getMouseOverTile(x, y)
{
	return document.getElementById("tile_" + x + "_" + y + "_mouseover");
}

function getTop(obj)
{
	if(obj)
	{	
		return parseInt(obj.style.top.replace("px",""));
	}
	
	return 0;
}

function getLeft(obj)
{
	if(obj)
	{
		return parseInt(obj.style.left.replace("px",""));
	}
		
	return 0;
}


function setAsNormalTile(x, y)
{
	tile = document.getElementById("tile_" + x + "_" + y);
	if(tile)
	{
		tile.style.visibility="visible";
		document.getElementById("tile_" + x + "_" + y + "_selected").style.visibility="hidden";
		
		document.getElementById("tile_" + x + "_" + y + "_movement").style.visibility="hidden";
		document.getElementById("tile_" + x + "_" + y + "_movement").setAttribute("canMoveTo","N");
	
		document.getElementById("tile_" + x + "_" + y + "_target").style.visibility="hidden";
		document.getElementById("tile_" + x + "_" + y + "_target").setAttribute("canTarget","N");

	}
}

function removeUnit(unitID)
{
	d = document.getElementById("unit_" + unitID);
	d.style.top = "-1000px";
	d.style.visibility = "hidden";
	d.setAttribute("tileX",-1);
	d.setAttribute("tileY",-1);
}

function hideDebug()
{
	document.getElementById("debugPanel").style.visibility="hidden";
}


function showDebug()
{
	document.getElementById("debugPanel").style.visibility="visible";
}

function debug(str)
{
	document.getElementById("debugPanel").innerHTML = str + "<br>" + document.getElementById("debugPanel").innerHTML;

}

function getDistance(x1, y1, x2, y2)
{
	//alert(x1 + "," + y1 + " to " + x2 + "," + y2);
	return (Math.abs(Math.sqrt(((x1 - x2) * (x1 - x2) ) + ( (y1 - y2) * (y1 - y2) ) )));
}


function getDistanceFromUnit(unitID, x2, y2)
{
	objU = document.getElementById('unit_' + unitID);
	return getDistance(objU.getAttribute("tileX"),objU.getAttribute("tileY"),x2,y2);

}

function getDistanceBetweenUnits(unitID, unitID2)
{
	objU = document.getElementById('unit_' + unitID);
	objU2 = document.getElementById('unit_' + unitID2);
	
	return getDistance(objU.getAttribute("tileX"),objU.getAttribute("tileY"),objU2.getAttribute("tileX"),objU2.getAttribute("tileY"));
}

function getNearestEnemy(unitID)
{
	attU = document.getElementById("unit_" + unitID);
	uIDs = getUnitIDs();
	minDistance = 999999;
	targetID = 0;
	var uIDList = uIDs.split(",");
	for(k=0;k<uIDList.length;k++)
	{
		targetU = document.getElementById("unit_" + uIDList[k]);
		if(targetU != null)
		{
			if(targetU.getAttribute("ownerID") != attU.getAttribute("ownerID") && targetU.getAttribute("life") > 0)
			{
				//same owner
				distance = getDistanceBetweenUnits(uIDList[k], unitID);
				if(distance < minDistance)
				{
					targetID = uIDList[k];
					minDistance = distance;
				}
			}
			
		}

	}
	
	
	return targetID;
}


function getNearestEnemyWithinRange(unitID, range)
{
	attU = document.getElementById("unit_" + unitID);
	uIDs = getUnitIDs();
	minDistance = 999999;
	targetID = 0;
	var uIDList = uIDs.split(",");
	for(k=0;k<uIDList.length;k++)
	{
		targetU = document.getElementById("unit_" + uIDList[k]);
		if(targetU != null)
		{
			if(targetU.getAttribute("ownerID") != attU.getAttribute("ownerID")  && targetU.getAttribute("life") > 0)
			{
				//same owner
				distance = getDistanceBetweenUnits(uIDList[k], unitID);
				if(distance < range)
				{
					targetID = uIDList[k];
					minDistance = distance;
					
				}
			}
			
		}

	}
	
	return targetID;
}

function moveToNearestEnemy(unitID)
{
	debug("Moving to Nearest Enemy:" + unitID);
	attUnit = document.getElementById("unit_" + unitID);
	targetID = getNearestEnemy(unitID);
	target = document.getElementById("unit_" + targetID);

	if(targetID != 0)
	{

		destX = parseInt(attUnit.getAttribute("tileX"));
		destY = parseInt(attUnit.getAttribute("tileY"));
		if(target.getAttribute("tileX") < attUnit.getAttribute("tileX"))
		{
			destX--;
		}

		if(target.getAttribute("tileX") > attUnit.getAttribute("tileX"))
		{
			destX++;
		}	


		if(target.getAttribute("tileY") < attUnit.getAttribute("tileY"))
		{
			destY--;
		}

		if(target.getAttribute("tileY") > attUnit.getAttribute("tileY"))
		{
			destY++;
		}	

		if(ableToWalk(destX, destY) == 'Y')
		{
			moveUnit(unitID, destX, destY);
		}
		
		
	}
	
	return targetID;
}

function ableToWalk(x, y)
{
	tmpU = getUnitAt(x,y);
	if(tmpU != 0)
	{
		return "N";
	}
	
	return "Y";
}


function attackNearestEnemy(unitID)
{
	var tmpU = document.getElementById("unit_" + unitID);
	return attackNearestEnemyWithinRange(unitID, tmpU.getAttribute("range"))
	
}

function attackNearestEnemyWithinRange(unitID, range)
{
	var targetID = getNearestEnemyWithinRange(unitID, range);
	if(targetID != 0)
	{
		attack(unitID, targetID);
		return targetID;
	}
	
	return 0;	
}



function setWaitTime(unitID, t)
{
	var unit = document.getElementById("unit_" + unitID);
	unit.setAttribute("waitTime",t);
	
	//
	// Set the counter and move it over the unit
	//
	var counter = document.getElementById("unitWait_" + unitID);
	counter.innerHTML = t;
	counter.style.visibility = "visible"
	counter.style.top = (getTop(unit)) + "px" ;
	counter.style.left = (getLeft(unit) + 35) + "px";
	
	//
	// Set transparency for those units still waiting...
	//
	if(t > 0)
	{
		unit.style.opacity = .5;
		unit.style.filter = 'alpha(opacity=50)';
	}
	else
	{
		unit.style.opacity = 1;
		unit.style.filter = 'alpha(opacity=100)';
		counter.style.visibility = "hidden"
	}
}

function getPropertiesOfObject(obj) {
  var i, v;
  var count = 0;
  var props = [];
  if (typeof(obj) === 'object') {
    for (i in obj) {
      v = obj[i];
      if (v !== undefined && typeof(v) !== 'function' && typeof(v) !== 'CSSStyleDeclaration') {
        props[count] = i;
        count++;
      }
    }
  }
  return props;
};

/*****************************************************************************************

	Adding Units

*****************************************************************************************/

var newUnitIDs = "";

function addUnitFromStrings(unitFields, unitInfo)
{
	debug("Adding Unit: addUnitFromStrings()");
	var fields = unitFields.split(",");
	var data = unitInfo.split(",");

	addUnitFromArrays(fields, data);
}

function copyUnit(origUnit, newUnitID)
{
	//origUnit = document.getElementById("unit_" + originalUnitID);
	
	if(origUnit == null)
	{
		errorHandler("Error in copyUnit(" + originalUnitID + "," + newUnitID + "): Original Unit:" + originalUnitID + " does not exists");
		return;
	}

	returnUnit = new Object();
	
	var attribs = getPropertiesOfObject(origUnit);
	for (a=0; a<attribs.length; a++)
	{
		val = eval("origUnit." + attribs[a]);
		eval("returnUnit." + attribs[a] + "='" + val +"'");
		
	}
	
	returnUnit.unitID = newUnitID;
	
	return returnUnit;
}


function copyTileObject(origObj, newObjectID)
{	
	if(origObj == null)
	{
		errorHandler("Error in copyObject(): Original Object is null");
		return;
	}

	returnObj = new Object();
	
	var attribs = getPropertiesOfObject(origObj);
	for (a=0; a<attribs.length; a++)
	{
		val = eval("origObj." + attribs[a]);
		eval("returnObj." + attribs[a] + "='" + val +"'");
		
	}
	
	returnObj.objectID = newObjectID;
	
	return returnObj;
}


function addUnit(unit)
{
	if(unit == null)
	{
		errorHandler("Error at addUnit(): unitObj is null ");
		return;
	}
	
	if(unit.unitID <= 0)
	{
		errorHandler("Error at addUnit(): unitID is null or 0 ");
		return;
	}

	if(unit.x == null || unit.y == null)
	{
		errorHandler("Error at addUnit(): x or y is null ");
		return;
	}	
	
	t = document.getElementById("tile_" + unit.x + "_" + unit.y);
	
	newUnitIDs+=unit.unitID + ",";
	var newDiv = document.createElement("DIV");
	newDiv.style.position = "absolute";
	newDiv.style.top = (getTop(t) - 55) + "px";
	newDiv.style.left = getLeft(t) + "px";
	newDiv.style.zIndex=(getMapHeight() + 25 - unit.x );

	
	//alert((getTop(t) - 55) + "px" + "," + getLeft(t) + "px"); 
	newDiv.setAttribute("ID", "unit_" + unit.unitID);
	newDiv.setAttribute("tileX", unit.x);
	newDiv.setAttribute("tileY", unit.y);
	newDiv.setAttribute("finalX", unit.x);
	newDiv.setAttribute("finalY", unit.y);
	newDiv.setAttribute("nextX", unit.x);
	newDiv.setAttribute("nextY", unit.y);
	newDiv.setAttribute("currX", unit.x);
	newDiv.setAttribute("currY", unit.y);
	newDiv.setAttribute("destPointX", unit.x);
	newDiv.setAttribute("destPointY", unit.y);
	
	//put all fiels in the div tag as attributes
	//alert(getPropertiesOfObject(unit));
	var attribs = getPropertiesOfObject(unit);
	for (a=0; a<attribs.length; a++)
	{
		val = eval("unit." + attribs[a]);
		newDiv.setAttribute(attribs[a], val);
		//debug("Setting: " + attribs[a] + "=" + val);
		
	}


	html = "<img src='" + baseImageUrl + "" + unit.imageName + ".gif' ";
	html+= " border=0> ";
	newDiv.innerHTML = html;
	
	document.body.appendChild(newDiv);
	
	
	//
	// add wait div
	//
	var waitDiv = document.createElement("DIV");
	waitDiv.style.position = "absolute";
	waitDiv.style.top = (getTop(t) - 55) + "px";
	waitDiv.style.left = (getLeft(t)) + "px";
	waitDiv.style.width = "40px";
	waitDiv.style.height = "2px";
	waitDiv.style.color = "white";
	waitDiv.style.visibility = "hidden";
	waitDiv.style.zIndex=20;
	waitDiv.setAttribute("ID", "unitWait_" + unit["unitID"]);
	waitDiv.innerHTML = unit["waitTime"];
	
	document.body.appendChild(waitDiv);	
	
}

var newObjectIDs = "";
function addTileObject(obj)
{
	if(obj == null)
	{
		errorHandler("Error at addObject(): obj is null ");
		return;
	}


	if(obj.objectID == null || obj.objectID <= 0)
	{
		errorHandler("Error at addObject(): objectID is null or 0");
		return;
	}	
	
	if(obj.x == null || obj.y == null)
	{
		errorHandler("Error at addObject(): x or y is null ");
		return;
	}	
	
	t = document.getElementById("tile_" + obj.x + "_" + obj.y);
	newObjectIDs+=obj.objectID + ",";
	var newDiv = document.createElement("DIV");
	newDiv.style.position = "absolute";
	newDiv.style.top = (getTop(t) - 55) + "px";
	newDiv.style.left = getLeft(t) + "px";
	
	newDiv.style.zIndex= (getMapHeight() + 20 - obj.x);
	
	newDiv.setAttribute("ID", "obj_" + obj.objectID);
	newDiv.setAttribute("tileX", obj.x);
	newDiv.setAttribute("tileY", obj.y);
	
	//put all fiels in the div tag as attributes
	//alert(getPropertiesOfObject(obj));
	var attribs = getPropertiesOfObject(obj);
	for (a=0; a<attribs.length; a++)
	{
		val = eval("obj." + attribs[a]);
		newDiv.setAttribute(attribs[a], val);
		//debug("Setting: " + attribs[a] + "=" + val);
	}


	html = "<img src='" + baseFloorImageUrl + "" + obj.imageName + ".gif' ";
	html+= " border=0> ";
	newDiv.innerHTML = html;
	
	document.body.appendChild(newDiv);
	
}



function addUnitFromArrays(fields, data)
{
	debug("Adding Unit: addUnitFromArrays()");
	
	unit = new Array();
	for(k=0;k<fields.length;k++)
	{
		unit[fields[k]] = data[k];
		
	}
					
		
	newUnitIDs+=unit["unitID"] + ",";
	
	var newDiv = document.createElement("DIV");
	
	t = document.getElementById("tile_" + unit["x"] + "_" + unit["y"]);
	newDiv.style.position = "absolute";
	newDiv.style.top = (getTop(t) - 55) + "px";
	newDiv.style.left = getLeft(t) + "px";
	newDiv.style.zIndex=8;
	debug("Pos:" + newDiv.style.left + "," + newDiv.style.top);
	
	newDiv.setAttribute("ID", "unit_" + unit["unitID"]);
	newDiv.setAttribute("tileX", unit["x"]);
	newDiv.setAttribute("tileY", unit["y"]);
	newDiv.setAttribute("finalX", unit["x"]);
	newDiv.setAttribute("finalY", unit["y"]);
	newDiv.setAttribute("nextX", unit["x"]);
	newDiv.setAttribute("nextY", unit["y"]);
	newDiv.setAttribute("currX", unit["x"]);
	newDiv.setAttribute("currY", unit["y"]);
	newDiv.setAttribute("destPointX", unit["x"]);
	newDiv.setAttribute("destPointY", unit["y"]);
	
	//put all fiels in the div tag as attributes
	for(m=0;m<fields.length;m++)
	{
		if(fields[m] != "")
		{
			newDiv.setAttribute(fields[m], data[m]);
			//debug("Setting: " + fields[m] + "=" + data[m]);
		}
	}
	
	

	html = "<img src='" + baseImageUrl + "" + unit["imageName"] + ".gif' ";
	html+= " border=0> ";
	newDiv.innerHTML = html;
	
	document.body.appendChild(newDiv);
	
	
	//
	// add wait div
	//
	var waitDiv = document.createElement("DIV");
	waitDiv.style.position = "absolute";
	waitDiv.style.top = (getTop(t) - 55) + "px";
	waitDiv.style.left = getLeft(t) + "px";
	waitDiv.style.width = "40px";
	waitDiv.style.height = "2px";
	waitDiv.style.color = "white";
	waitDiv.style.visibility = "hidden";
	waitDiv.style.zIndex=20;
	waitDiv.setAttribute("ID", "unitWait_" + unit["unitID"]);
	waitDiv.innerHTML = unit["waitTime"];
	
	document.body.appendChild(waitDiv);
	//stop = true;
	
	
}

/*****************************************************************************************

	Unit Messaging - (Small popups for damage)

*****************************************************************************************/
var fadeUnitMsgCounter = 0;
var maxMovement = 15;
var fadeSpeed = 2;
var fadeOffsetTop = 10;
var fadeOffsetLeft = 25;
function showUnitMsg(unitID, msg)
{
	var d = document.getElementById("unitMsg");
	d.innerHTML = msg;
	
	var unit = document.getElementById("unit_" + unitID);
	d.style.top = (getTop(unit) - fadeOffsetTop) + "px";
	d.style.left = (getLeft(unit) + fadeOffsetLeft) + "px";
	d.style.visibility = "visible";
	//alert("Unit msg:" + unitID + " : " + msg);
	fadeUnitMsgCounter = 0;
	fadeUnitMsg();
}



function fadeUnitMsg()
{
	var d = document.getElementById("unitMsg");
	d.style.top = (getTop(d)-fadeSpeed) + "px";
	d.style.left = getLeft(d) + "px";
	fadeUnitMsgCounter++;
	
	if(fadeUnitMsgCounter < maxMovement)
	{
		setTimeout("fadeUnitMsg()",100);
	}	
	else
	{
		d.style.visibility = "hidden";	
	}
}




/*****************************************************************************************

	Animated Walk

	//
	// The following code moves a unit around the board
	// modify at your own risk
	//
*****************************************************************************************/
function moveUnit(selectedUnitID, x, y)
{
	
	startAnimateUnit(selectedUnitID, x, y);
}

var animateCount = 0;
function startAnimateUnit(unitID, x, y)
{
	var unit = document.getElementById("unit_" + unitID);
	
	if(unit != null)
	{
		if(unit.getAttribute('finalX') != x || unit.getAttribute('finalY') != y)
		{
			unit.setAttribute('finalX',x);
			unit.setAttribute('finalY',y);
			unit.setAttribute('nextX',unit.getAttribute('tileX'));
			unit.setAttribute('nextY',unit.getAttribute('tileY'));
			animateCount = 0;
			pickNextDest(unit);
		}
	}
	
}

function pickNextDest(objUnit)
{
	finalX = parseInt(objUnit.getAttribute('finalX'));
	finalY = parseInt(objUnit.getAttribute('finalY'));

	currX = parseInt(objUnit.getAttribute('nextX'));
	currY = parseInt(objUnit.getAttribute('nextY'));

	nextX = currX;
	nextY = currY;
	
	if((finalX != currX || finalY != currY) && animateCount < 50)
	{
		if(finalX != currX)
		{
			if(finalX > currX)
			{
				nextX = nextX + 1;
			}
			if(finalX < currX)
			{
				nextX = nextX - 1;
			}
		}
		else
		{
			if(finalY > currY)
			{
				nextY = nextY + 1;
			}
			if(finalY < currY)
			{
				nextY = nextY - 1;
			}
		}

		var tile = document.getElementById("tile_" + nextX + "_" + nextY);
		objUnit.setAttribute('nextX',nextX);
		objUnit.setAttribute('nextY',nextY);
		objUnit.setAttribute('currX',currX);
		objUnit.setAttribute('currY',currY);
		objUnit.setAttribute('destPointX',getLeft(tile));
		objUnit.setAttribute('destPointY',getTop(tile));
		//alert("set: " + nextX + "," + nextY);	
		animateUnit(objUnit.getAttribute("unitID"));
	}
	else
	{
		//alert("At Dest");

		var tile = document.getElementById("tile_" + finalX + "_" + finalY);
		objUnit.style.left = (getLeft(tile)) + "px";
		objUnit.style.top = (getTop(tile) - 55) + "px";
		objUnit.setAttribute('tileX',finalX);
		objUnit.setAttribute('tileY',finalY);
		objUnit.style.zIndex=(getMapHeight() + 25 - finalX);
		setWaitTime(objUnit.getAttribute("unitID"),objUnit.getAttribute("waitTime"));
		doneMoving(objUnit.getAttribute("unitID"));
	}
}


function animateUnit(unitID)
{
	//alert(unitID);
	animateCount++;
	
	var unit = document.getElementById("unit_" + unitID);
	
	nextX = parseInt(unit.getAttribute('nextX'));
	nextY = parseInt(unit.getAttribute('nextY'));
	
	currX = parseInt(unit.getAttribute('currX'));
	currY = parseInt(unit.getAttribute('currY'));
	//alert("move: " + currX + "," + currY + " to " + nextX + "," + nextY);
	
	left = getLeft(unit);
	top = getTop(unit);
	
	if(nextX == currX && nextY < currY)
	{
		//alert("here1");
		left+=4;
		top+=2;
	}

	if(nextX == currX && nextY > currY)
	{
		//alert("here2");
		left-=4;
		top-=2;
	}

	if(nextX < currX && nextY == currY)
	{
		//alert("here3");
		left-=4;
		top+=2;
	}

	if(nextX > currX && nextY == currY)
	{
		//alert("here4");
		left+=4;
		top-=2;
	}
	
	unit.style.top = top + "px";
	unit.style.left = left + "px";
	
	diffX = Math.abs(getLeft(unit) - unit.getAttribute('destPointX'));
	diffY = Math.abs(getTop(unit) - unit.getAttribute('destPointY'));
	
	//showDamage(unitID, Math.round(diffX/21) + "," + Math.round(diffY/45));
	
	//if(Math.round(diffX/21) <= 0 && Math.round(diffY/45) <= 1)
	if(Math.round((diffX+5)/21) <= 0 && Math.round(diffY/45) <= 1)
	{
		pickNextDest(unit);
	}
	else
	{
		setTimeout("animateUnit(" + unitID + ")",100);
	}

	
}

