global = new Array(2,10);
global['unit_selected'] = null;
global['squad_action'] = null;
global['squad_position'] = null;
global['squad_selected'] = null;
global['squad_origin'] = 0;

global['global_random'] = null;
global['global_id'] = null;
global['lasttd'] = null;
global['lastpureid'] = null;
global['lastid'] = null;
global['structure_type'] = null;
global['caching'] = 0;
global['g_dim'] = 8;

global['mapheight'] = 160;
global['mapwidth'] = 160;

// document.oncontextmenu=function(){return false}; 

var map = new Array(2400);
	for (i = 0; i < map.length; ++ i) map [i] = new Array(2400);
var squad = new Array(2400);
	for (i = 0; i < squad.length; ++ i) squad [i] = new Array(2400);
var road = new Array(2400);
	for (i = 0; i < road.length; ++ i) road [i] = new Array(2400);
var fortification = new Array(2400);
	for (i = 0; i < fortification.length; ++ i) fortification [i] = new Array(2400);
var colonytag = new Array(2400);
	for (i = 0; i < colonytag.length; ++ i) colonytag [i] = new Array(2400);
var ownership = new Array(2400);
	for (i = 0; i < ownership.length; ++ i) ownership [i] = new Array(2400);


// Getting $_GET

var $_GET = new Object();
var $qry_str = location.search.substring(1);
var $k = 0;

if($qry_str.indexOf("=") > 0)
{
	do {
	    $_GET[$qry_str.split("=")[0].replace(/&/, "")] = $qry_str.split("=")[1].split(/&|$/)[0];
	    $qry_str = $qry_str.split($qry_str.split("=")[1].split(/&|$/)[0])[1];
	    $k ++;
	} while($k < (location.search.split("=").length - 1));
}	


global['currentx'] = $_GET['xmin'];
global['currenty'] = $_GET['ymin'];


function setTile(where, what)
	{
		xajax_setTile(where, what);
	}
function setTile_cb(result)
	{
	}
function doselect(id)
	{
		global['squad_position'] = id;
		global['squad_origin'] = id;
		td = id + "_td";
		
		if(global['lasttd'] != null) 
			{ 
				deselect(global['lastid']);				
			}
		
		global['lastid'] = id; 
		global['lasttd'] = td;
	}
function squadAction(target)
	{		
		if(global['squad_action'] == 1)
			{
				moveSquad(target);
			}
		if(global['squad_action'] == 2)
			{
				attack(target);
			}
		if(global['squad_action'] == 15)
			{
				foundColony(target);
			}	
		if(global['squad_action'] == 14)
			{
				buildRoad(target);
			}	
	}
function setSquadAction(what, who)
	{
		if(what == "none")
			{
				global['squad_action'] = null;
				global['squad_selected'] = 0;
				for(c = 1; c <= 3;c++)
					{
						document.getElementById("action_" + c).src = "images/global/" + c + ".gif";
					}			
			}
		else
			{
				if(global['squad_action'] == what)
					{
						setSquadAction("none", 0);
					}
				else
					{
									global['squad_action'] = what;
									global['squad_selected'] = who;
									for(c = 1; c <= 3;c++)
										{
											document.getElementById("action_" + c).src = "images/global/" + c + ".gif";
										}
									document.getElementById("action_" + what).src = "images/global/" + what + "_down.gif";
					}
			}
	}
function moveSquad(to)
	{
		xajax_moveSquad(global['squad_selected'],to);
	}
function moveSquad_cb(success)
	{
		if(success.indexOf("Fail") >= 0 || success.indexOf("Waypoint Defined - Your troops will") >= 0)
			{
				notice(success);			
				setSquadAction("none", 0);
			}
		else if(success.indexOf("Waypoint Defined - Your troops were") >= 0)
			{
				success = success.split("%");
				global['global_random'] = success[2];

				clearTileUnit(success[1]);

				refreshTile(success[1]);
				refreshTile(success[2]);
								
				doselect(success[1]);
				notice(success[0], "_notice");			
				setSquadAction("none", 0);
			}
		else	
			{		
				success = success.split("%");
				global['global_random'] = success[2];
				
				clearTileUnit(success[1]);

				refreshTile(success[1]);				
				refreshTile(success[2]);
				
				global['squad_origin'] = null;	
				setSquadAction("none", 0);				
				doselect(success[1]);			
				notice(success[0], "_notice");			
			}
	}
function attack(target)
	{
		if(target != global['squad_position'])
			{
				target = target.replace(":", "x");
				window.location = "battle.php?attacker=" + global['squad_selected'] + "&defender=" + target;
			}	
	}
function buildRoad(where)	
	{
		global['global_random'] = where;
		xajax_buildRoad(where, global['squad_selected']);	
	}
function buildRoad_cb(success, connections, cachebit)
	{
		if(success == "success")
			{	
				addcache = global['global_random'].split(":");
				road[addcache[0]][addcache[1]] = cachebit;
				connection = connections.split("_");
				
				for(c=0; c < connection.length;c++)
					{
						if(document.getElementById(connection[c] + "_floater"))
							{
								clearTileRoad(connection[c]);		
							}	
						rtRoad(connection[c]);
					}
				
				notice("Road built.");

			}
		else
			{
				notice("We worked hard for hours but were unable to build a road.<br />Reason: " + success);
			}
		global['squad_action'] = null;
	}
function foundColony(to)
	{
		global['global_random'] = to;
		xajax_foundColony(to, global['squad_selected']);	
	}
function foundColony_cb(success)
	{
		if(success == "success")
			{
				refreshTile(global['global_random']);
				notice("Colony founded.");

			}
		else
			{
				notice("We were unable to found a colony.<br />Reason: " + success + "");
			}
		global['squad_action'] = null;
	}

<!---- REFRESH TILE ----->
function refreshTile(tile)
	{		
		rtBackground(tile);
		setTimeout("rtRoad('" + tile + "');",100);
		setTimeout("rtUnit('" + tile + "');",200);	
	}
function rtBackground(tile)
	{
		xajax_rtBackground(tile);
	}
function rtBackground_cb(value)
	{
		document.getElementById(global['global_random'] + "_td").style.backgroundImage = "url('" + value + "');";
	}
function rtUnit(tile)
	{
		xajax_rtUnit(tile);
	}
function rtUnit_cb(value, tile, name)
	{
		var loc = tile.split(":");
		squad[loc[0]][loc[1]] = name;
		document.getElementById(tile + "_td").innerHTML += value;
	}
function rtRoad(tile)
	{
		xajax_rtRoad(tile);
	}
function rtRoad_cb(value, tile, cachebit)
	{
		if(document.getElementById(tile + "_floater"))
			{
				clearTileRoad(tile);		
			}	
		document.getElementById(tile + "_td").innerHTML = value + document.getElementById(tile + "_td").innerHTML;	
		addcache = tile.split(":");
		road[addcache[0]][addcache[1]] = cachebit;
	}
function clearTile(tile)
	{
		newvar = "<img id='" + tile + "_marker' src='images/map/none.gif'>";
		document.getElementById(tile + "_td").innerHTML = newvar;
	}
function clearTileRoad(tile)
	{		
		ref = document.getElementById(tile + "_floater"); ref.parentNode.removeChild(ref);
	}
function clearTileUnit(tile)
	{		
		ref = document.getElementById(tile + "_squad"); ref.parentNode.removeChild(ref);
	}
	
<!---- REFRESH TILE ----->
function drawUnit(tile)
	{
		xajax_drawUnit(tile, global['squad_selected'], 'ajax');
	}
function drawUnit_cb(value)
	{
		document.getElementById(global['global_random'] + "_td").innerHTML = value + document.getElementById(global['global_random'] + "_td").innerHTML;
	}
	
function deselect(zone)
	{
		global['squad_selected'] = 0;	
		global['squad_action'] = null;	
	}
function dohover(zone)
	{
		var color = "666666";
		marker = document.getElementById(zone + "_marker");
		if(global['squad_action'] == 1 || global['squad_action'] == 2 || global['squad_action'] == 14|| global['squad_action'] == 15)
				{
					nloc = zone.split(":");
					var position = global['squad_position'];
					oloc = position.split(":");
					xmov = Math.abs(nloc[0] - oloc[0]);
					ymov = Math.abs(nloc[1] - oloc[1]);
					if(ymov <= 1 && xmov <= 1)
						{
							if(global['squad_action'] == 15) // build
								{
									color = "4ebd4c";
									marker.src = "images/map/marker_construct.png";
								}
							else if(global['squad_action'] == 14)  // attack
								{
									color = "fff000";						
									marker.src = "images/map/marker_road.png";
								}
							else if(global['squad_action'] == 2)  // attack
								{
									color = "fff000";						
									marker.src = "images/map/marker_attack.png";
								}
							else if(global['squad_action'] == 1)  // move
								{
									color = "ffba00";						
								}

						}	
					else
						{
							if(global['squad_action'] == 15) 
								{
									color = "cf4a4a";							
									marker.src = "images/map/toofar.png";
							
								}
							else if(global['squad_action'] == 14) 
								{
									color = "cf4a4a";								
									marker.src = "images/map/toofar.png";
					
								}
							else if(global['squad_action'] == 2) 
								{
									color = "cf4a4a";								
									marker.src = "images/map/toofar.png";
					
								}
							else if(global['squad_action'] == 1)  // move
								{
									color = "ffba00";						
								}
						}	

				}
			
		document.getElementById(zone + "_td").style.borderLeft = "1px #" + color + " solid";
		document.getElementById(zone + "_td").style.borderTop = "1px #" + color + " solid";
			
	}
function dehover(zone)
	{
		if(document.getElementById(zone + "_marker"))
			{
				document.getElementById(zone + "_marker").src = "images/map/none.gif";
			}
			
		comparison = document.getElementById(zone + "_td").style.borderLeft = "1px #252525 solid";
		comparison = document.getElementById(zone + "_td").style.borderTop = "1px #252525 solid";
	}
function buildMap(direction)
	{
		var requestx = parseInt(global['currentx']);
		var requesty = parseInt(global['currenty']);
		if((direction == "left" && requestx-1 > -1) || (direction == "up" && requesty-1 > -1) || direction == "right" || direction == "down")
			{
				var negativepreventionx = requestx - 6;
				if(negativepreventionx < 1) negativepreventionx = 1;
				var negativepreventiony = requesty-6;
				if(negativepreventiony < 1) negativepreventiony = 1;

				if((undefined == map[negativepreventionx][negativepreventiony] || undefined == map[requestx+6][negativepreventiony] || undefined == map[negativepreventionx][requesty+6] || undefined == map[requestx+6][requesty+6]) && global['caching'] == 0) { cacheMap(requestx, requesty) }

				if(direction == "right") 
					{ 
						requestx = parseInt(global['currentx']) + 1;
					}
				if(direction == "left") 
					{ 
						requestx = parseInt(global['currentx']) - 1;
					}
				if(direction == "up") 
					{ 
						requesty = parseInt(global['currenty']) - 1;
					}
				if(direction == "down") 
					{ 
						requesty = parseInt(global['currenty']) + 1;
					}
				constructFromCache(requestx,requesty); 
			}	
			
	}
function cacheMap(x, y)
	{
		if(global['caching'] == 1)
			{
				setTimeout("cacheMap('" + x + "', '" + y + "');",300);	
			}
		else	
			{
				global['caching'] = 1;
				console.log("Charting map...");
		
				xajax_cacheMap(x,y);
			}	
	}
function doExpandMap(x,y,type,units,roads,g_dim,fortifications,colonytags,ownerships)
	{
		global['g_dim'] = g_dim;
		var cached = 1;
		for(c=0; c<=type.length; c++)
			{			
				if(x[c]!=null && y[c]!=null && type[c]!=null) 
					{ 
						map[x[c]][y[c]] = type[c]; 
						squad[x[c]][y[c]] = units[c];						
						road[x[c]][y[c]] = roads[c];	
						fortification[x[c]][y[c]] = fortifications[c];	
						colonytag[x[c]][y[c]] = colonytags[c];
						ownership[x[c]][y[c]] = ownerships[c];
					}
			}
		global['caching'] = 0;	
		if(document.getElementById('maploading').style.visibility != "hidden") document.getElementById('maploading').style.visibility = "hidden";
	}
function getNextValue(value, direction, increment)
	{		
		newvalue = parseInt(value) + (parseInt(direction) * parseInt(increment));
		return newvalue;
	}
	
function constructFromCache(x,y)
	{
		console.log("constructFromCache()..." + x + ":" + y);
		
		c = parseInt(global['currentx']);
		d = parseInt(global['currenty']);
		
		g_dim = global['g_dim'] - 1;
		
		offsetx = 0;
		offsety = 0;
		
		operatorx = 1;
		operatory = 1;
				
		if(x > c) { global['currentx']++; offsetx = g_dim; operatorx = 0 - 1; c += g_dim; x += g_dim;}
		if(y > d) { global['currenty']++; offsety = g_dim; operatory = 0 - 1; d += g_dim; y += g_dim;}
		
		if(x < c) { global['currentx']--; operatorx = 1;}
		if(y < d) { global['currenty']--; operatory = 1;}		
		
		if(x == c) stallx = 1; else stallx = 0;
		if(y == d) stally = 1; else stally = 0;

		original_x = x; 
		original_y = y;

		// Changing ID's and Border numbers X
		i = c;			
		while(i<=(c+g_dim) && i >= (c-g_dim) && stallx != 1)
			{
				document.getElementById('1_x' + i).innerHTML = x;
				document.getElementById('1_x' + i).id = '1_x' + x;	
				document.getElementById('2_x' + i).innerHTML = x;
				document.getElementById('2_x' + i).id = '2_x' + x;	

				x = getNextValue(x,operatorx,1);					
				i = getNextValue(i,operatorx,1);
			}

		// Changing ID's and Border numbers Y		
		j = d;
		while(j<=(d+g_dim) && j >= (d-g_dim) && stally != 1)
			{
				document.getElementById('1_y' + j).innerHTML = y;
				document.getElementById('1_y' + j).id = '1_y' + y;	
				document.getElementById('2_y' + j).innerHTML = y;
				document.getElementById('2_y' + j).id = '2_y' + y;	

				y = getNextValue(y,operatory,1);					
				j = getNextValue(j,operatory,1);
			}			
			

		// Tile refreshes
		x = original_x;
		y = original_y;
					
		j = d;
		while(j<=(d+g_dim) && j >= (d-g_dim))
				{
					x = original_x;
					i = c;					
					while(i<=(c+g_dim) && i >= (c-g_dim))
						{
							var old_id = i + ":" + j;
							var new_id = x + ":" + y;
							if(!map[x][y]) 
								{
									if(y == (global['mapheight'] + 1)) map[x][y] = "edge_bottom";
									else if(x == (global['mapwidth'] + 1)) map[x][y] = "edge_right";
									else if(y == 0) map[x][y] = "edge_top";
									else if(x == 0) map[x][y] = "edge_left";
									else map[x][y] = "nomap";
								}	
							
							if(map[x][y].indexOf("_11") > 0) { thismap = map[x][y].substr(0,(map[x][y].length - 3)); document.getElementById(old_id + "_td").style.backgroundPosition = "0px 0px"; }
							else if(map[x][y].indexOf("_12") > 0) { thismap = map[x][y].substr(0,(map[x][y].length - 3)); document.getElementById(old_id + "_td").style.backgroundPosition = "0px -48px"; }
							else if(map[x][y].indexOf("_21") > 0) { thismap = map[x][y].substr(0,(map[x][y].length - 3)); document.getElementById(old_id + "_td").style.backgroundPosition = "-48px 0px"; }
							else if(map[x][y].indexOf("_22") > 0) { thismap = map[x][y].substr(0,(map[x][y].length - 3)); document.getElementById(old_id + "_td").style.backgroundPosition = "-48px -48px"; }
							else { thismap = map[x][y]; document.getElementById(old_id + "_td").style.backgroundPosition = "0px 0px"; }
							if(document.getElementById(old_id + "_floater_ownership")) 
								{ 
									ref = document.getElementById(old_id + "_floater_ownership"); ref.parentNode.removeChild(ref);
								}								

							if(document.getElementById(old_id + "_colonytag")) 
								{ 
									ref = document.getElementById(old_id + "_colonytag"); ref.parentNode.removeChild(ref);
									document.getElementById(old_id + "_td").attributes["onmouseover"].value = "";
									document.getElementById(old_id + "_td").attributes["onmouseout"].value = "";
								}								
							document.getElementById(old_id + "_td").style.backgroundImage = "url('./images/map/" + thismap + ".gif')";
							document.getElementById(old_id + "_td").attributes["onclick"].value = 'squadAction("' + new_id + '"); doselect("' + new_id + '"); xajax_getLayout("dyn_mapinfo", "' + new_id + '", "mapinfo");';
							document.getElementById(old_id + "_td").id = new_id + "_td";			
							document.getElementById(old_id + "_marker").id = new_id + "_marker";			

							if(document.getElementById(old_id + "_squad")) 
								{ 
									ref = document.getElementById(old_id + "_squad"); ref.parentNode.removeChild(ref); 
								}
							if(document.getElementById(old_id + "_floater")) 
								{ 
									ref = document.getElementById(old_id + "_floater"); ref.parentNode.removeChild(ref);
								}
							if(document.getElementById(old_id + "_floater_fortification")) 
								{ 
									ref = document.getElementById(old_id + "_floater_fortification"); ref.parentNode.removeChild(ref);
								}
							if(road[x][y]) 
								{									
									document.getElementById(new_id + "_td").innerHTML = "<img id='" + new_id + "_floater' style='position:absolute; z-index:0;' src='images/map/road/" + road[x][y] + "'>" + document.getElementById(new_id + "_td").innerHTML;		
								}
							if(fortification[x][y]) 
								{									
									document.getElementById(new_id + "_td").innerHTML = "<img id='" + new_id + "_floater_fortification' style='position:absolute; z-index:1;' src='images/map/" + fortification[x][y] + ".png'>" + document.getElementById(new_id + "_td").innerHTML;		
								}
							if(squad[x][y]) 
								{									
									document.getElementById(new_id + "_td").innerHTML += "<img id='" + new_id + "_squad' class='tileoverlay' src='images/units/" + squad[x][y] + "_iso.png'>";								
								}
							if(colonytag[x][y]) 
								{									
									document.getElementById(new_id + "_td").innerHTML += colonytag[x][y];
									document.getElementById(new_id + "_td").attributes["onmouseover"].value += " document.getElementById('" + new_id + "_colonytag').style.display = 'block'";			
									document.getElementById(new_id + "_td").attributes["onmouseout"].value += " document.getElementById('" + new_id + "_colonytag').style.display = 'none'";			
								}
							if(ownership[x][y]) 
								{	
									color = "2px #" + ownership[x][y] + " dashed";

									document.getElementById(new_id + "_td").innerHTML += "<div id='" + new_id + "_floater_ownership' class='tileoverlay' style='height:48px; width:48px; margin-top:-48px; margin-left:0px; border: none;'></div>";								
																							
									if(!ownership[x-1][y]) { document.getElementById(new_id + "_floater_ownership").style.borderLeft = color; } else { document.getElementById(new_id + "_floater_ownership").style.borderLeft = ''; }
									if(!ownership[x+1][y]) { document.getElementById(new_id + "_floater_ownership").style.borderRight = color; } else { document.getElementById(new_id + "_floater_ownership").style.borderRight = ''; }
									if(!ownership[x][y-1]) { document.getElementById(new_id + "_floater_ownership").style.borderTop = color; } else { document.getElementById(new_id + "_floater_ownership").style.borderTop = ''; }
									if(!ownership[x][y+1]) { document.getElementById(new_id + "_floater_ownership").style.borderBottom = color; } else { document.getElementById(new_id + "_floater_ownership").style.borderBottom = ''; }								
									
								}						
							x = getNextValue(x,operatorx,1);					
							i = getNextValue(i,operatorx,1);
						}	
					y = getNextValue(y,operatory,1);					
					j = getNextValue(j,operatory,1);
				}	
	}
function getCoords()
	{
		return global['currentx'] + ":" + global['currenty'];		
	}
function waypointAdd()
	{
		xajax_waypointAdd(global['currentx'],global['currenty'],global['squad_selected'], null, 'ajax');
	}
function waypointRemove(waypoint)
	{
		xajax_waypointRemove(waypoint,'ajax');
	}
function waypointSetPatrol(waypoint)
	{
		xajax_waypointSetPatrol(waypoint,'ajax');
	}