--------------------------------------------------------------------------------
-- MapName: 	CM_20_BattleOfEvelance
-- Author: 		Andreas Nitsche, Thomas Friedmann
--                                                                              
-- Quest: 	                                                                    
--                                                                              
----------------------------------------------------------------------------------
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	--Input.KeyBindDown (Keys.NumPad0, "Cheat_Trader1_Start()")
	--Input.KeyBindDown (Keys.NumPad4, "Cheat_Trader3_Start()")


	-- Include main function
		Script.Load( "Data\\Script\\MapTools\\Main.lua" )

	--	globals
	
		IncludeGlobals("MapSettings_Main")

	--	locals
	
		IncludeLocals("player_1")
		IncludeLocals("player_4")
		IncludeLocals("player_5")

		IncludeLocals("gameControl")
		IncludeLocals("tributeControl")
	
		IncludeLocals("quest_defeat")
		IncludeLocals("quest_destroyOutpost")
		IncludeLocals("quest_destroyLionsDen")
		IncludeLocals("quest_trader1")
		IncludeLocals("quest_trader2")
		IncludeLocals("quest_trader3")
		IncludeLocals("quest_reinforcements")
		IncludeLocals("quest_wetCannons")
		IncludeLocals("quest_reachWeatherMachine")
		IncludeLocals("quest_rewards")
		IncludeLocals("quest_weatherMaker")
		IncludeLocals("quest_door")
		
		IncludeLocals("army_attack1")
		IncludeLocals("army_attack2")
		IncludeLocals("army_attack3")
		IncludeLocals("army_minePatrol")
		IncludeLocals("army_defendDen")
		IncludeLocals("army_defendMines")
		IncludeLocals("army_EndFight")
		
		IncludeLocals("briefing_prelude")
		IncludeLocals("briefing_trader1")
		IncludeLocals("briefing_trader2")
		IncludeLocals("briefing_trader3")
		IncludeLocals("briefing_explodingCannons")
		IncludeLocals("briefing_Trader2Paid")
		IncludeLocals("briefing_ReinforcementArrives")
		IncludeLocals("briefing_gatesOpen")
		IncludeLocals("briefing_weatherMachine")
		IncludeLocals("briefing_miner1")
		IncludeLocals("briefing_weatherMaker")
		IncludeLocals("briefing_endFight")
		
		IncludeLocals("customMapFuncs")
		IncludeLocals("InterpolationZMath")
		IncludeLocals("WorldRastertung")
		
		IncludeLocals("LuaObject")
		IncludeLocals("GetRandom")
		IncludeLocals("CopyTable")
		IncludeLocals("GetAngleBetween")
		IncludeLocals("GetCirclePosition")
		IncludeLocals("GetDistance")
		IncludeLocals("IsEntityOfType")
		IncludeLocals("TriggerFix")
		IncludeLocals("TargetFilter")
		IncludeLocals("IsValidPosition")
		IncludeLocals("EntityIdChangedHelper")
		IncludeLocals("UnlimitedArmy")
		IncludeLocals("UnlimitedArmyRecruiter")
		IncludeLocals("UnlimitedArmySpawnGenerator")
		IncludeLocals("PostEventMPServerFix")
		
		IncludeLocals("quest_CollectHeroes")
		
		IncludeLocals("Cutscene_Control")		--TF_Include!
		IncludeLocals("Map_LocalInit")			--TF_Include!
		

-- This function is called from main script to initialize the diplomacy states
function Mission_InitDiplomacy()
	
	Logic.SetDiplomacyState( 1, 4, Diplomacy.Hostile )
	Logic.SetDiplomacyState( 1, 5, Diplomacy.Neutral )
	Logic.SetDiplomacyState( 1, 6, Diplomacy.Neutral )
	Logic.SetDiplomacyState( 1, 7, Diplomacy.Friendly )

end


--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- This function is called from main script to init all resources for player(s)
function Mission_InitResources()
--function Tools.GiveResouces(_PlayerID, _gold, _clay,_wood, _stone,_iron,_sulfur)
	GlobalMissionScripting.GiveResouces(gvMission.PlayerID, 2000, 1200, 2000, 1200, 1200, 1200)
end


--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- This function is called to setup Technology states on mission start
function Mission_InitTechnologies()
end


--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- This function is called to set the player colors
function Mission_InitPlayerColorMapping()

		Display.SetPlayerColorMapping(2, NPC_COLOR)				-- NPCs
		Display.SetPlayerColorMapping(6, KERBEROS_COLOR)			-- Keberos Boss Base

		Display.SetPlayerColorMapping(3, KERBEROS_COLOR)		-- Kerberos walls
		Display.SetPlayerColorMapping(4, KERBEROS_COLOR)		-- Kerberos Outpost
		Display.SetPlayerColorMapping(5, KERBEROS_COLOR)		-- Kerberos inner Castle
		
		Display.SetPlayerColorMapping(7, PLAYER_FRIEND_COLOR)		-- extended allies
		Logic.SetShareExplorationWithPlayerFlag(1, 7, 1)
		Logic.SetShareExplorationWithPlayerFlag(7, 1, 1)

end



--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- This function is called on game start to initialize ai for all ai players
function Mission_InitAI()

	--	set up all players

end


--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- This function is called on game start and after save game is loaded, setup your weather gfx
-- sets here
function Mission_InitWeatherGfxSets()

	Display.SetRenderUseGfxSets(1)
	
	WeatherSets_SetupEvelance(1)
	WeatherSets_SetupEvelanceRain(2)
	WeatherSets_SetupEvelanceSnow(3)
	
	Display.GfxSetSetFogParams(1, 0.0, 1.0, 1, 152,172,182, 5000,29000)
	Display.GfxSetSetFogParams(2, 0.0, 1.0, 1, 102,132,142, 3000,29000)
	Display.GfxSetSetFogParams(3, 0.0, 1.0, 1, 152,172,182, 3000,29000)
	
	Display.SetFarClipPlaneMinAndMax(0, 30000)
	
	if suddenDeathflag == true then
		Display.GfxSetSetFogParams(1, 0.0, 1.0, 1, 152,172,182, 5000,29000)
		Display.GfxSetSetFogParams(2, 0.0, 1.0, 1, 102,132,142, 3000,29000)
		Display.GfxSetSetFogParams(3, 0.0, 1.0, 1, 152,172,182, 3000,29000)
		Display.GfxSetSetRainEffectStatus(1, 0.0, 1.0, 1)
		Display.GfxSetSetRainEffectStatus(2, 0.0, 1.0, 1)
		Display.GfxSetSetRainEffectStatus(3, 0.0, 1.0, 1)
		Display.GfxSetSetLightParams(1,  0.0, 1.0, 40, -15, -50,  255,70,70, 128,104,72)
		Display.GfxSetSetLightParams(2,  0.0, 1.0, 40, -15, -50,  255,70,70, 128,104,72)
		Display.GfxSetSetLightParams(3,  0.0, 1.0, 40, -15, -50,  255,70,70, 255,234,202)
	end
	
	if LastFightPart ~= nil then
		if LastFightPart >= 3 then
			function GUIUpdate_VCTechRaceProgress() end
			function GUIUpdate_GetTeamPoints() end
			function GUIUpdate_VCTechRaceColor(_Player) end
			XGUIEng.ShowWidget("VCMP_Window", 1)
			XGUIEng.ShowWidget("VCMP_Team2", 0)
			XGUIEng.ShowWidget("VCMP_Team3", 0)
			XGUIEng.ShowWidget("VCMP_Team4", 0)
			XGUIEng.ShowWidget("VCMP_Team5", 0)
			XGUIEng.ShowWidget("VCMP_Team6", 0)
			XGUIEng.ShowWidget("VCMP_Team7", 0)
			XGUIEng.ShowWidget("VCMP_Team8", 0)
			XGUIEng.ShowWidget("VCMP_Team2_Shade", 0)
			XGUIEng.ShowWidget("VCMP_Team3_Shade", 0)
			XGUIEng.ShowWidget("VCMP_Team4_Shade", 0)
			XGUIEng.ShowWidget("VCMP_Team5_Shade", 0)
			XGUIEng.ShowWidget("VCMP_Team6_Shade", 0)
			XGUIEng.ShowWidget("VCMP_Team7_Shade", 0)
			XGUIEng.ShowWidget("VCMP_Team8_Shade", 0)
			XGUIEng.ShowWidget("VCMP_Team1Name",0)
			XGUIEng.ShowWidget("VCMP_Team1Player1", 0)
			XGUIEng.ShowWidget("VCMP_Team1Player2", 0)
			XGUIEng.ShowWidget("VCMP_Team1Player3", 0)
			XGUIEng.ShowWidget("VCMP_Team1Player4", 0)
			XGUIEng.ShowWidget("VCMP_Team1Player5", 0)
			XGUIEng.ShowWidget("VCMP_Team1Player6", 0)
			XGUIEng.ShowWidget("VCMP_Team1Player7", 0)
			XGUIEng.ShowWidget("VCMP_Team1Player8", 0)
			XGUIEng.SetWidgetPositionAndSize(XGUIEng.GetWidgetID("VCMP_Window"), 256, 80, 522, 300)
			XGUIEng.ShowWidget("VCMP_Team1TechRace",1)
			XGUIEng.SetWidgetPositionAndSize(XGUIEng.GetWidgetID("VCMP_Team1"),0,0,522,30)
			XGUIEng.SetWidgetPositionAndSize(XGUIEng.GetWidgetID("VCMP_Team1TechRace"),0,0,522,48)
			XGUIEng.SetWidgetPositionAndSize(XGUIEng.GetWidgetID("VCMP_Team1Progress"),12,19,498,10)
			XGUIEng.SetWidgetPositionAndSize(XGUIEng.GetWidgetID("VCMP_Team1ProgressBG"),12,19,498,10)
			XGUIEng.SetWidgetPositionAndSize(XGUIEng.GetWidgetID("VCMP_Team1_Shade"),0,0,522,48)
			XGUIEng.SetMaterialColor(XGUIEng.GetWidgetID("VCMP_Team1Progress"), 0, 120, 0, 0, 255)
			for i = 0,5,1 do XGUIEng.SetMaterialColor(XGUIEng.GetWidgetID("VCMP_Team1_Shade"), i, 255, 255, 255, 255) end
			for i = 0,5,1 do XGUIEng.SetMaterialColor(XGUIEng.GetWidgetID("VCMP_Team1ProgressBG"), i, 50, 50, 50, 255) end
			for i = 0,5,1 do XGUIEng.SetMaterialTexture(XGUIEng.GetWidgetID("VCMP_Team1_Shade"), i, Folders.Map.."testobjekt10.png") end
			BossbalkenCalc(LastFightPart)
		end
	end
end

--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- This function is called on game start you should setup your weather periods here
function Mission_InitWeather()

	 Logic.AddWeatherElement(3, 200, 1, 3, 5, 10)
	--Trigger.RequestTrigger(Events.LOGIC_EVENT_EVERY_SECOND, "", "weatherfunc", 1)
	
--	Logic.SetupGfxSet(1)
	
--	Logic.AddWeatherElement(3, 200, 1, 3, 5, 10)
--	Logic.AddWeatherElement(2, 500, 1, 2, 5, 10) zum zeitpunkt wo die Kanonen zerstört werden machen
  
 
		-- [fun]  AddWeatherElement
		--          Add weather period on end of periods.
		-- Param1: Weather State of period, 1 = normal, 2 = rain, 3 = snow
		-- Param2: Duration of period in seconds
		-- Param3: Is periodic, 1 for (normal)periodic weather element else 0 for weather machine effects
		-- Param4: Gfx Set of this weather element
		-- Param5: Gfx Set forerun (gfx transition start some time before logic state change), time in seconds
		-- Param6: duration of Gfx Set transition
 
end
	
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- This function is called on game start after all initialization is done
function Mission_FirstMapAction()
--++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

		String.Init("CM01_20_BattleOfEvelance_Txt")


	-- Set Music-Set
		LocalMusic.UseSet = EVELANCEMUSIC

	--	chest handling

		CreateChestOpener("dario")
		CreateChestOpener("erec")
		CreateChestOpener("helias")
		CreateChestOpener("ari")
		CreateChestOpener("pilgrim")
		CreateChestOpener("salim")
	
		CreateRandomGoldChests()
		CreateRandomChests()
		
		StartChestQuest()
		
		--Display.GfxSetSetFogParams(1, 0.0, 1.0, 1, 152,172,182, 5000,29000)
		--Display.GfxSetSetFogParams(2, 0.0, 1.0, 1, 102,132,142, 3000,29000)
		--Display.GfxSetSetFogParams(3, 0.0, 1.0, 1, 152,172,182, 3000,29000)
		
		Score.Player[0] = {buildings=0, all=0}
		EntityIdChangedHelper.Init()
		
		--gvGUI_WidgetID.MainMenuSaveWindow = XGUIEng.GetWidgetID( "MainMenuSaveWindow" )
		
		math.randomseed(XGUIEng.GetSystemTime())


	-- Create players
		createPlayer1()
		createPlayer4()
		createPlayer5()
		
	-- start job for mines
	
		HistoryFlag = GoldHistoryCheck()
		
		ScreenX,ScreenY = GUI.GetScreenSize()
	
		StartSimpleJob("MineJob")
		
		Mission_OnSaveGameLoaded_Reloadfunc = Mission_OnSaveGameLoaded
		Mission_OnSaveGameLoaded = function()
		Mission_OnSaveGameLoaded_Reloadfunc()
		if Trigger.IsTriggerEnabled(QuickSaveDelayerID) then
			Trigger.UnrequestTrigger(QuickSaveDelayerID)
		end
		ReloadfuncForSave()
		end
		
		function GameCallback_Camera_CalculateZoom( _ZoomFactor )

			if gvCamera.DefaultFlag == 1 then

				local ZoomFactorEx = _ZoomFactor
		
				if ZoomFactorEx > 1 then
					ZoomFactorEx = 1
				end
			gvCamera.ZoomFac = _ZoomFactor
			gvCamera.CalcFov = gvCamera.ZoomFOVMin + (gvCamera.ZoomFOVMax - gvCamera.ZoomFOVMin) * ZoomFactorEx
			gvCamera.CalcAngle = gvCamera.ZoomAngleMin + (gvCamera.ZoomAngleMax - gvCamera.ZoomAngleMin) * ZoomFactorEx
			gvCamera.CalcDistance = gvCamera.ZoomDistanceMin + (gvCamera.ZoomDistanceMax - gvCamera.ZoomDistanceMin) * 0.45 * ( _ZoomFactor + _ZoomFactor * _ZoomFactor ) 
			
			Camera.ZoomSetFOV(gvCamera.CalcFov)
			Camera.ZoomSetAngle(gvCamera.CalcAngle)
			Camera.ZoomSetDistance(gvCamera.CalcDistance)
			end

		end
		
		function GUIAction_ToggleMenu( _Menu, _Status )
			
			-- Do not go back the main menu, when player hast los / won the game and cancle loading
			if XGUIEng.GetCurrentWidgetID() == XGUIEng.GetWidgetID( "MainMenuLoadWindowCloseButton" ) 
			and Logic.PlayerGetGameState(GUI.GetPlayerID())  ~= 1 then
				_Menu = gvGUI_WidgetID.GameEndScreenWindowHint	
				_Status = 0
			end
			
			if 		XGUIEng.GetCurrentWidgetID() == gvGUI_WidgetID.MainMenuWindow_LoadGame 
				or	_Menu == gvGUI_WidgetID.MainMenuLoadWindow then

				MainWindow_LoadGame_GenerateList()

			end

			if	 	XGUIEng.GetCurrentWidgetID() == gvGUI_WidgetID.MainMenuWindow_SaveGame then
				
				MainWindow_SaveGame_GenerateList()

			end
			
			--if Logic.PlayerGetGameState(GUI.GetPlayerID())  ~= 1 
			--and _Menu ~= gvGUI_WidgetID.MainMenuLoadWindow 
			--and _Menu ~= gvGUI_WidgetID.GameEndScreenWindowHint	then
			--	return
			--end
			

			
			-- Should toggle AND is shown right now? 
			local DoneFlag = 0
			if _Status == -1 then
				if XGUIEng.IsWidgetShown( _Menu ) == 1 then						
					DoneFlag = 1
				end	
			end
			
			
			-- Hide all
			XGUIEng.ShowAllSubWidgets( gvGUI_WidgetID.Windows, 0 )		
			
			-- Check trade			
			if _Menu == gvGUI_WidgetID.TradeWindow then
				local TributIDs =  { Logic.GetAllTributes(GUI.GetPlayerID()) }
				local HasPlayerTributes = TributIDs[1]
				if HasPlayerTributes == 0 then
					DoneFlag = 1
				end
			end
			
			-- Check quest
			if _Menu == gvGUI_WidgetID.QuestWindow then
				local QuestIDs = { Logic.GetAllQuests(GUI.GetPlayerID()) }
				local HasPlayerQuests = QuestIDs[1]
				if HasPlayerQuests == 0 then
					DoneFlag = 1
				end
			end
			
			-- Check network
			if _Menu == gvGUI_WidgetID.NetworkWindow 
			or _Menu == gvGUI_WidgetID.BuyHeroWindow then
				if XNetwork.Manager_DoesExist() == 0 then
					DoneFlag = 1
				end
			end
			
			-- Done?
			if DoneFlag == 1 then		
				return
			end
			
			XGUIEng.ShowWidget( _Menu, _Status )
			
			if _Menu == gvGUI_WidgetID.MainMenuWindow then
				if Trigger.IsTriggerEnabled(SaveDelayerID) == 0 then
					SaveDelayerID = Trigger.RequestTrigger(Events.LOGIC_EVENT_EVERY_SECOND,"","SaveDelayFunc",1,nil,nil)
				else
					Trigger.UnrequestTrigger(SaveDelayerID)
					SaveDelayerID = Trigger.RequestTrigger(Events.LOGIC_EVENT_EVERY_SECOND,"","SaveDelayFunc",1,nil,nil)
				end
			end
		end
		
		function
		GUIUpdate_DisplayButtonOnlyInMode(_ModeFlag)
			
			local CurrentWidgetID = XGUIEng.GetCurrentWidgetID()
			
			if _ModeFlag == 2 then
				local NameType = {Framework.GetCurrentMapTypeAndCampaignName()}
				local Type = NameType[1]
				
				if Type == -1 then
					if Logic.PlayerGetGameState( GUI.GetPlayerID() ) == 3 
					or Logic.PlayerGetGameState( GUI.GetPlayerID() ) == 2 then
					
						XGUIEng.DisableButton(CurrentWidgetID ,0)			
					else
						XGUIEng.DisableButton(CurrentWidgetID ,1)		
					end
				end
				return
			end
			
			
			local MapName= Framework.GetCurrentMapName()
					
			if XNetwork.Manager_DoesExist() == _ModeFlag
			or (MapName == "00_Tutorial1" 	and (CurrentWidgetID ~= XGUIEng.GetWidgetID( "MainMenuWindow_RestartGame" ) )) 
			or (MapName == "00_Tutorial1" 	and (CurrentWidgetID ~= XGUIEng.GetWidgetID( "GameEndScreen_WindowRestartGame" ) ))
			or XNetworkUbiCom.Manager_DoesExist() == 1 then		
				XGUIEng.DisableButton(CurrentWidgetID ,1)	
			else
				if CurrentWidgetID == gvGUI_WidgetID.MainMenuWindow_SaveGame then
					--XGUIEng.DisableButton(CurrentWidgetID ,1)
				else
					XGUIEng.DisableButton(CurrentWidgetID ,0)
				end
			end
			
		end
		
		function QuickSave()
			if Trigger.IsTriggerEnabled(QuickSaveDelayerID) == 1 then
				return
			end

			if Logic.PlayerGetGameState(GUI.GetPlayerID())  ~= 1 then
				return
			end
			
			local MapName= Framework.GetCurrentMapName()
			if MapName == "00_Tutorial1"  then
				return
			end 
			

			if XNetwork == nil or XNetwork.Manager_DoesExist() == 0 then
				QuickSaveDelayerID = StartSimpleJob("QuickSaveDelayer")
		--[[	local Desc = "(*) - " .. MainWindow_SaveGame_CreateSaveGameDescription()
				local success = Framework.SaveGame("quicksave", Desc)
				if success then
					GUI.AddNote( XGUIEng.GetStringTableText( "InGameMessages/GUI_GameSaved" ) )
				end]]
			end
		end
		
		function
		GUIUpdate_StopWatch()
			
			local CurrentTimeSeconds = Logic.GetTime()	
			local SecondsLeft=  math.floor(gvGUI.UltimatumTime-(CurrentTimeSeconds - gvGUI.UltimatumStartTime))
			
			local TotalMinutes = math.floor( SecondsLeft / 60 )	
			local Minutes = math.mod( TotalMinutes, 60 )
			local Hours = math.floor( TotalMinutes / 60 )
			local TotalSeconds = math.mod( math.floor(SecondsLeft), 60 )
				
			local String = " "
			
			if SecondsLeft < 60 then
				String = " @color:255,120,120,255  "
			end
			
			String = String.. "@center "
		 
			if Hours > 0 then
			
				String = String .. Hours .. ":"
			
				if Minutes < 10 then
				
					String = String .. "0"
				
				end
			
			end
			 
			if TotalSeconds < 10 then		
				String = String .. Minutes .. ":" .. "0" .. TotalSeconds	
			else		
				String = String .. Minutes .. ":" .. TotalSeconds	
			end

			if SecondsLeft == 60 then		
				Sound.Play2DSound( Sounds.Smith01,0 )
			end
			
			
			local MiliSecondsLeft = math.floor((gvGUI.UltimatumTime*1000)-(Logic.GetTimeMs() - (gvGUI.UltimatumStartTime*1000)))
			if MiliSecondsLeft == 5000
			or MiliSecondsLeft == 4000
			or MiliSecondsLeft == 3000
			or MiliSecondsLeft == 2000
			or MiliSecondsLeft == 1000 then
				Sound.Play2DSound( Sounds.Smith01,0 )
			end
			
			XGUIEng.SetText("StopWatchCounter", String)	
			
		end
		
		--weatherchangeTriggerID = Trigger.RequestTrigger(Events.LOGIC_EVENT_WEATHER_STATE_CHANGED,nil,"activeweactherchange",nil,nil)
		ReloadfuncForSave()
		SetSpecialSVs()
		
		CreateWoodPile("Holzhaufen1",50000000)
		CreateWoodPile("Holzhaufen2",50000000)
		
		GlobalMissionScripting_AttachSoldiersToLeader("P1_LeaderCrossbow",8)

	-- Start prelude

		StartCutscene("Intro", startQuestDestroyOutpost)

end

function QuickSaveDelayer()
	if Counter.Tick2("QuickSaveTimer",4) then
		local Desc = "(*) - " .. MainWindow_SaveGame_CreateSaveGameDescription()
		Framework.SaveGame("quicksave", Desc)
		--local success = Framework.SaveGame("quicksave", Desc)
		--if success then
		GUI.AddNote( XGUIEng.GetStringTableText( "InGameMessages/GUI_GameSaved" ))
		return true
		--end
	else
		GUI.AddNote("Schnellspeichern in "..Counter["QuickSaveTimer"].Limit-Counter["QuickSaveTimer"].TickCount.." ..." )
	end
	return false
end

function SaveDelayFunc()
	local CurrentTime = Logic.GetTime()
	if LightningLastTime ~= nil then
		if CurrentTime - LightningLastTime <= 2 then
			if XGUIEng.IsButtonDisabled(gvGUI_WidgetID.MainMenuWindow_SaveGame) == 0 then
				XGUIEng.DisableButton(gvGUI_WidgetID.MainMenuWindow_SaveGame ,1)
			end
			return false
		else
			if XGUIEng.IsButtonDisabled(gvGUI_WidgetID.MainMenuWindow_SaveGame) == 1 then
				XGUIEng.DisableButton(gvGUI_WidgetID.MainMenuWindow_SaveGame ,0)
			end
		end
	else
		if XGUIEng.IsButtonDisabled(gvGUI_WidgetID.MainMenuWindow_SaveGame) == 1 then
			XGUIEng.DisableButton(gvGUI_WidgetID.MainMenuWindow_SaveGame ,0)
		end
	end
end

function activeweactherchange()
	if suddenDeathflag == true then
		weathertime = 30
	else
		weathertime = 350
	end
	return false
end

function MineJob()
	for i = 1,17,1 do
		local mineID = Logic.GetEntityIDByName("ResourcenMine"..i)
		if Logic.GetResourceDoodadGoodAmount(mineID) < 5000 then
			Logic.SetResourceDoodadGoodAmount(mineID, 5000)
		end
	end
	return false
end

function GoldHistoryCheck()
	if XNetwork.Manager_IsNATReady then
		return 1
	else
		return 0
	end
end

function weatherfunc()
  if weathertime == nil then
    weathertime = 0
  end
  weathertime = weathertime + 1
  if not suddenDeathflag then
    if weathertime > 900 and Logic.GetWeatherState() == 3 then
      Logic.AddWeatherElement(1, 500, 0, 1, 5, 10)
      weathertime = 0
    elseif weathertime > 700 and Logic.GetWeatherState() == 1 then
      Logic.AddWeatherElement(3,200,0,3,5,10)
       weathertime = 0
    end
  else
    if weathertime > 40 then
      local weatherid = math.random(1,3)
      if weatherid ~= Logic.GetWeatherState() then
        Logic.AddWeatherElement(weatherid,1000,0,weatherid,5,10)
        weathertime = 0
      end
    end
  end
  return false
end

function InitInvisBuildings()
	local invubuildingID
	InvisBuildingsPart1 = 	{"part1building1",
							"part1building2",
							"part1building3",
							"part1building4",
							"part1building5",
							"part1building6",
							"part1building7",
							"part1building8",
							"part1building9",
							"part1building10",
							"part1building11",
							"part1building12",
							"part1building13",
							"part1building14",
							"part1building15",
							"part1building16",
							"part1building17",
							"part1building18",
							"part1building19",
							"innerFestungSpawnTurm1",
							"Reward2"
							}
	for _,buildingID in ipairs(InvisBuildingsPart1) do
		invubuildingID = Logic.GetEntityIDByName(buildingID)
		SetVisibility(invubuildingID,true)
		Logic.SetEntityInvulnerabilityFlag(invubuildingID, 1)
	end
	InvisBuildingsPart2 = 	{"part2building1",
							"part2building2",
							"part2building3",
							"part2building4",
							"part2building5",
							"part2building6",
							"part2building7",
							"part2building8",
							"part2building9",
							"part2building10",
							"part2building11",
							"innerFestungSpawnTurm2"
							}
	for _,buildingID in ipairs(InvisBuildingsPart2) do
		invubuildingID = Logic.GetEntityIDByName(buildingID)
		SetVisibility(invubuildingID,true)
		Logic.SetEntityInvulnerabilityFlag(invubuildingID, 1)
	end
	InvisBuildingsPart3 = 	{"part3building1",
							"part3building2",
							"part3building3",
							"part3building4",
							"part3building5",
							"part3building6",
							"innerFestungSpawnTurm3"
							}
	for _,buildingID in ipairs(InvisBuildingsPart3) do
		invubuildingID = Logic.GetEntityIDByName(buildingID)
		SetVisibility(invubuildingID,true)
		Logic.SetEntityInvulnerabilityFlag(invubuildingID, 1)
	end
	InvisBuildingsPart4 = {"part4building1",
							"part4building2",
							"part4building3",
							"part4building4",
							"part4building5",
							"part4building6",
							"part4building7",
							"part4building8",
							"part4building9",
							"part4building10",
							"part4building11",
							"part4building12",
							"part4building13",
							"part4building14",
							"part4building15",
							"part4building16",
							"part4building17",
							"innerFestungSpawnTurm4",
							"InvisMine"
							}
	for _,buildingID in ipairs(InvisBuildingsPart4) do
		invubuildingID = Logic.GetEntityIDByName(buildingID)
		SetVisibility(invubuildingID,true)
		Logic.SetEntityInvulnerabilityFlag(invubuildingID, 1)
	end
	InvisBuildingsPart5 = 	{"part5building1",
							"part5building2",
							"part5building3",
							"part5building4",
							"part5building5",
							"innerFestungSpawnTurm5"
							}
	for _,buildingID in ipairs(InvisBuildingsPart5) do
		invubuildingID = Logic.GetEntityIDByName(buildingID)
		SetVisibility(invubuildingID,true)
		Logic.SetEntityInvulnerabilityFlag(invubuildingID, 1)
	end
	InvisBuildingsPart6 = {"part6building1",
							"part6building2",
							"lionsDen"
							}
	for _,buildingID in ipairs(InvisBuildingsPart6) do
		invubuildingID = Logic.GetEntityIDByName(buildingID)
		SetVisibility(invubuildingID,true)
		Logic.SetEntityInvulnerabilityFlag(invubuildingID, 1)
	end

end

function SetVisibility(id,flag)
	local idtemp
	if type(id)=="number" then
		idtemp = id
	end
	if type(id)=="string" then
		idtemp = Logic.GetEntityIDByName(id)
	end
	if flag then
		if HistoryFlag == 1 then
			Logic.SetEntityScriptingValue(idtemp, -26, 513)
		elseif HistoryFlag == 0 then
			Logic.SetEntityScriptingValue(idtemp, -30, 513)
		end
	else
		if HistoryFlag == 1 then
			Logic.SetEntityScriptingValue(idtemp, -26, 65793)
		elseif HistoryFlag == 0 then
			Logic.SetEntityScriptingValue(idtemp, -30, 65793)
		end
	end
end

function CreateWoodPile( _posEntity, _resources )
    assert( type( _posEntity ) == "string" )
    assert( type( _resources ) == "number" )
    gvWoodPiles = gvWoodPiles or {
        JobID = StartSimpleJob("ControlWoodPiles"),
    }
    local pos = GetPosition( _posEntity )
    local pile_id = Logic.CreateEntity( Entities.XD_Rock3, pos.X, pos.Y, 0, 0 )

    SetEntityName( pile_id, _posEntity.."_WoodPile" )

    local newE = ReplaceEntity( _posEntity, Entities.XD_ResourceTree )
    Logic.SetModelAndAnimSet(newE, Models.XD_TreeEvelance1)
    Logic.SetResourceDoodadGoodAmount( GetEntityId( _posEntity ), _resources*10 )
    Logic.SetModelAndAnimSet(pile_id, Models.Effects_XF_ChopTree)
    table.insert( gvWoodPiles, { ResourceEntity = _posEntity, PileEntity = _posEntity.."_WoodPile", ResourceLimit = _resources } )
end

function ControlWoodPiles()
    for i = table.getn( gvWoodPiles ),1,-1 do
        if Logic.GetResourceDoodadGoodAmount( GetEntityId( gvWoodPiles[i].ResourceEntity ) ) <= gvWoodPiles[i].ResourceLimit then
            DestroyWoodPile( gvWoodPiles[i], i )
        end
    end
end

function DestroyWoodPile( _piletable, _index )
    local pos = GetPosition( _piletable.ResourceEntity )
    DestroyEntity( _piletable.ResourceEntity )
    DestroyEntity( _piletable.PileEntity )
    Logic.CreateEffect( GGL_Effects.FXCrushBuilding, pos.X, pos.Y, 0 )
    table.remove( gvWoodPiles, _index )
end