Script.Load( "Data\\Script\\MapTools\\Main.lua" )
------------------------------------------------------------------------------
function InitDiplomacy()
    SetHostile(1,2)

	end
------------------------------------------------------------------------------
function InitResources()
    -- set some resources
    AddStone(500)
    AddClay(500)
    AddGold(1000)
    AddSulfur(500)
    AddIron(200)
    AddWood(1000)
    end
------------------------------------------------------------------------------
function InitTechnologies()
	ForbidTechnology(Technologies.GT_Matchlock)
	ForbidTechnology(Technologies.GT_PulledBarrel)

	ResearchTechnology(Technologies.GT_Construction)
	ResearchTechnology(Technologies.GT_GearWheel)
	ResearchTechnology(Technologies.GT_ChainBlock)
	ResearchTechnology(Technologies.GT_Printing)
	ResearchTechnology(Technologies.GT_Trading)
	ResearchTechnology(Technologies.GT_Literacy)
	ResearchTechnology(Technologies.GT_Mercenaries)
	--erforschen:
	--Flaschenzug
	--Zahnrad
	--Buchdruck
	--Handelswesen

	--ResearchTechnology(Technologies.GT_Mathematics)
	--ResearchTechnology(Technologies.GT_Binocular)

	
	--ResearchTechnology(Technologies.GT_Alchemy)
    end
------------------------------------------------------------------------------
function InitWeatherGfxSets()
	SetupEvelanceWeatherGfxSet()
    end
------------------------------------------------------------------------------
function InitWeather()
	AddPeriodicSummer(10)
    end
------------------------------------------------------------------------------
function InitPlayerColorMapping()

    Display.SetPlayerColorMapping(1,PLAYER_COLOR) --eigentlich PLAYER_COLOR
    Display.SetPlayerColorMapping(2,NEPHILIM_COLOR)
    Display.SetPlayerColorMapping(3,PLAYER_COLOR)
    Display.SetPlayerColorMapping(4,NPC_COLOR)
    --Display.SetPlayerColorMapping(5,NPC_COLOR)
    Display.SetPlayerColorMapping(6,FRIENDLY_COLOR1)

end
------------------------------------------------------------------------------
function FirstMapAction()
	IncludeLocals("BriefingTable")
	
	IncludeLocals("GetRandom")
	IncludeLocals("TriggerFix")
	IncludeLocals("FrameworkWrapperLight")
	IncludeLocals("GetCirclePosition")
	IncludeLocals("GetAngleBetween")
	IncludeLocals("CopyTable")
	IncludeLocals("EntityIDChangedHelper")
	IncludeLocals("GetDistance")
	IncludeLocals("IsEntityOfType")
	IncludeLocals("IsValidPosition")
	IncludeLocals("LuaObject")
	IncludeLocals("TargetFilter")
	IncludeLocals("UnlimitedArmy")
	
	IncludeLocals("TradeBalancer")
	
	IncludeLocals("PoisenReiter")
	
	IncludeLocals("gameControl")
	
	IncludeLocals("BriefingTable")
	
	IncludeLocals("briefing_prelude")
	IncludeLocals("briefing_crossroads")
	IncludeLocals("briefing_lab")
	IncludeLocals("briefing_openBridge")
	IncludeLocals("briefing_victory")
	IncludeLocals("briefing_helias")
	IncludeLocals("briefing_keyKeeper")
	IncludeLocals("briefing_gateKeeper")
	IncludeLocals("briefing_openGate")
	IncludeLocals("briefing_guards")
	IncludeLocals("briefing_fortifyVillageDone")
	IncludeLocals("briefing_scharfi")
	IncludeLocals("quest_openGate")
	IncludeLocals("army_tools")
	IncludeLocals("army_villageAttacker")
	IncludeLocals("briefing_fortifyVillageResolved")
	IncludeLocals("quest_helias")
	IncludeLocals("quest_weather")
	IncludeLocals("quest_fortifyVillage")
	IncludeLocals("quest_destroyCamp")
	IncludeLocals("quest_defeat")
	IncludeLocals("quest_helias")
	IncludeLocals("quest_rescueGateKeeper")
	IncludeLocals("army_wayDefenders")
	IncludeLocals("army_SouthPath")
	IncludeLocals("player2")
	
	IncludeLocals("InteractiveObjects")
	
	IncludeLocals("quest_DestroyCaves")
	
	IncludeLocals("Towerlimit")
	
	math.randomseed(math.mod(XGUIEng.GetSystemTime(),10)*10000000)


	Cutscenes = {}
	Cutscenes[INTROCUTSCENE] = "INTRO"
	Cutscenes[MISSIONCOMPLETECUTSCENE] = "MISSIONCOMPLETE"

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

	--EnableDebugging()
	--Game.GameTimeReset()

	String.Init("CM02_05_Headhunter")
	
	reloadTextFunc = function()
		IncludeLocals("BriefingTable")
	end
	AddMapStartAndSaveLoadedCallback(reloadTextFunc)
	
	TriggerFix.AllScriptsLoaded()
	
	ActivateTowerLimit(13)
	
	TradeBlancerInit()

    CreateRandomGoldChests()
    CreateChestOpener("Dario")
    CreateChestOpener("Pilgrim")
    CreateChestOpener("Ari")
    CreateChestOpener("Helias")
    CreateChestOpener("Salim")
    CreateChestOpener("Yuki")
    StartChestQuest()

    createPlayer2()

	SetPlayerName(6, String.Key("_Player6Name"))
	-- SetPlayerName(6, "Freundliche Stadt")

		LocalMusic.UseSet = EVELANCEMUSIC
		
		bridgeflag = 0
		
	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
	
	StartSimpleJob("Bombers")
	
	EnableNpcMarker("scharfiTyp")
	
	bombriders = {}
	bobmersHP = {}
	
	OverrideGUI()
	
	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)
		
	createArmyVillageAttackers()

    beginChapterOne()

	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 _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
						
						for _res, _menge in pairs(InterfaceGlobals.CostTable) do
							Logic.SubFromPlayersGlobalResource(PlayerID,_res,_menge)
						end
						
					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)			
				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("Hero10_RechargeSniperAttack"),1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero10_RechargeLongRangeAura"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero10_SniperAttack"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero10_LongRangeAura"),0)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Selection_Hero10"),1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Selection_Hero"),1)
				XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero10_RechargeSniperAttack"),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("Hero10,RechargeSniperAttack"),1)
					XGUIEng.DisableButton(XGUIEng.GetWidgetID("Formation01"), 1)
				else
					XGUIEng.ShowWidget(XGUIEng.GetWidgetID("Hero10,RechargeSniperAttack"),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("Hero10_RechargeSniperAttack"),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)
			
			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.AbilitySniper 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("Hero10_RechargeSniperAttack"),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
		XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomCosts, CostString)
		XGUIEng.SetTextKeyName(gvGUI_WidgetID.TooltipBottomText, _TooltipString)
		XGUIEng.SetText(gvGUI_WidgetID.TooltipBottomShortCut, ShortCutToolTip)
	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("CannonMerchant")] = 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] >= 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

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
	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