---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
--
-- Описания эффектов в главном меню
--
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------


---------------------------------------------------------------------------------------------
-- эффект подсветки богов
---------------------------------------------------------------------------------------------
function remove_gods_flash()
	local was_count_4 = false

	local i = 4
	while i>0 do
		local god = ConvertToCImageWidget(g_MainMenu:GetWidget("god"..i))
		local god_image = god:GetImage():GetImageId()
		local glow = ConvertToCGlowGodWidget(g_MainMenu:GetWidget("godglow"..i))
		if not glow:IsGlowDisabled() then
			local count = 0
			local j = 4
			while j>0 do
				if ConvertToCImageWidget(g_MainMenu:GetWidget("god"..j))==god_image 
				and not g_MainMenu:GetWidget("godglow"..j):IsGlowDisabled()
				then 
					count = count + 1 
				end
				j = j - 1
			end
			
			if count<4 then
				glow:RemoveEternalFlash()
			else
				was_count_4 = true
			end
		else
			glow:RemoveEternalFlash()
		end
		i = i - 1
	end

	if not was_count_4 then
		local effect = g_MainMenu:GetWidget("play_button_glow_effect")
		if effect then g_MainMenu:RemoveWidget(effect) end
		PauseScarabSparkleEffect(g_MainMenu, true)
	end
end


function update_gods_flash(window)
	local count = 1

	local god_image = ConvertToCImageWidget(window:GetWidget("god4")):GetImage():GetImageId()

	local i = 3
	while i>0 do
		local god = ConvertToCImageWidget(window:GetWidget("god"..i))	
		local glow = ConvertToCGlowGodWidget(window:GetWidget("godglow"..i))

		if not glow:IsGlowDisabled() and god:GetImage():GetImageId()==god_image then count = count + 1 end

		i = i - 1
	end

	if count==4 then
		local w = window:GetWidget("play_button_glow_effect")
		if w then window:RemoveWidget(w) end
		local w = window:GetWidget("play")
		CreatePlayButtonGlowEffect(w, "play_button_glow_effect")
		PauseScarabSparkleEffect(window, false)
		--play_sound("sound_goal_reached")

		local i = 4
		while i>0 do
			local glow = ConvertToCGlowGodWidget(window:GetWidget("godglow"..i))
			glow:Flash(get_number("mainmenu_effect", "god_flash_period"), true)
			i = i - 1
		end
	else
		PauseScarabSparkleEffect(window, true)
		local w = window:GetWidget("play_button_glow_effect")
		if w then window:RemoveWidget(w) end
		local i = 4
		while i>0 do
			local glow = ConvertToCGlowGodWidget(window:GetWidget("godglow"..i))
			glow:RemoveEternalFlash()
			i = i - 1
		end

	end
end

function update_gods(new_god)
	local god_image = new_god:GetImage():GetImageId()

	local count = 0

	local i = 4
	while i>0 do
		local god = ConvertToCImageWidget(g_MainMenu:GetWidget("god"..i))	
		local glow = ConvertToCGlowGodWidget(g_MainMenu:GetWidget("godglow"..i))

		if not glow:IsGlowDisabled() and god:GetImage():GetImageId()==god_image then count = count + 1 end

		i = i - 1
	end

	if count>1 then
		play_sound("sound_gods_flash")
		local i = 4
		while i>0 do
			local god = ConvertToCImageWidget(g_MainMenu:GetWidget("god"..i))	
			local glow = ConvertToCGlowGodWidget(g_MainMenu:GetWidget("godglow"..i))
	
			if not glow:IsGlowDisabled() and god:GetImage():GetImageId()==god_image then 
				glow:Flash(get_number("mainmenu_effect", "god_flash_period"), count==4) 
			end
	
			i = i - 1
		end

		if count==4 then
			local w = g_MainMenu:GetWidget("play_button_glow_effect")
			if w then g_MainMenu:RemoveWidget(w) end
			local w = g_MainMenu:GetWidget("play")
			CreatePlayButtonGlowEffect(w, "play_button_glow_effect")
			PauseScarabSparkleEffect(g_MainMenu, false)
			play_sound("sound_gods_complete")
		end
		
	end

end

function CreateGodChangeEffect(god, glow)

	play_sound("sound_gods_move")

	god:GetImage():RemFlags(CImage.backward_animation)
	god:GetImage():PlayAnimationTimes(1)

	if god:GetRect().mX > 400 then
		god:GetImage():AddFlags(CImage.mirrored)
	end

	glow:DisableGlow(true)
	ConvertToCGlowGodWidget(glow):RemoveEternalFlash()

	remove_gods_flash()

	local effect = CParticleNode()
	effect:SetEternal(true)

	local anim2 = CLuaStringAction(g_Lua, [[
		local god = ConvertToCImageWidget(g_MainMenu:GetWidget("]]..god:GetId()..[[")) 
		local list = {"image_gui_hathor", "image_gui_re", "image_gui_neit", "image_gui_hnum"}
		local revert_list = 
			{"image_gui_hathor_revert", "image_gui_re_revert", "image_gui_neit_revert", "image_gui_hnum_revert"}
		local i = table.getn(list)
		while i>0 do
			if god:GetImage():GetImageId()==list[i] then
				list = revert_list
				table.remove(list, i)
				break
			end
			if god:GetImage():GetImageId()==revert_list[i] then
				table.remove(list, i)
				break
			end

			i = i - 1
		end
		god:SetImage(list[math.random(table.getn(list))])
		god:GetImage():AddFlags(CImage.backward_animation)

		if god:GetRect().mX < 400 then
			god:GetImage():AddFlags(CImage.mirrored)
		else
			god:GetImage():RemFlags(CImage.mirrored)
		end

		god:GetImage():SetTime(0)
		god:GetImage():PlayAnimationTimes(1)
		]])
	anim2:OnceActionTime(720 - 60)
	effect:AddAction(anim2)

	local stop = CLuaStringAction(g_Lua, [[
		local god = ConvertToCImageWidget(g_MainMenu:GetWidget("]]..god:GetId()..[[")) 

		local new_image = "image_gui_play"
		local list = {"image_gui_hathor", "image_gui_re", "image_gui_neit", "image_gui_hnum"}
		local revert_list = 
			{"image_gui_hathor_revert", "image_gui_re_revert", "image_gui_neit_revert", "image_gui_hnum_revert"}
		local i = table.getn(list)
		while i>0 do
			if god:GetImage():GetImageId()==list[i] then
				new_image = revert_list[i]
				break
			end
			if god:GetImage():GetImageId()==revert_list[i] then
				new_image = list[i]
				break
			end

			i = i - 1
		end
		god:SetImage(new_image)

		god:GetImage():RemFlags(CImage.backward_animation)

		if god:GetRect().mX < 400 then
			god:GetImage():RemFlags(CImage.mirrored)
		else
			god:GetImage():AddFlags(CImage.mirrored)
		end

		local glow = ConvertToCGlowGodWidget(g_MainMenu:GetWidget("]]..glow:GetId()..[["))
		glow:DisableGlow(false)

		local num = string.byte(god:GetId(), string.len(god:GetId())) - 48
		profile_manager():GetCurrentProfile():SetGodImage(num-1, god:GetImage():GetImageId())
		play_sound("sound_gods_stop")

		update_gods(god)
		]])
	stop:OnceActionTime(2*720 - 70)
	effect:AddAction(stop)

	local w = CParticleWidget()
	w:AddParticleNode(effect)
	w:Start()
	glow:AddWidget(w)
end


---------------------------------------------------------------------------------------------
-- эффект подсветки кнопки Play в главменю
---------------------------------------------------------------------------------------------

local button_glow = {}

-- НАСТРОЙКИ --------------------------------------------------------------------------------

button_glow.image = "image_gui_playglow" -- изображение подсветки

button_glow.min_scale = 0.7 		-- минимальный масштаб
button_glow.max_scale = 1 		-- максимальный масштаб
button_glow.scale_period = 5000	-- период масштабирования

button_glow.angle_amplit = 10		-- амплитуда колебаний в градусах
button_glow.angle_period = 20000	-- период колебаний в градусах

button_glow.min_brightness = 120	-- мин. яркость
button_glow.max_brightness = 255	-- макс. яркость
button_glow.brightness_period=2000	-- период изменения яркости


-- РЕАЛИЗАЦИЯ --------------------------------------------------------------------------------

function CreatePlayButtonGlowEffect(button, id)
	if not button then return end

	local glow = CParticleNode()
	glow:SetEternal(true)
	glow:SetImage(button_glow.image)

	glow:SetColor(CColor(button_glow.min_brightness, button_glow.min_brightness, button_glow.min_brightness))

	-- перемещаем в центр кнопки
	glow:SetPosition(CFloatVector(button:GetRect().mX + button:GetRect().mWidth/2, 
		button:GetRect().mY + button:GetRect().mHeight/2))
	
	-- моргание
	local color = CColorAction(CColor(button_glow.min_brightness, button_glow.min_brightness, button_glow.min_brightness), 
		CColor(button_glow.max_brightness, button_glow.max_brightness, button_glow.max_brightness), 
		button_glow.brightness_period)
	glow:AddAction(color)
	
	-- вращение
	local rotation = CLuaAction(g_Lua, "play_button_glow_effect_rotation")
	glow:AddAction(rotation)

	-- масштабирование
	local scale = CScaleAction(button_glow.min_scale, button_glow.max_scale)
	scale:PeriodActionTime(button_glow.scale_period, 0, button_glow.scale_period)
	glow:AddAction(scale)

	local w = CParticleWidget(id, button:GetLayer()-1)
	w:AddParticleNode(glow)
	w:Start()
	button:GetParent():AddWidget(w)

end

local g_PlayButtonGlowRotationTime = 0

function play_button_glow_effect_rotation(p, dt)
	g_PlayButtonGlowRotationTime = g_PlayButtonGlowRotationTime + dt
	if g_PlayButtonGlowRotationTime > button_glow.angle_period then
		g_PlayButtonGlowRotationTime = math.mod(g_PlayButtonGlowRotationTime, button_glow.angle_period)
	end

	p:SetAngle(button_glow.angle_amplit*3.1415/180*math.sin(g_PlayButtonGlowRotationTime/button_glow.angle_period*6.283))
end



 
-- эффект искрящихся крыльев скарабея
---------------------------------------------------------------------------------------------

local sparkle_config = {}

-- НАСТРОЙКИ --------------------------------------------------------------------------------

sparkle_config.lifetime = 2500	-- время существования звездочки
sparkle_config.emit_timeout = 150	-- задержка вылетания звездочек
sparkle_config.max_emits = 1000000		-- максимальное количество звездочек

sparkle_config.image = "image_game_bonuses_sparkle_small"	-- картинка
sparkle_config.size = CFloatVector(27,27)	-- размер
sparkle_config.speed = 3			-- скорость движения
sparkle_config.speed_delta = 1		-- отклонения скорости движения
sparkle_config.rotation_speed = 360		-- скорость вращения (в градусах)
sparkle_config.color = CColor(255, 255, 100)	-- цвет
sparkle_config.min_scale = 0.5 -- уменьшение частицы

sparkle_config.gravity = true		-- гравитация?
sparkle_config.gravity_acc = 50	-- ускорение гравитации

sparkle_config.coords = -- список координат из которых вылетают искры
		{ {x=268, y=196},  {x=251, y=212}, {x=244, y=232}, {x=244, y=250}, {x=246, y=266},
		  {x=531, y=196},  {x=549, y=212}, {x=557, y=232}, {x=557, y=250}, {x=554, y=266}}


-- РЕАЛИЗАЦИЯ --------------------------------------------------------------------------------

function CreateScarabSparkleEffect(window)
	sparkle_config.paused = true

	local count = table.getn(sparkle_config.coords)
	while count>0 do
		CreatePointSparkleEffect(window, "scarabsparkle"..count, 
			CFloatVector(sparkle_config.coords[count].x, sparkle_config.coords[count].y), sparkle_config.color)
		count = count - 1
	end
end

function PauseScarabSparkleEffect(window, pause)
--[[	local count = 1
	while true do
		local w = ConvertToCParticleWidget(window:GetWidget("scarabsparkle"..count))
		if not w then break end
		if pause then w:Stop() else w:Start() end
		count = count + 1
	end]]
	sparkle_config.paused = pause
end

function CreatePointSparkleEffect(hostwidget, effectid, coord, color)
	local nodeemitter = CLuaEmitter(g_Lua, "sparkle_emitter", sparkle_config.emit_timeout)
	local pnode = CParticleNode(nodeemitter, true)
	
	pnode:SetEternal(true)
	pnode:SetPosition(coord)
	pnode:SetColor(CColor(color.mRed, color.mGreen, color.mBlue, 0))
	
	local widget = CParticleWidget(effectid, 0)
	widget:AddParticleNode(pnode)
	widget:Start()
	hostwidget:AddWidget(widget)
end

function sparkle_emitter(pnode)
	if sparkle_config.paused or pnode:GetParticleNumber() > sparkle_config.max_emits then return end
	
	local p = CParticleNode()
	p:SetLifetime(sparkle_config.lifetime)
	p:SetPosition(pnode:GetPosition())
	p:SetColor(pnode:GetColor())
	p:SetImage(sparkle_config.image)
	p:SetSize(sparkle_config.size)
	
	angle = (6.283)*(math.random())

	local uf = CFadeAction(0, 255)
	uf:StartActionTime(0)
	uf:EndActionTime(50)
	p:AddAction(uf)
	
	local df = CFadeAction(255, 0)
	df:StartActionTime(50)
	df:EndActionTime(sparkle_config.lifetime)
	p:AddAction(df)

	local rot = sparkle_config.rotation_speed * 3.1415 / 180
	if math.random(2)==1 then rot = -rot end
	local r = CRotateAction(rot)
	p:AddAction(r)
		
	local move = CMoveAction()
	move:StartActionTime(0)
	move:EndActionTime(sparkle_config.lifetime)
	p:AddAction(move)		

	local s = CScaleAction(1, sparkle_config.min_scale)
	s:StartActionTime(0)
	s:EndActionTime(sparkle_config.lifetime)
	p:AddAction(s)

	local dx = math.cos(angle)-math.sin(angle)
	local dy = math.sin(angle)+math.cos(angle)

	local speed = sparkle_config.speed + math.random(sparkle_config.speed_delta*2) - sparkle_config.speed_delta
		
	p:SetSpeed(CFloatVector(speed * dx, speed * dy))
	if sparkle_config.gravity then p:SetAccel(CFloatVector(0, sparkle_config.gravity_acc)) end
	
	pnode:InsertParticle(p)
end
