Script.Load( "Data\\Script\\MapTools\\Main.lua" )

------------------------------------------------------------------------------
function InitDiplomacy()
    -- diplomacy
    SetHostile(1,2)
    SetHostile(8,2)
	end
------------------------------------------------------------------------------
function InitResources()
    -- set some resources
    AddStone(0)
    AddClay(0)
    AddGold(0)
    AddSulfur(0)
    AddIron(0)
    AddWood(0)
    end
------------------------------------------------------------------------------
function InitTechnologies()
    end
------------------------------------------------------------------------------
function InitWeatherGfxSets()
	SetupMoorWeatherGfxSet()
    end
------------------------------------------------------------------------------
function InitWeather()
	AddPeriodicWinter(1200)
	AddPeriodicSummer(240)
	AddPeriodicWinter(60)
	
	StartWinter(10000000)
end
------------------------------------------------------------------------------
function InitPlayerColorMapping()

	Display.SetPlayerColorMapping(1,PLAYER_COLOR)
	Display.SetPlayerColorMapping(2,NEPHILIM_COLOR)
	Display.SetPlayerColorMapping(4,NEPHILIM_COLOR)
	Display.SetPlayerColorMapping(5,FRIENDLY_COLOR1)
	Display.SetPlayerColorMapping(8,FRIENDLY_COLOR1)
	Display.SetPlayerColorMapping(3,NPC_COLOR)
		
end

------------------------------------------------------------------------------
function FirstMapAction()
	
	Script.Load(Folders.Map.."s5CommunityLib/packer/devLoad.lua")
	mcbPacker.Paths = {{Folders.Map,".lua"}}
	mcbPacker.require("s5CommunityLib/lib/UnlimitedArmyRecruiter")
	mcbPacker.require("s5CommunityLib/lib/UnlimitedArmySpawnGenerator")
	-- load scripts
	mcbPacker.require("army_bridges")
	mcbPacker.require("army_DestroyHQ")
	mcbPacker.require("army_nephilimsHQ")
	mcbPacker.require("army_p8Defense")
	mcbPacker.require("army_player")
	mcbPacker.require("army_tribalCamps")
	
	mcbPacker.require("BombriderConverter")

	mcbPacker.require("briefing_bridges")
	mcbPacker.require("briefing_cleanUpRuins")
	mcbPacker.require("briefing_prelude")

	mcbPacker.require("gameControl")

	mcbPacker.require("npc_gate1")
	mcbPacker.require("npc_gate2")
	mcbPacker.require("npc_hq1")
	mcbPacker.require("npc_hq2")
	mcbPacker.require("npc_hq3")

	mcbPacker.require("player_2")
	mcbPacker.require("player_8")

	mcbPacker.require("quest_bridges")
	mcbPacker.require("quest_cleanUpRuins")
	mcbPacker.require("quest_defeat")
	mcbPacker.require("quest_gatekey1")
	mcbPacker.require("quest_gatekey2")
	
	mcbPacker.require("Towerlimit")
	mcbPacker.require("PoisenReiter")
	mcbPacker.require("TradeBalancer")
	
	mcbPacker.require("PoisenTraps")
	
	reloadTextFunc = function()
		IncludeLocals("BriefingTable")
	end
	
	reloadDestroyBuildingBottonWidgetID = function()
		gvGUI_WidgetID.DestroyBuildingButton = XGUIEng.GetWidgetID("DestroyBuildingButton")
	end
	
	AddMapStartAndSaveLoadedCallback(reloadTextFunc)
	AddMapStartAndSaveLoadedCallback(reloadDestroyBuildingBottonWidgetID)
	
	TriggerFix.AllScriptsLoaded()
	
	TradeBlancerInit()
	ActivateTowerLimit(16)
	UACounter = 0
	UAMaxCounter = 17 + 8 + 2 --(3 + 3 + 5 + 5 + 2 + 5 + 3)
	
	OverrideGUI()
	
	StartSimpleJob("Bombers")
	bombriders = {}
	bobmersHP = {}
	
	Trigger.RequestTrigger(Events.LOGIC_EVENT_ENTITY_HURT_ENTITY,nil,"CustomHPCalc",1,nil,nil)
	Trigger.RequestTrigger(Events.LOGIC_EVENT_EVERY_SECOND,nil,"CustomHPReg",1,nil,nil)
	
	Trigger.RequestTrigger(Events.LOGIC_EVENT_ENTITY_DESTROYED,nil,"bombriderDestroied",1,nil,nil)
	
	Trigger.RequestTrigger(Events.LOGIC_EVENT_ENTITY_CREATED, nil,"AntiBug", 1,nil,nil)
	
	MakeInvulnerable("NPC_HighlandCounseler")
	BishipID = GetID("NPC_HighlandCounseler")
	Trigger.RequestTrigger(Events.LOGIC_EVENT_ENTITY_HURT_ENTITY,nil,"AntiBishopCrash",1,nil,nil)
	--Init String tables
	String.Init("CM02_08_UnexploredLand")
	
	CreateBombMonch()
	
	FixStadtwache()
	
    -- debugging stuff

    --EnableDebugging()
    
   
	-- String
	String.Init("CM02_08_UnexploredLand")
	
	Cutscenes 							= {}
	Cutscenes[INTROCUTSCENE] 			= "INTRO"	
	Cutscenes[THRESHOLDONECUTSCENE] 	= "ATTACKSOLDIER"
	Cutscenes[MISSIONCOMPLETECUTSCENE] 	= "MISSIONCOMPLETE"

				
	IncludeLocals("Cutscene_" .. Cutscenes[INTROCUTSCENE])
	IncludeLocals("Cutscene_" .. Cutscenes[THRESHOLDONECUTSCENE])
	IncludeLocals("Cutscene_" .. Cutscenes[MISSIONCOMPLETECUTSCENE])

    
    LocalMusic.UseSet = DARKMOORMUSIC
	
	function
	LocalMusic.CallbackSettlerKilled(_HurterPlayerID, _HurtPlayerID)
	
	local PlayerID = GUI.GetPlayerID()
	
	if _HurterPlayerID ~= _HurtPlayerID and PlayerID == _HurtPlayerID  then		
			if LocalMusic.LastBattleMusicStarted < Logic.GetTime() then					
				if Logic.IsEntityInCategory(_HurterPlayerID,EntityCategories.EvilLeader) == 1 then
					LocalMusic.BattlesOnTheMap = 2
				else
					LocalMusic.BattlesOnTheMap = 1
				end
				LocalMusic.LastBattleMusicStarted = Logic.GetTime() + 127
				LocalMusic.SongLength = 0
			end
		end
	end
	
	StartSpeech = function(_key)

		if _key ~= nil then

			local tablePos = string.find(_key, "/")
			if tablePos ~= nil then
				Stream.Start("Voice\\"..string.sub(_key, 1, tablePos-1).."\\"..string.sub(_key, tablePos + 1, -1)..".mp3", 150)
			else
				if BriefingsVoices[_key][2] then
					Stream.Start(Folders.Map.."voices/"..BriefingsVoices[_key][1]..".mp3", BriefingsVoices[_key][2])
				else
					Stream.Start("Voice\\CM02_03_BigCity\\"..BriefingsVoices[_key][1]..".mp3", 150)
				end
			end
		end

	end

	-- start
	StartCutscene(Cutscenes[INTROCUTSCENE],start1stChapter)

	end
	
function AntiBug()
	local entityID = Event.GetEntityID()
	if Logic.GetEntityType(entityID) == Entities.XD_Bomb1 then
		if IsValid("destRock") and GetDistance("Pilgrim","destRock") <= 500 then
			ReplaceEntity("destRock",Entities.XD_RockDestroyableMedium1)
			Logic.SetEntityInvulnerabilityFlag(GetID("player2"), 0)
		end
	end
	if Logic.GetEntityType(entityID) == Entities.XD_Keg1 then
		local kegpos = GetPosition(entityID)
		local thiefs,_ = Logic.GetEntitiesInArea(Entities.PU_Thief, kegpos.X, kegpos.Y, 200, 1)
		if thiefs <= 0 then
			Logic.DestroyEntity(entityID)
		end
	end
	return false
end

function AntiBishopCrash()
	local _entID = Event.GetEntityID2()
	if _entID == BishipID then
		StartSimpleHiResJob("KillBiship")
		return true
	end
	return false
end

function KillBiship()
	Logic.DestroyEntity(BishipID)
end

function bombriderDestroied()
	local _entID = Event.GetEntityID()
	if bombriders[_entID] then
		bombriders[_entID] = nil
	end
	return false
end

function Bombers()
	for _id,_time in pairs(bombriders) do 
		if _time < 40 then
			bombriders[_id] = _time + 1
		end
	end
	return false
end

function CustomHPCalc()
	if not bombriders[Event.GetEntityID2()] then
		return false
	end
	local reiterID = Event.GetEntityID2()
	if Logic.IsEntityAlive(reiterID) then
		local attackerID = Event.GetEntityID1()
		local dmg = Logic.GetEntityDamage(attackerID) - 12 -- 12 ist Ruestungsvalue
		if dmg < 0 then
			dmg = 0
		end
		bobmersHP[reiterID] = bobmersHP[reiterID] - dmg
		MakeVulnerable(reiterID)
		SetHealth(reiterID,math.floor(((bobmersHP[reiterID]/500)*100)+0.5))
		MakeInvulnerable(reiterID)
		return false
	end
	return false
end

function CustomHPReg()
	for key,_ in pairs(bombriders) do
	if Logic.IsEntityAlive(key) then
		if Counter.Tick2("MiraiReg",2) then
			bobmersHP[key] = math.min(bobmersHP[key] + 8,500)
			SetHealth(key,math.floor(((bobmersHP[key]/500)*100)+0.5))
		end
	end
	end
end

function OverrideGUI()
	function GUITooltip_TroopOffer(_SlotIndex)
		local LeaderType, Amount = Logic.GetMercenaryOffer(SelectedTroopMerchantID,_SlotIndex, InterfaceGlobals.CostTable)
		local TooltipText = "@color:180,180,180,255 "	
		local ShortCutToolTip = " "
		local CostString = InterfaceTool_CreateCostString( InterfaceGlobals.CostTable )
		local EntityTypeName = Logic.GetEntityTypeName( LeaderType )
		if EntityTypeName == nil then
			return
		end
		local NameString = "names/" .. EntityTypeName
		--if XGUIEng.GetStringTableText(NameString) and _SlotIndex ~= 2 then
			TooltipText = TooltipText .. " " .. XGUIEng.GetStringTableText(NameString) .. " @cr "
		--else
		--	TooltipText = TooltipText.." Bombenreiter @cr "
		--end
		TooltipText = TooltipText .. "@color:255,255,255,255 Erwerbt eine Truppe dieser Einheitenart."
		XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomCosts, CostString)
		XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomText,TooltipText)
		XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomShortCut, ShortCutToolTip)
	end
	function GUIAction_BuyMerchantOffer(_index)
		local tableDI;
		local PlayerID = GUI.GetPlayerID()
		if Logic.GetPlayerAttractionUsage( PlayerID ) >= Logic.GetPlayerAttractionLimit( PlayerID ) then
			GUI.SendPopulationLimitReachedFeedbackEvent(PlayerID)
			return
		end	
		Logic.GetMercenaryOffer(SelectedTroopMerchantID,_index, InterfaceGlobals.CostTable)
		if InterfaceTool_HasPlayerEnoughResources_Feedback( InterfaceGlobals.CostTable ) == 1 then	
			-- Yes
			if not bombrideroffers[SelectedTroopMerchantID] or _index ~= 2 then
				GUI.BuyMerchantOffer(SelectedTroopMerchantID, PlayerID, _index)
			else
					if bombrideroffers[GetID("CannonMerchant")] > 0 then
						tableID = CreateEntity(1,Entities.PU_LeaderHeavyCavalry2,GetPosition("bombers"), nil)
						Logic.SetSpeedFactor(tableID, 1.5)
						Logic.SetEntityInvulnerabilityFlag(tableID, 1)
						bombriders[tableID] = 40
						bobmersHP[tableID] = 500
						bombrideroffers[SelectedTroopMerchantID] = bombrideroffers[SelectedTroopMerchantID] - 1
					end
			end
			GUIUpdate_TroopOffer(_index)
		end
	end
	
	function GameCallback_GUI_SelectionChanged()

		-- Hide selection widgets
		XGUIEng.ShowAllSubWidgets(gvGUI_WidgetID.SelectionView,0)	
	
		--Hide all BG Textures
		XGUIEng.ShowAllSubWidgets(gvGUI_WidgetID.BackgroundContainer,0)	
		XGUIEng.ShowWidget(gvGUI_WidgetID.BackgroundLeft,1)
		
		-- Stop video playback
		XGUIEng.StopVideoPlayback( gvGUI_WidgetID.VideoPreview )	
		XGUIEng.ShowWidget(gvGUI_WidgetID.VideoPreview,0)
	
		-- disable following
		if gvCamera.DefaultFlag ~= 0 then	    
			Camera.FollowEntity(0)		
		end

	--	
		if gvGUI.HawkIsFlying == 1 then
			GUIAction_GoBackFromHawkViewInNormalView()
		end
		
		-- Get selected entity
		local EntityId = GUI.GetSelectedEntity()

		GUI_Selection = { GUI.GetSelectedEntities() }
	
		if table.getn(GUI_Selection) > 1 then
			XGUIEng.ShowWidget(gvGUI_WidgetID.MultiSelectionContainer,1)
			GUIAction_UpdateMultiSelectionContainer()
		end
		if GUI_Selection == nil or table.getn(GUI_Selection) <= 1 then
			XGUIEng.ShowWidget(gvGUI_WidgetID.MultiSelectionContainer,0)		
		end
	
		--	
		if EntityId == nil then
			gvGUI.LastSelectedEntityID = 0
			return
		end
	
		-- Get entity type
		local EntityType = Logic.GetEntityType( EntityId )
		local EntityTypeName = Logic.GetEntityTypeName( EntityType )
	
		--Init Sounds
		local SelectionSound = Sounds.Selection_global
		local FunnyComment = 0
		local RandomSelectionSound = XGUIEng.GetRandom(4)

		-- Confirm	
		XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionGeneric,1)	
		XGUIEng.ShowWidget(gvGUI_WidgetID.BackgroundFull,1)
	
	
		-- Start video and show full GUI
		if EntityType ~= 0 then
			XGUIEng.ShowWidget(gvGUI_WidgetID.VideoPreview,1)		
			local VideoName = "data\\graphics\\videos\\" .. EntityTypeName .. ".bik"
			XGUIEng.StartVideoPlayback( gvGUI_WidgetID.VideoPreview, VideoName, 1 )			
		end
	
		-- Is selected entity a serf?
		if Logic.IsSerf( EntityId ) == 1 then		

			FunnyComment = Sounds.VoicesSerf_SERF_FunnyComment_rnd_01
			
			local OnlySerfsSelected = 1
			
			local i 
			for i=1, 20, 1 do
				local SerfEntityType = Logic.GetEntityType( GUI_Selection[i] )
				if GUI_Selection [i] == nil then
					break
				elseif SerfEntityType ~= Entities.PU_Serf then
					OnlySerfsSelected = 0
					break
				end
			end
			
			XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionSerf,OnlySerfsSelected)						
			XGUIEng.UnHighLightGroup(gvGUI_WidgetID.InGame, "BuildingGroup")
			
			--Set contrsuction menu as default and highlight the tab
			XGUIEng.ShowAllSubWidgets(gvGUI_WidgetID.SerfMenus,0)	
			XGUIEng.ShowWidget(gvGUI_WidgetID.SerfConstructionMenu,1)
			XGUIEng.UnHighLightGroup(gvGUI_WidgetID.InGame, "BuildingMenuGroup")
			XGUIEng.HighLightButton(gvGUI_WidgetID.ToSerfBeatificationMenu,1)
		
		-- Is selected entity a worker?
		elseif Logic.IsWorker( EntityId ) == 1 then
		
		
			SelectionSound = 0
			FunnyComment = Sounds.VoicesWorker_WORKER_FunnyComment_rnd_01
		
		
			XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionWorker,1)	
			Camera.FollowEntity(EntityId)		
		
			
		-- Is selected entity a leader?
		elseif Logic.IsLeader( EntityId ) == 1 then	
		
		
			--this can be done better: AnSu		
			XGUIEng.DisableButton(gvGUI_WidgetID.ExpelSettler,0)
		
			--Hide all militray unit widgets
			XGUIEng.ShowAllSubWidgets(gvGUI_WidgetID.SelectionMilitaryUnit,0)	
		
			--Display Military Unit container
			XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionMilitaryUnit,1)		
			XGUIEng.ShowWidget(gvGUI_WidgetID.CommandsGeneric,1)
		
			if Logic.IsEntityInCategory(EntityId,EntityCategories.Military) == 1
			and Logic.IsEntityInCategory(EntityId,EntityCategories.Cannon) == 0 
			and Logic.IsEntityInCategory(EntityId,EntityCategories.CavalryHeavy) == 0 
			and Logic.IsEntityInCategory(EntityId,EntityCategories.CavalryLight) == 0 
			and Logic.IsHero(EntityId) == 0 then
				XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionLeader,1)
			end
		
			if EntityType == Entities.PU_BattleSerf  then
				XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionBattleSerf ,1)	
				XGUIEng.ShowWidget(gvGUI_WidgetID.CommandsGeneric,0)
				XGUIEng.ShowWidget("Commands_Leader",0)
				--gvGUI.FunnyComment = Sounds.VoicesWorker_LEADER_FunnyComment_rnd_04	
			end
			
			--Scout and Thief
			if EntityType == Entities.PU_Scout then
				XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionScout,1)
				XGUIEng.ShowWidget(gvGUI_WidgetID.CommandsGeneric,1)			
				XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionLeader,0)
				FunnyComment = Sounds.AOVoicesScout_Scout_FunnyComment_rnd_01		
			end
		
			if EntityType == Entities.PU_Thief then
				XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionThief,1)
				XGUIEng.ShowWidget(gvGUI_WidgetID.CommandsGeneric,1)			
				XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionLeader,0)
				FunnyComment = Sounds.AOVoicesThief_Thief_FunnyComment_rnd_01			
			end
		
		
			if GUI_Selection[2] == nil then
			
				if Logic.IsHero(EntityId) == 1 then
	
					if Logic.IsEntityInCategory(EntityId,EntityCategories.Hero1) == 1 then

						FunnyComment = Sounds.VoicesHero1_HERO1_FunnyComment_rnd_01						
				
					elseif Logic.IsEntityInCategory(EntityId,EntityCategories.Hero2) == 1 then

						FunnyComment = Sounds.VoicesHero2_HERO2_FunnyComment_rnd_01
									
					elseif Logic.IsEntityInCategory(EntityId,EntityCategories.Hero3) == 1 then

						FunnyComment = Sounds.VoicesHero3_HERO3_FunnyComment_rnd_01
					
					elseif Logic.IsEntityInCategory(EntityId,EntityCategories.Hero4) == 1 then

						FunnyComment = Sounds.VoicesHero4_HERO4_FunnyComment_rnd_01
									
					elseif Logic.IsEntityInCategory(EntityId,EntityCategories.Hero5) == 1 then

						FunnyComment = Sounds.VoicesHero5_HERO5_FunnyComment_rnd_01
				
					elseif Logic.IsEntityInCategory(EntityId,EntityCategories.Hero6) == 1 then

						FunnyComment = Sounds.VoicesHero6_HERO6_FunnyComment_rnd_01
					
					elseif EntityType == Entities.CU_BlackKnight then

						FunnyComment = Sounds.VoicesHero7_HERO7_FunnyComment_rnd_01
					
					elseif EntityType == Entities.CU_Mary_de_Mortfichet then

						FunnyComment = Sounds.VoicesHero8_HERO8_FunnyComment_rnd_01	
				
					elseif EntityType == Entities.CU_Barbarian_Hero then

						FunnyComment = Sounds.VoicesHero9_HERO9_FunnyComment_rnd_01	
					
					--AddOn
				
				elseif Logic.IsEntityInCategory(EntityId,EntityCategories.Hero10) == 1 then
					FunnyComment = Sounds.AOVoicesHero10_HERO10_FunnyComment_rnd_01
				elseif Logic.IsEntityInCategory(EntityId,EntityCategories.Hero11) == 1 then
					FunnyComment = Sounds.AOVoicesHero11_HERO11_FunnyComment_rnd_01
				elseif EntityType == Entities.CU_Evil_Queen then
					FunnyComment = Sounds.AOVoicesHero12_HERO12_FunnyComment_rnd_01
				
				
				
					end
				else
				--disbale Buy soldier Area for cannons
				if Logic.IsEntityInCategory(EntityId,EntityCategories.Cannon) == 1 
				or EntityType == Entities.PU_BattleSerf 
				or EntityType == Entities.PU_Scout 
				or EntityType == Entities.PU_Thief then
					XGUIEng.ShowWidget(gvGUI_WidgetID.BuySoldierArea ,0)
				else
					XGUIEng.ShowWidget(gvGUI_WidgetID.BuySoldierArea ,1)		
				end
				--XGUIEng.ShowWidget(gvGUI_WidgetID.BuySoldier,1)
				
				FunnyComment = Sounds.VoicesLeader_LEADER_FunnyComment_rnd_04
				end
		
			end	
		
	
		-- Is selected entity a building?
		elseif Logic.IsBuilding( EntityId ) == 1 then
	
			if RandomSelectionSound == 2 then
				local Name = "OnKlick_" .. EntityTypeName
				SelectionSound = Sounds[Name]
			end
			
		
			--Hide all building widgets
			XGUIEng.ShowAllSubWidgets(gvGUI_WidgetID.SelectionBuilding,0)	
		
			--Display building container
			XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionBuilding,1)
		
			local UpgradeCategory = Logic.GetUpgradeCategoryByBuildingType(EntityType)
		
			
			--Display Worker buttons for buildings with more then one worker
			do 
				--Does the building have Workers?
				local MaxNumberOfworkers = Logic.GetMaxNumWorkersInBuilding(EntityId)
				if MaxNumberOfworkers > 1 then
					--YES!
					--Display Buttons				
					XGUIEng.ShowWidget(gvGUI_WidgetID.BuildingTabs,1)
					XGUIEng.UnHighLightGroup(gvGUI_WidgetID.InGame, "BuildingMenuGroup")	
					XGUIEng.HighLightButton(gvGUI_WidgetID.ToBuildingSettlersMenu,1)	
				
					XGUIEng.ShowWidget(gvGUI_WidgetID.ActivateOvertimes,1)
					
					InterfaceTool_UpdateWorkerAmountButtons()			
				end
			end
		
		
			--Display destroy button for all buildings expect headquarter
			do
				if 	UpgradeCategory ~= UpgradeCategories.Headquarters then
					XGUIEng.ShowWidget(gvGUI_WidgetID.DestroyBuilding,1)
					if Logic.GetEntityType(EntityId) == Entities.CB_Abbey01 then
						--editieren
						for i =0,5,1 do
							XGUIEng.SetMaterialTexture(gvGUI_WidgetID.DestroyBuildingButton, i, Folders.Map.."AbbyConvertPic.png")
						end
						XGUIEng.SetWidgetPosition(gvGUI_WidgetID.DestroyBuilding, 199, 123)
					else
						--zuruecksetzen
						for i = 0,5,1 do
							XGUIEng.SetMaterialTexture(gvGUI_WidgetID.DestroyBuildingButton, i, "data\\graphics\\textures\\gui\\b_generic_building.png")
						end
						XGUIEng.SetWidgetPosition(gvGUI_WidgetID.DestroyBuilding, 398, 164)
					end
				end
			end
		
			--Display technology progress if building is reseaching something
			do
				if Logic.GetTechnologyResearchedAtBuilding(EntityId) ~= 0 then			
					XGUIEng.ShowWidget(gvGUI_WidgetID.ResearchInProgress,1)			
				end			
			end
		
			
			--Display Upgrade Progress if building will be upgraded currently 
			do 
				if Logic.GetRemainingUpgradeTimeForBuilding(EntityId) ~= Logic.GetTotalUpgradeTimeForBuilding (EntityId) then
					XGUIEng.ShowWidget(gvGUI_WidgetID.UpgradeInProgress,1)			
				end
			end
			
			--Check selected building Type
			if Logic.IsConstructionComplete( EntityId ) == 1 then
			
				local ButtonStem = ""
				
				--Is EntityType the Headquarter?
				if  UpgradeCategory == UpgradeCategories.Headquarters then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Headquarter,1)	
					XGUIEng.ShowWidget(gvGUI_WidgetID.HQOutpostCommands,1)										
					ButtonStem = "Upgrade_Headquarter"		
				
				--Is EntityType the Village?
				elseif  UpgradeCategory == UpgradeCategories.VillageCenter then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Village,1)							
					ButtonStem = "Upgrade_Village"							
				
				--Is EntityType the residence?
				elseif 	UpgradeCategory == UpgradeCategories.Residence then			
					XGUIEng.ShowWidget(gvGUI_WidgetID.Residence,1)
					ButtonStem =  "Upgrade_Residence"
					
					--HACK:
					XGUIEng.ShowWidget(gvGUI_WidgetID.BuildingTabs,1)
					XGUIEng.UnHighLightGroup(gvGUI_WidgetID.InGame, "BuildingMenuGroup")	
					XGUIEng.HighLightButton(gvGUI_WidgetID.ToBuildingSettlersMenu,1)	
					
					XGUIEng.ShowWidget(gvGUI_WidgetID.ActivateOvertimes,0)
					XGUIEng.ShowWidget(gvGUI_WidgetID.QuitOvertimes,0)
					
					--GUIAction_ChangeBuildingMenu(gvGUI_WidgetID.ToBuildingSettlersMenu)			
					
				
				--Is EntityType the farm?
				elseif 	UpgradeCategory == UpgradeCategories.Farm then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Farm,1)
					ButtonStem =  "Upgrade_Farm"				
					--HACK
					XGUIEng.ShowWidget(gvGUI_WidgetID.BuildingTabs,1)
					XGUIEng.UnHighLightGroup(gvGUI_WidgetID.InGame, "BuildingMenuGroup")	
					XGUIEng.HighLightButton(gvGUI_WidgetID.ToBuildingSettlersMenu,1)
					
					XGUIEng.ShowWidget(gvGUI_WidgetID.ActivateOvertimes,0)
					XGUIEng.ShowWidget(gvGUI_WidgetID.QuitOvertimes,0)
					
									
					--GUIAction_ChangeBuildingMenu(gvGUI_WidgetID.ToBuildingSettlersMenu)			
					
							
				--Is EntityType the Barracks?
				elseif 	UpgradeCategory == UpgradeCategories.Barracks then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Barracks,1)
					XGUIEng.ShowWidget(gvGUI_WidgetID.ToggleRecruitGroups,1)
					ButtonStem =  "Upgrade_Barracks"
				
				--Is EntityType the Archery?
				elseif 	UpgradeCategory == UpgradeCategories.Archery then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Archery,1)
					XGUIEng.ShowWidget(gvGUI_WidgetID.ToggleRecruitGroups,1)
					ButtonStem =  "Upgrade_Archery"			
				
				--Is EntityType the Foundry?
				elseif 	UpgradeCategory == UpgradeCategories.Foundry then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Foundry,1)
					ButtonStem =  "Upgrade_Foundry"			
					local CannonProgress = Logic.GetCannonProgress(EntityId)
					if CannonProgress ~= 100 then
						XGUIEng.ShowWidget(gvGUI_WidgetID.CannonInProgress,1)
					else			
						XGUIEng.ShowWidget(gvGUI_WidgetID.CannonInProgress,0)
					end
					
				--Is EntityType the Stables?
				elseif 	UpgradeCategory == UpgradeCategories.Stable then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Stables,1)
					XGUIEng.ShowWidget(gvGUI_WidgetID.ToggleRecruitGroups,1)
					ButtonStem =  "Upgrade_Stables"			
				
				--Is EntityType the University?
				elseif 	UpgradeCategory == UpgradeCategories.University then			
					XGUIEng.ShowWidget(gvGUI_WidgetID.University,1)
					ButtonStem =  "Upgrade_University"
				
								
				--Is EntityType the Silvermine?
				elseif 	UpgradeCategory == UpgradeCategories.ClayMine then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Claymine,1)					
					ButtonStem =  "Upgrade_Claymine"			
				
				--Is EntityType the Sulfurmine?
				elseif 	UpgradeCategory == UpgradeCategories.SulfurMine then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Sulfurmine,1)					
					ButtonStem =  "Upgrade_Sulfurmine"
					
				--Is EntityType the Ironmine?
				elseif 	UpgradeCategory == UpgradeCategories.IronMine then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Ironmine,1)					
					ButtonStem =  "Upgrade_Ironmine"
				
				--Is EntityType the Stonemine?
				elseif 	UpgradeCategory == UpgradeCategories.StoneMine then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Stonemine,1)					
					ButtonStem =  "Upgrade_Stonemine"
								
				--Is EntityType the Brickworks?
				elseif 	UpgradeCategory == UpgradeCategories.Brickworks then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Brickworks,1)					
					ButtonStem =  "Upgrade_Brickworks"
				
				--Is EntityType the Sawmill?
				elseif 	UpgradeCategory == UpgradeCategories.Sawmill then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Sawmill,1)					
					ButtonStem =  "Upgrade_Sawmill"			
				
				--Is EntityType the Blacksmith?
				elseif 	UpgradeCategory == UpgradeCategories.Blacksmith then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Blacksmith,1)					
					ButtonStem =  "Upgrade_Blacksmith"
				
				--Is EntityType the StoneMason?
				elseif 	UpgradeCategory == UpgradeCategories.StoneMason then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Stonemason,1)					
					ButtonStem =  "Upgrade_Stonemason"
				
				
				--Is EntityType the Alchemist?
				elseif 	UpgradeCategory == UpgradeCategories.Alchemist then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Alchemist,1)					
					ButtonStem =  "Upgrade_Alchemist"
				
				
				--Is EntityType the Monastery?
				elseif 	UpgradeCategory == UpgradeCategories.Monastery then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Monastery,1)					
					ButtonStem =  "Upgrade_Monastery"
					
				--Is EntityType the Market?
				elseif 	UpgradeCategory == UpgradeCategories.Market then
				
					--You can only trade at market level 2
					if EntityType == Entities.PB_Market2 then
						XGUIEng.ShowWidget(gvGUI_WidgetID.Trade,1)
						--Trdae in progress?
						if Logic.GetTransactionProgress(EntityId) ~= 100 then
							XGUIEng.ShowWidget(gvGUI_WidgetID.TradeInProgress,1)
						else			
							XGUIEng.ShowWidget(gvGUI_WidgetID.TradeInProgress,0)
						end
					else
						XGUIEng.ShowWidget(gvGUI_WidgetID.Trade,0)
						XGUIEng.ShowWidget(gvGUI_WidgetID.TradeInProgress,0)
					end
					
					
					
					XGUIEng.ShowWidget(gvGUI_WidgetID.Market,1)					
					ButtonStem =  "Upgrade_Market"
					
					if EntityId ~= gvGUI.LastSelectedEntityID then
						GUIAction_MarketClearDeals()
					end
					
				
				--Is EntityType the Bank?
				elseif 	UpgradeCategory == UpgradeCategories.Bank then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Bank,1)					
					ButtonStem =  "Upgrade_Bank"
				
				
				--Is EntityType the Tower?
				elseif 	UpgradeCategory == UpgradeCategories.Tower then
					XGUIEng.ShowWidget(gvGUI_WidgetID.Tower,1)					
					ButtonStem =  "Upgrade_Tower"
					
				--Is EntityType the outpost?
				elseif 	UpgradeCategory == UpgradeCategories.Outpost then
					
					XGUIEng.ShowWidget(gvGUI_WidgetID.Outpost,1)					
					XGUIEng.ShowWidget(gvGUI_WidgetID.HQOutpostCommands,1)				
				
				--Is EntityType the weathertower?
				elseif 	UpgradeCategory == UpgradeCategories.Weathermachine then				
					XGUIEng.ShowWidget(gvGUI_WidgetID.WeatherTower,1)					
				--Is EntityType the powerPlant?
				elseif 	UpgradeCategory == UpgradeCategories.PowerPlant then				
					XGUIEng.ShowWidget(gvGUI_WidgetID.PowerPlant,1)					
					
				
			-- ADDON:
			--Is EntityType the Tavern?
			elseif 	UpgradeCategory == UpgradeCategories.Tavern then
				XGUIEng.ShowWidget(gvGUI_WidgetID.Tavern,1)					
				ButtonStem =  "Upgrade_Tavern"
				
			--Is EntityType the Gunsmith?
			elseif 	UpgradeCategory == UpgradeCategories.GunsmithWorkshop then
				XGUIEng.ShowWidget(gvGUI_WidgetID.GunsmithWorkshop,1)					
				ButtonStem =  "Upgrade_GunsmithWorkshop"
				
			--Is EntityType the Master builder Workshop?
			elseif 	UpgradeCategory == UpgradeCategories.MasterBuilderWorkshop then
				XGUIEng.ShowWidget(gvGUI_WidgetID.MasterBuilderWorkshop,1)					
				
			--Is EntityType the bridge?
			--elseif 	UpgradeCategory == UpgradeCategories.Bridge then
			--	XGUIEng.ShowWidget(gvGUI_WidgetID.Bridge,1)					
			
			
				end
				--Update Upgrade Buttons
				InterfaceTool_UpdateUpgradeButtons(EntityType, UpgradeCategory,ButtonStem)								
			end
		end
		
		
		--funny comment only for settlers
		if FunnyComment ~= 0 then
			if Logic.IsSettler( EntityId ) == 1 then
				
				if EntityId  == gvGUI.LastSelectedEntityID then
					gvGUI.FunnyCommentsSelectionCounter = gvGUI.FunnyCommentsSelectionCounter + 1
				end
				
				
				if gvGUI.FunnyCommentsSelectionCounter >= 8 then
					Sound.PlayQueuedFeedbackSound(FunnyComment,127)				
					SelectionSound = 0
					gvGUI.FunnyCommentsSelectionCounter = 0
					gvGUI.FunnyCommentStartTime = Game.RealTimeGetMs() / 1000
				end			
				
			end
		end
		
		
		if gvGUI.LastSelectedEntityID ~= EntityId then
			-- play selection sound
			-- Confirm FX - only every x ms
			if Logic.IsWorker( EntityId )  == 0 then
				
					do
						local CurrentTime = Game.RealTimeGetMs() / 1000		
						if 		gvSelection_LastTimeFXStarted == nil 
							or 	( CurrentTime - gvSelection_LastTimeFXStarted ) > 0.4
						then			
							local volume = 64
							if Logic.IsBuilding( EntityId ) == 1 then						
								volume = 20
								Sound.PlayGUISound( SelectionSound, volume )
							end
							if SelectionSound ~= 0 then								
								if gvGUI.FunnyCommentStartTime == nil 
								or ( CurrentTime - gvGUI.FunnyCommentStartTime ) > 2.5 then
									Sound.PlayGUISound( SelectionSound, volume )
								end
							end
						end
						gvSelection_LastTimeFXStarted = CurrentTime
					
				end	
			else			
				GUIAction_WorkerFeedbackBySelection( EntityId )
			end
		end
		
		gvGUI.LastSelectedEntityID = EntityId
		
		-- Init hero selection
		HeroSelection_Init()
		
		-- Any hero selected
		if HeroSelection_GetCurrentHeroType() ~= 0 then
			
			-- Show hero page
			HeroWidgetUpdate_ShowHeroWidget(HeroSelection_GetCurrentSelectedHeroID())
			
		end
		
		--Update all buttons in the visible container
		XGUIEng.DoManualButtonUpdate(gvGUI_WidgetID.InGame)
		
		if bombriders[EntityId] then
				XGUIEng.ShowAllSubWidgets(gvGUI_WidgetID.SelectionHero,0)
				XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionHero,1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero4_RechargeCircularAttack"),1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero4_RechargeAuraOfWar"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero4_CircularAttack"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero4_AuraOfWar"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Selection_Hero4"),1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Selection_Hero"),1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero4_RechargeCircularAttack"),1)
				XGUIEng.ShowWidget(gvGUI_WidgetID.SelectionLeader,1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Formation02"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Formation03"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Formation04"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Buy_Soldier"),0)
				if bombriders[EntityId] < 40 then
					XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero4,RechargeCircularAttack"),1)
					XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation01"), 1)
				else
					XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero4,RechargeCircularAttack"),0)
					XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation01"), 0)
				end
				for i = 0,5,1 do
					XGUIEng.SetMaterialTexture(XGUIEng.GetWidgetID("Formation01"), i, Folders.Map.."/bombriderpicture.png")
				end
			else
				local teststate = Logic.GetTechnologyState(1, Technologies.GT_Tactics)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero4_RechargeCircularAttack"),0)
				XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation01"), (((teststate == 2) or (teststate == 3) or (teststate == 4)) and 0) or 1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Formation02"),1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Formation03"),1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Formation04"),1)
				XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation02"), (((teststate == 2) or (teststate == 3) or (teststate == 4)) and 0) or 1)
				XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation03"), (((teststate == 2) or (teststate == 3) or (teststate == 4)) and 0) or 1)
				XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation04"), (((teststate == 2) or (teststate == 3) or (teststate == 4)) and 0) or 1)
				if Logic.IsHero(EntityId) == 0 and Logic.IsEntityInCategory(EntityId,EntityCategories.Cannon) ~= 1 
				and EntityType ~= Entities.PU_BattleSerf 
				and EntityType ~= Entities.PU_Scout 
				and EntityType ~= Entities.PU_Thief  then
					XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Buy_Soldier"),1)
				else
					XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Buy_Soldier"),0)
				end
				for i = 0,5,1 do
					XGUIEng.SetMaterialTexture(XGUIEng.GetWidgetID("Formation01"),i,"data\\graphics\\textures\\gui\\b_units_military.png")
				end
			end
	end
	
	function GUIAction_ChangeFormation(_formationtype)


		local SelectedEntityIDs = { GUI.GetSelectedEntities() }

		if not bombriders[SelectedEntityIDs[1]] then
			
			do
				for i=1, 20, 1 do
					local SelectedEntityID = SelectedEntityIDs[ i ]
					if SelectedEntityID ~= nil and SelectedEntityID > 0 and not bombriders[SelectedEntityID] then
						if _formationtype == 1 then
							GUI.LeaderChangeFormationType( SelectedEntityID, 1 )		
						elseif _formationtype == 2 then
							GUI.LeaderChangeFormationType( SelectedEntityID, 2 )
						elseif _formationtype == 3 then
							GUI.LeaderChangeFormationType( SelectedEntityID, 3 )
						elseif _formationtype == 4 then
							GUI.LeaderChangeFormationType( SelectedEntityID, 4 )
						end			
					end
				end
			end
				
			GUI.SendChangeFormationFeedbackEvent(_formationtype)
		
		elseif _formationtype == 1 then
			local _pID = GUI.GetPlayerID()
			local bombpos = GetPosition(GUI.GetSelectedEntity())
			
			Logic.CreateEntity(Entities.XD_Bomb1,bombpos.X,bombpos.Y,0,_pID)
			Logic.CreateEntity(Entities.XD_Bomb1,bombpos.X+1,bombpos.Y-1,0,_pID)
			Logic.CreateEntity(Entities.XD_Bomb1,bombpos.X-1,bombpos.Y+1,0,_pID)
			--Logic.CreateEntity(Entities.XD_Bomb1,bombpos.X-1,bombpos.Y,0,_pID)
			--Logic.CreateEntity(Entities.XD_Bomb1,bombpos.X,bombpos.Y-1,0,_pID)
			
			bombriders[SelectedEntityIDs[1]] = 0
			XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Formation01"),0)
			XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Formation01"),1)
			XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation01"),1)
		end
		
		return
	end
		
	function GUIUpdate_HeroAbility(_ability, _button)
	
		local CurrentWidgetID = XGUIEng.GetCurrentWidgetID()
		
		local SelectedEntityID = GUI.GetSelectedEntity()
		
		if Logic.IsHero(SelectedEntityID) == 1 then
			SelectedEntityID = HeroSelection_GetCurrentSelectedHeroID()	
		end
		
		if not bombriders[SelectedEntityID] then		
			
			local RechargeTime = Logic.HeroGetAbilityRechargeTime(SelectedEntityID, _ability)
			local TimeLeft = Logic.HeroGetAbiltityChargeSeconds(SelectedEntityID, _ability)
			
			if TimeLeft == RechargeTime then		
				XGUIEng.SetMaterialColor(CurrentWidgetID,1,0,0,0,0)
				XGUIEng.DisableButton(_button,0)
			end
			if TimeLeft < RechargeTime then
				XGUIEng.SetMaterialColor(CurrentWidgetID,1,214,44,24,189)						
				XGUIEng.DisableButton(_button,1)
			end
			
			XGUIEng.SetProgressBarValues(CurrentWidgetID,TimeLeft, RechargeTime)
		else
			if _ability == Abilities.AbilityCircularAttack then
				if bombriders[SelectedEntityID] < 40 then
					XGUIEng.SetMaterialColor(CurrentWidgetID,1,214,44,24,189)	
					XGUIEng.DisableButton(_button,1)
				else
					XGUIEng.SetMaterialColor(CurrentWidgetID,1,0,0,0,0)
					XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation01"),0)
					XGUIEng.DisableButton(_button,0)
				end
				XGUIEng.SetProgressBarValues(XGUIEng.GetWidgetID("Hero4_RechargeCircularAttack"),bombriders[SelectedEntityID],40)
			end
		end
	
	end
	
	function GUITooltip_NormalButton(_TooltipString, _ShortCut)
	if not bombriders[GUI.GetSelectedEntity()] then
		local CostString = " "
		local ShortCutToolTip = " "
		
		
		
		if _ShortCut ~= nil then
			ShortCutToolTip = XGUIEng.GetStringTableText("MenuGeneric/Key_name") .. ": [" .. XGUIEng.GetStringTableText(_ShortCut) .. "]"
		end
		if _TooltipString == "MenuBuildingGeneric/destroybuilding" and Logic.GetEntityType(GUI.GetSelectedEntity()) == Entities.CB_Abbey01 then
			local CostString = InterfaceTool_CreateCostString( {[ResourceType.Sulfur] = 2000, [ResourceType.Gold] = 3000, [ResourceType.Iron] = 1500, [ResourceType.Wood] = 0, [ResourceType.Clay] = 0, [ResourceType.Stone] = 0, [ResourceType.Silver] = 0 })
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomCosts, CostString)
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomShortCut, ShortCutToolTip)
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomText,"@color:180,180,180,255 Schwere Kavallerie Stufe 2 zu Bombenreiter konvertieren  @cr @color:255,255,255,255 Einer eurer Hauptmänner der schweren Kavallerie Stufe 2 wird in einen Bombenreiter umgewandelt. @cr Es können maximal 2 gleichzeitig existieren.")
		else
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomCosts, CostString)
			XGUIEng.SetTextKeyName(gvGUI_WidgetID.TooltipBottomText, _TooltipString)
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomShortCut, ShortCutToolTip)
		end
	else
		if _TooltipString == "MenuCommandsGeneric/formation_group" then
			local CostString= " "
			local ShortCutToolTip = " "
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomCosts, CostString)
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomShortCut, ShortCutToolTip)
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomText,"@color:180,180,180,255 Bombe legen  @cr @color:255,255,255,255 Euer Soldat legt eine Bombe unter sich auf den Boden.")
		else
			local CostString = " "
			local ShortCutToolTip = " "
			
			if _ShortCut ~= nil then
				ShortCutToolTip = XGUIEng.GetStringTableText("MenuGeneric/Key_name") .. ": [" .. XGUIEng.GetStringTableText(_ShortCut) .. "]"
			end
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomCosts, CostString)
			XGUIEng.SetTextKeyName(gvGUI_WidgetID.TooltipBottomText, _TooltipString)
			XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomShortCut, ShortCutToolTip)
		end
	end
	
	end
	
	bombrideroffers = {}
	--bombrideroffers[GetID("CannonMe0rchant")] = 2
	
	function GUIUpdate_TroopOffer(_SlotIndex)
			
		
		local CurrentWidgetID = XGUIEng.GetCurrentWidgetID()
		
		local AmountOfOffers = Logic.GetNumerOfMerchantOffers(SelectedTroopMerchantID) 
			
		local LeaderType, Amount = Logic.GetMercenaryOffer(SelectedTroopMerchantID,_SlotIndex, InterfaceGlobals.CostTable)
		
		local SourceButton 
		
		if Logic.IsEntityTypeInCategory(LeaderType,EntityCategories.Bow) == 1 then
			SourceButton = "Buy_LeaderBow"
		elseif Logic.IsEntityTypeInCategory(LeaderType,EntityCategories.Spear)== 1 then
			SourceButton = "Buy_LeaderSpear"
		elseif Logic.IsEntityTypeInCategory(LeaderType,EntityCategories.CavalryHeavy)== 1 then
			SourceButton = "Buy_LeaderCavalryHeavy"
		elseif Logic.IsEntityTypeInCategory(LeaderType,EntityCategories.CavalryLight) == 1 then
			SourceButton = "Buy_LeaderCavalryLight"
		elseif Logic.IsEntityTypeInCategory(LeaderType,EntityCategories.Rifle) == 1 then	
			SourceButton = "Buy_LeaderRifle"		
		elseif LeaderType == Entities.PV_Cannon1 then	
			SourceButton = "Buy_Cannon1"		
		elseif LeaderType == Entities.PV_Cannon2 then	
			SourceButton = "Buy_Cannon2"		
		elseif LeaderType == Entities.PV_Cannon3 then	
			SourceButton = "Buy_Cannon3"		
		elseif LeaderType == Entities.PV_Cannon4 then	
			SourceButton = "Buy_Cannon4"		
		elseif LeaderType == Entities.PU_Serf then
			SourceButton = "Buy_Serf"
		elseif LeaderType == Entities.PU_Thief then
			SourceButton = "Buy_Thief"				
		elseif LeaderType == Entities.PU_Scout then
			SourceButton = "Buy_Scout"				
		else
			SourceButton = "Buy_LeaderSword"
		end
		XGUIEng.TransferMaterials(SourceButton, CurrentWidgetID)
		--[[
		if _SlotIndex == 2 then
			if bombrideroffers[SelectedTroopMerchantID] and bombrideroffers[SelectedTroopMerchantID] >= 0 then
				Amount = bombrideroffers[SelectedTroopMerchantID]
				XGUIEng.SetText(gvGUI_WidgetID.TroopMerchantOfferAmount[_SlotIndex], "@ra " .. Amount)
			end
			return 
		end
		]]
		
		if Amount == -1 then
			Amount = "00"
		end
		
		XGUIEng.SetText(gvGUI_WidgetID.TroopMerchantOfferAmount[_SlotIndex], "@ra " .. Amount)
		
	end
	
	function GUIAction_ToDestroyBuildingWindow()
		if GUI.GetSelectedEntity() == GetID("BombKonverter") then
			ConvertReiter()
			return 
		end
		XGUIEng.ShowAllSubWidgets(gvGUI_WidgetID.SelectionBuilding,0)	
		XGUIEng.ShowWidget(gvGUI_WidgetID.DestroyBuildingConfirmation ,1)
	end
	
	function GUIUpdate_BuildingButtons(_Button, _Technology)
		
		local PlayerID = GUI.GetPlayerID()
		local TechState = Logic.GetTechnologyState(PlayerID, _Technology)
		
		if not bombriders[GUI.GetSelectedEntity()] then
			--Building is interdicted
			if TechState == 0 then	
				XGUIEng.DisableButton(_Button,1)
			
			--Building is not available yet or Technology is to far in the futur
			elseif TechState == 1 or TechState == 5 then
				XGUIEng.DisableButton(_Button,1)
				XGUIEng.ShowWidget(_Button,1)
				
			--Building is enabled and visible	
			elseif TechState == 2 or TechState == 3 or TechState == 4 then
				XGUIEng.ShowWidget(_Button,1)
				XGUIEng.DisableButton(_Button,0)	
			
			end
		end
	end
end

--Stadtwachenfix
function FixStadtwache()
   GameCallback_OnTechnologyResearchedOriginal = GameCallback_OnTechnologyResearched
   function GameCallback_OnTechnologyResearched( _PlayerID, _TechnologyType )
       GameCallback_OnTechnologyResearchedOriginal( _PlayerID,_TechnologyType)
       if _TechnologyType == Technologies.T_TownGuard then
       Logic.SetTechnologyState(_PlayerID,Technologies.T_CityGuard, 3)
       end
   end
end