{$EVENT evtTick:OnTickCusLoc}
{$EVENT evtBeacon:OnBeaconCusLoc}
{$EVENT evtHouseBuilt:OnHouseBuiltCusLoc}
{$EVENT evtHouseAfterDestroyed:OnHouseAfterDestroyedCusLoc}

type 
	KD_CustomLocation = record
		StoreBuilded, LocationSelected : Boolean;
		Pos : TKMPoint;
		LocationPoses : array of TKMPoint;
		TimeToSelect, Radius : Integer;
	end;
	
var gCustomLocation : KD_CustomLocation;

procedure OnHouseBuiltCusLoc(aHouse : Integer);
var HH : KD_HouseStats;
begin
	If gCustomLocation.StoreBuilded then 
		Exit;
		
	If S.HouseOwner(aHouse) <> 0 then 
		Exit;
		
	HH := SetHouse(aHouse, false);
	If HH.aType <> 11 then 
		Exit;
	A.HouseAddWaresTo(aHouse, 1, 60 + S.KaMRandomI(10));
	A.HouseAddWaresTo(aHouse, 2, 40 + S.KaMRandomI(10));
	A.HouseAddWaresTo(aHouse, 8, 90 + S.KaMRandomI(10));
	A.HouseAddWaresTo(aHouse, 7, 60 + S.KaMRandomI(10));
	A.HouseAddWaresTo(aHouse, 10, 60 + S.KaMRandomI(10));
	A.HouseAddWaresTo(aHouse, 13, 20 + S.KaMRandomI(10));
	A.HouseAddWaresTo(aHouse, 27, 30 + S.KaMRandomI(10));
	gCustomLocation.StoreBuilded := true;
end;

procedure OnHouseAfterDestroyedCusLoc(aHType, aOwner,aX,aY : Integer);
begin
	If gCustomLocation.StoreBuilded then 
		Exit;
		
	If aOwner = PLAYER then
		If aHType = 11 then 
			A.GiveHouseSite(PLAYER, 11, aX,aY, true);
end;

function PointInLocationPoses(aX,aY : Integer) : Boolean;
var I : Integer;
begin		
	Result := false;
	with gCustomLocation do 
		for I := 0 to high(LocationPoses) do 
			If PointNearPoint(LocationPoses[I], U.KMPoint(aX, aY), Radius) then 
				If S.FogRevealed(PLAYER, aX, aY) then
					Result := true;
		
end;

procedure SelectLocation(aX, aY : Integer);
begin
	If A.GiveHouseSite(PLAYER, 11, aX,aY, true) < 0 then 
		A.ShowMSG(PLAYER, 'GAME : Cannot place a storehouse site!')
	else			
	with gCustomLocation do 
	begin
		Pos := U.KMPoint(aX,aY);
		LocationSelected := true;
		A.GiveRoad(PLAYER, aX ,aY + 1);
		A.ShowMSG(PLAYER, 'GAME : Location selected.');
		
		If GT >= aTimeToReset then 
			A.OverlayTextSet(PLAYER, '');
	end;
end;

procedure OnBeaconCusLoc(aPlayer,aX,aY : Integer);
begin
	If gCustomLocation.LocationSelected then 
		Exit;
		
	If aPlayer <> PLAYER then 
		Exit;
	If length(gCustomLocation.LocationPoses) > 0 then 
	begin
		If PointInLocationPoses(aX, aY) then 
			SelectLocation(aX,aY)
		else
			A.ShowMSG(PLAYER, 'GAME : Cannot select location here!');
			
	end else
	If S.FogRevealed(PLAYER, aX,aY) then 
		SelectLocation(aX, aY)
	else
		A.ShowMSG(PLAYER, 'GAME : Cannot select location here!');
	
end;
procedure ShowTimer;
begin
	If GT >= gCustomLocation.TimeToSelect then 
		A.PlayerDefeat(0)
	else
		A.OverlayTextSet(PLAYER, '<$2> ' + U.TimeToString(gCustomLocation.TimeToSelect - GT) );
		
end;

procedure OnTickCusLoc;
begin
	If not gCustomLocation.LocationSelected then 
		If GT >= aTimeToReset then 
			ShowTimer;
end;