-- events 

-- strings for localization:
--
T_TOO_MANY_PROFILES	= Localize ("Too many profiles. Please delete a profile to create a new one.");
T_NOTE							= Localize ("Note");


function OnLoad ()
    CacheSound ("ui/sfx/panel_move.ogg");
end;


function UpdateProfileButtons ()
	-- initialize the profile buttons with actual profile content.
	-- the active profile is marked with a button that is disabled
	-- (button.bm_disabled graphic is designed that way).
	
	current_profile = GetProfile ();
		
	i = 0;
	while (i < 5) do
		exists = SetProfile (i);
		-- button names are "0", "1", "2", ... so we can easily concat "2:visible" and so on
		SetProperty (i .. ":visible", exists);
		SetProperty (i .. ":active", 1);
		SetProperty (i .. ":button.text", GetProfileStat ("name"));
		i = i + 1;
	end;
	SetProfile (current_profile);
	
	-- it's already selected, let's mark it by disabling it
	SetProperty (current_profile .. ":active", 0);
end;

function OnEnter ()
	SaveProfiles ();
	PlaySound ("ui/sfx/panel_move.ogg");
	UpdateProfileButtons ();
end;

function OnLeave ()
end;


function OnClick (name)

	
	Print ("OnClick " .. name .. "\n");
	
	if (name == "Ok") then
	    PlaySound ("ui/sfx/panel_move.ogg");
		SaveProfiles ();
		PopScreen ("Profiles");
		return;
	end;
	if (name == "Cancel") then
	    PlaySound ("ui/sfx/panel_move.ogg");
		LoadProfiles ();
		PopScreen ("Profiles");
		return;
	end;
	
	if (name == "Stats") then
		PushScreen ("Stats");
		return;
	end;
	
	if (name == "New") then
		if (GetNumberOfProfiles () >= 5) then
			SetProperty ("/InfoPopup/title:label.text", T_NOTE);
			SetProperty ("/InfoPopup/text:label.text", T_TOO_MANY_PROFILES);
			PushScreen ("InfoPopup");
		else
			PushScreen ("NewProfile");
		end;
		return;
	end;
	
	if (name == "Delete") then
		PushScreen ("DeleteProfile");
		return;
	end;
	
	-- need the string libraries here, otherwise it tries to se the profile to for ex. "panel"
	if (string.find(name, '%d')) then
	
		Print ("Setting profile " .. name .. "..\n");	
		SetProfile (name);
	end;
		
	UpdateProfileButtons ();

end;


function OnUpdate (tdelta)

	akey = GetActiveScreenAnimKey ();

	trans = math.sin (0.5*3.1415926535 * GetActiveScreenTransPhase ());
	SetProperty ("panel:position_offset.y", (1-trans) * 500);
	SetProperty ("panel:alpha", trans);
	SetProperty ("fader:alpha", trans + trans * 0.05 * math.sin (2*3.141592*akey));
	
	UpdateProfileButtons ();
	
	if (IsScreenInStack ("NewProfile") == false and GetProfileStat ("name") == "") then
		PushScreen ("NewProfile");
	end;		
end;

function OnDraw ()

end;
