--=============================================================================
-- Global helper functions
--=============================================================================


--=============================================================================
-- Loading Scene
--=============================================================================
loadingScene = {}
loadingScene.background = nil
loadingScene.ending = false
loadingScene.lastDuration = 0

function loadingScene.startAnimation(loading)
	loadingScene.background = loading:child("BACKGROUND")

	--for i=1, 5, 1 do
		--loadingScene:addStarRandom()
	--end

	loadingScene.background:doEvery(800, loadingScene.addStarTop)
end

function loadingScene:addStarTop()
	if (loadingScene.ending) then
		return nil
	end
	
	loadingScene:addStar(-100)
	return math.random(700, 1200)
end

function loadingScene:addStarRandom()
	loadingScene:addStar(math.random(-100, 700))
end

function loadingScene:addStar(startY)
	local startX = math.random(-20, 820)
	local star = loadingScene.background:newChildSprite({x=startX, y=startY, image="LOADING_STAR_".. math.random(0, 7), section="preloading"})	

	star:setAnchorPoint("center")
	
	local startAlpha = 1
	local endAlpha = 0
	if (math.random(1, 2) == 1) then
		startAlpha = 0
		endAlpha = 1
	end
	star:setAlpha(startAlpha)
	
	local duration = math.random(6000, 8000) * (1 - ((startY + 100) / 800))	
	if (duration > loadingScene.lastDuration) then
		loadingScene.lastDuration = duration
	end	

	local rotPerSec = math.random(5, 25) / 100
	star:doOften(function(s, time)
		s:setRotation(s:rotation() + ((time / 1000) * rotPerSec * (2 * math.pi)))
	end)
	
	star:setScale(math.random(6, 10) / 10)

	star:animate(
		{x=startX, y=700, alpha=endAlpha, duration=duration},
		{call=function() star:setObsolete() end}
	)
end

function loadingScene:endAnimationSelection()
	loadingScene.ending = true
	local duration = math.max(3000, loadingScene.lastDuration)
	loadingScene.background:animate(
		{delay=duration},
		{command="continue", target=scene}
	)
end

function loadingScene:endAnimationSnowflake()
	loadingScene.ending = true
	local duration = math.max(4000, loadingScene.lastDuration)
	loadingScene.background:animate(
		{delay=500},
		{command="start_snowflake", target=scene},
		{delay=duration-500},
		{command="continue", target=scene}
	)
end
