function credits_window_generic_handler(window, action, widget)
	standard_generic_handler(widnow, action, widget)

	if action=='pressed' then
		if widget:GetId()=="close" then
			window:Close()
		elseif widget:GetId()=="e-mail" then
			ShellExecute("mailto:contaсts@stargaze-int.com?subject=\""..string_table():GetString(231).."\"", "")
		end
	end
end

-------------------------------------------------------------------------------------------------

local function help_change_page(window, page1)
	local w = ConvertToCButtonWidget(window:GetWidget("page1"))
	if w then w:DisableButton(page1) end
	local w = ConvertToCButtonWidget(window:GetWidget("page2"))
	if w then w:DisableButton(not page1) end

	local w = window:GetWidget("title1")
	if w then w:Hide(not page1) end
	local w = window:GetWidget("title2")
	if w then w:Hide(page1) end

	local count = 1
	while count<10 do
		local w = window:GetWidget("flash1"..count)
		if w then 
			w:Hide(not page1) 
			w:Disable(not page1)
		end
		local w = window:GetWidget("flash2"..count)
		if w then 
			w:Hide(page1) 
			w:Disable(page1)
		end
		local w = window:GetWidget("image1"..count)
		if w then w:Hide(not page1) end
		local w = window:GetWidget("image2"..count)
		if w then w:Hide(page1) end

		count = count + 1
	end
end

-------------------------------------------------------------------------------------------------

function help_on_load_template(window)
	help_change_page(window, true)
end

-------------------------------------------------------------------------------------------------

function help_window_generic_handler(window, action, widget)
	standard_generic_handler(widnow, action, widget)

	if action=='pressed' then
		if widget:GetId()=="close" then
			pause_game(false)
			if g_Game then g_Game:Hide(false) end
			window:Close()
		elseif widget:GetId()=="page1" then
			 help_change_page(window, true)
		elseif widget:GetId()=="page2" then
			 help_change_page(window, false)
		elseif widget:GetId()=="credits" then
			local credits = CLuaWindow(g_Loader:GetTemplate("credits_window"), g_Lua)
			credits:MoveTo(
				(window:GetRect().mWidth - credits:GetRect().mWidth)/2, 
				(window:GetRect().mHeight - credits:GetRect().mHeight)/2)
			window:AddWidget(credits)
		end
	end
end

-------------------------------------------------------------------------------------------------

local create_profile_dialog = nil

-------------------------------------------------------------------------------------------------

function mainmenu_state_on_init(window)
	collectgarbage(0)
	PurgeShapes()
	default_state_init(window)
	g_MainMenu = ConvertToCLuaWindow(window:GetWidget("mainmenu"))
	AddLogos(g_MainMenu, "mainmenu_logos")

	--update_gods(ConvertToCImageWidget(g_MainMenu:GetWidget("god1")))
end

-------------------------------------------------------------------------------------------------

function mainmenu_on_init(window)
	log("mainmenu_on_init")
	if not trial_controller():IsRegistered() then
		local time = math.ceil(trial_controller():GetTimeLeft()/60000)
		if time>60 then time = 60 end
		local w = ConvertToCLabelWidget(window:GetWidget("time_left"))
		w:SetText(string.format(w:GetText(), time))
		w:Hide(false)
		
		local w = window:GetWidget("register")
		w:Hide(false)
		w:Disable(false)
	else
		local w = window:GetWidget("register")
		local dy = - w:GetRect().mY + window:GetWidget("records"):GetRect().mY

		local w = window:GetWidget("records")
		w:MoveTo(w:GetRect().mX, w:GetRect().mY - dy)
		local w = window:GetWidget("options")
		w:MoveTo(w:GetRect().mX, w:GetRect().mY - dy)
		local w = window:GetWidget("help_mainmenu")
		w:MoveTo(w:GetRect().mX, w:GetRect().mY - dy)
		local w = window:GetWidget("quit")
		w:MoveTo(w:GetRect().mX, w:GetRect().mY - dy)

	end

	init_mainmenu_music()

	CreateScarabSparkleEffect(window)

	on_profile_changed(window)
end

-------------------------------------------------------------------------------------------------

function on_profile_changed(window)
	local profile = profile_manager():GetCurrentProfile()	
	if not profile then return end

	local god = 4
	while god>0 do
		local godimage = ConvertToCImageWidget(window:GetWidget("god"..god))
		godimage:SetImage(profile:GetGodImage(god-1))
		if godimage:GetRect().mX < 400 then godimage:GetImage():RemFlags(CImage.mirrored)
		else godimage:GetImage():AddFlags(CImage.mirrored) end
		godimage:GetImage():SetTime(0)
		godimage:GetImage():AddFlags(CImage.stop_animation)
		godimage:GetImage():RemFlags(CImage.backward_animation)

		local glow = ConvertToCGlowGodWidget(window:GetWidget("godglow"..god))
		glow:ClearWidgets()
		glow:DisableGlow(false)
		
		god = god - 1
	end

	update_gods_flash(window)
	
	local greet = ConvertToCLabelWidget(window:GetWidget("greet"))
	if not greet then return end

	if not profile_manager():GetCurrentProfile() then greet:SetText(string_table():GetString(41))
	else 
		greet:SetText(string.format(string_table():GetString(42), profile_manager():GetCurrentProfile():GetName())) 
	end
end

-------------------------------------------------------------------------------------------------

function mainmenu_on_key_down(key, state)
	if key==13 then
		-- Return
		start_game_state()
	elseif key==27 then
		-- Escape
		quit_game()
	end
end

-------------------------------------------------------------------------------------------------

local shutter = false

function mainmenu_update(window, dt)
	if (not shutter) and (not profile_manager():GetCurrentProfile()) then
		shutter = true

		local dialog = create_profile_dialog(true, string_table():GetString(98))
		window:AddWidget(dialog)
		dialog:WaitForResult(true)
		local name = ConvertToCEditWidget(dialog:GetWidget("name"))
		if name then
			name = name:GetText()
			profile_manager():CreateProfile(name)
			profile_manager():SetCurrentProfile(name)
			local profile = profile_manager():GetCurrentProfile()

			local god_list = {"image_gui_re", "image_gui_hnum", "image_gui_hathor", "image_gui_neit"}
			local god = 4
			while god>0 do
				profile:SetGodImage(god-1, god_list[god])
				god = god - 1
			end
			on_profile_changed(window)
		end
	else
		shutter = true
	end

	g_Globals.value_chaged_timer = g_Globals.value_chaged_timer - dt
	if g_Globals.value_chaged_timer<0 then g_Globals.value_chaged_timer = 0 end

	g_Loader:UpdateFileChanges()
	g_Lua:CheckFileChanges()
	string_table():CheckChanges()
end

-------------------------------------------------------------------------------------------------

function mainmenu_generic_handler(window, action, widget)
	standard_generic_handler(window, action, widget)

	if action=="pressed" then OnLogoPress(widget) end

	if action=='over' then 
		if widget:GetId()=="godglow1" or widget:GetId()=="godglow2"
		or widget:GetId()=="godglow3" or widget:GetId()=="godglow4" then
			play_sound("sound_gods_over")
		else
			play_sound("sound_gui_sound") 
		end
	end

	if action=='pressed' then
		if widget:GetId()=='play' then
			if not trial_controller():IsRegistered() and trial_controller():GetTimeLeft()<=0 then
				pause_game(true)
				local res = dialog_do_modal(window, "time_expired_dialog")
				pause_game(false)
				if res==1 then
					ShellExecute("registrator.exe", "1 1")
					quit_game()
				end
				return
			end

			if profile_manager():GetCurrentProfile():IsSaved() then
				local res = dialog_do_modal(window, "new_or_continue_game_dialog")
				if res==0 then return end
				if res==1 then
					load_game()
					return
				end
			end
			start_game_state()
		elseif widget:GetId()=='quit' then
			local res = dialog_do_modal(window, "exit_dialog")
			if res~=-1 then return end
			if not trial_controller():IsRegistered() then
				local w = CLuaWindow(g_Loader:GetTemplate("nag_window"), g_Lua)
				window:AddWidget(w)
			else
				quit_game()
			end
			
		elseif widget:GetId()=='records' then
			local w = CLuaWindow(g_Loader:GetTemplate("records_window"), g_Lua)
			window:AddWidget(w)
		elseif widget:GetId()=='test' then
			g_WidgetAgent:AddWidget(CLuaWindow(g_Loader:GetTemplate("gui_test_window"), g_Lua))
		elseif widget:GetId()=='options' then
			show_menu_options(window)
		elseif widget:GetId()=='change_profile' then
			local w = CLuaWindow(g_Loader:GetTemplate("profile_window"), g_Lua)
			w:MoveTo( (window:GetRect().mWidth - w:GetRect().mWidth)/2, (window:GetRect().mHeight - w:GetRect().mHeight)/2)
			window:AddWidget(w)
		elseif widget:GetId()=='help_mainmenu' then
			show_help(g_MainMenu)
		elseif widget:GetId()=="register" then
			ShellExecute("registrator.exe", "1 0")
			quit_game()
		elseif widget:GetId()=="godglow1" or widget:GetId()=="godglow2"
		or widget:GetId()=="godglow3" or widget:GetId()=="godglow4" then
			if ConvertToCGlowGodWidget(widget):IsGlowDisabled() then return end
			local num = string.char(string.byte(widget:GetId(), string.len(widget:GetId())))
			CreateGodChangeEffect(ConvertToCImageWidget(window:GetWidget("god"..num)), 
				ConvertToCGlowGodWidget(widget))
		end
	end
end

-------------------------------------------------------------------------------------------------

local function show_options_base(window)
	if not trial_controller():IsRegistered() then
		local w = window:GetWidget("register")
		w:Hide(false)
		w:Disable(false)
		local deltay = window:GetRect().mHeight - (window:GetWidget("menu"):GetRect().mY + window:GetWidget("menu"):GetRect().mHeight)
		window:Resize(window:GetRect().mWidth, w:GetRect().mY + w:GetRect().mHeight + deltay)
	end
end

-------------------------------------------------------------------------------------------------

function show_game_options(parent)
	if g_Game then
		pause_game(true)
	end
	local options = CLuaWindow(g_Loader:GetTemplate("options_window"), g_Lua)

	show_options_base(options)

	local w = options:GetWidget("ok")
	if w then 
		w:Hide(true)
		w:Disable(true)
	end
	local w = options:GetWidget("cancel")
	if w then 
		w:Hide(true)
		w:Disable(true)
	end

	local w = options:GetWidget("title_menu")
	if w then
		w:Hide(true)
	end

	parent:AddWidget(options)
end

-------------------------------------------------------------------------------------------------

function show_menu_options(parent)
	local options = CLuaWindow(g_Loader:GetTemplate("options_window"), g_Lua)

	show_options_base(options)

	local w = options:GetWidget("return")
	if w then 
		w:Hide(true)
		w:Disable(true)
	end
	local w = options:GetWidget("menu")
	if w then 
		w:Hide(true)
		w:Disable(true)
	end

	local w = options:GetWidget("title_game")
	if w then
		w:Hide(true)
	end

	parent:AddWidget(options)
end

-------------------------------------------------------------------------------------------------

function options_on_load_template(options)
	g_Globals.options = {}

	g_Globals.options.sfx_vol = g_App:GetSfxVolume()
	g_Globals.options.music_vol = g_App:GetMusicVolume()

	g_Globals.options.windowed = g_App.mIsWindowed
	g_Globals.options.is3d = g_App:Is3DAccelerated()
	g_Globals.options.custom_cursor = g_App.mCustomCursorsEnabled

	local w = ConvertToCSliderWidget(options:GetWidget("sound"))
	if w then
		w:SetValue(g_Globals.options.sfx_vol)
	end
	local w = ConvertToCSliderWidget(options:GetWidget("music"))
	if w then
		w:SetValue(g_Globals.options.music_vol)
	end

	local w = ConvertToCCheckboxWidget(options:GetWidget("fullscreen"))
	if w then
		w:Check(not g_Globals.options.windowed)
	end
	local w = ConvertToCCheckboxWidget(options:GetWidget("hardware"))
	if w then
		w:Check(g_Globals.options.is3d)
	end
	local w = ConvertToCCheckboxWidget(options:GetWidget("cursors"))
	if w then
		w:Check(g_Globals.options.custom_cursor)
	end
	local w = ConvertToCCheckboxWidget(options:GetWidget("hints"))
	if w then
		w:Check(profile_manager():GetCurrentProfile():IsHintsEnabled())
	end
end

-------------------------------------------------------------------------------------------------

function options_window_generic_handler(window, action, widget)
	if  action=="pressed" then
		if widget:GetId()=="ok" then
			close_options(window, true)
		elseif widget:GetId()=="cancel" then
			close_options(window, false)
		elseif widget:GetId()=="menu" then
			close_options(window, true)
			start_mainmenu_state()
		elseif widget:GetId()=="return" then
			close_options(window, true)
		elseif widget:GetId()=="register" then
			ShellExecute("registrator.exe", "1 1")
			quit_game()
		end
	end

	if action=="value_changed" and window:GetParent() then
		if widget:GetId()=="music" then
			g_App:SetMusicVolume(ConvertToCSliderWidget(widget):GetValue())
		elseif widget:GetId()=="sound" then
			g_App:SetSfxVolume(ConvertToCSliderWidget(widget):GetValue())
			if g_Globals.value_chaged_timer <=0 then
				play_sound("sound_gui_sound")
				g_Globals.value_chaged_timer = 400
			end

		end
	end

	if action=="checked" then
		widget = ConvertToCCheckboxWidget(widget)

		if widget:GetId()=="hardware" then
			
			if widget:IsChecked() then
				if not g_App:Is3DAccelerationSupported() then
					dialog_do_modal(window, "hardware_not_supported_dialog")
					widget:Check(false)
				end
			end
		elseif widget:GetId()=="fullscreen" then
			if not widget:IsChecked() and g_App.mForceFullscreen then
				dialog_do_modal(window, "no_window_mode_dialog")
				widget:Check(true)
			end
		end
	end

	standard_generic_handler(widnow, action, widget)

end

-------------------------------------------------------------------------------------------------

function close_options(options, save)
	if g_Game then
		pause_game(false)
	end

	if save then
		local windowed = ConvertToCCheckboxWidget(options:GetWidget("fullscreen"))
		local is3d = ConvertToCCheckboxWidget(options:GetWidget("hardware"))
		if windowed and is3d then
			g_App:SwitchScreenMode(not windowed:IsChecked(), is3d:IsChecked(), false)
		end

		local cursors = ConvertToCCheckboxWidget(options:GetWidget("cursors"))
		if cursors then g_App:EnableCustomCursors(cursors:IsChecked()) end

		profile_manager():GetCurrentProfile():EnableHints(ConvertToCCheckboxWidget(options:GetWidget("hints")):IsChecked())
	else
		g_App:SetMusicVolume(g_Globals.options.music_vol)
		g_App:SetSfxVolume(g_Globals.options.sfx_vol)
	end

	options:Close()
end

-------------------------------------------------------------------------------------------------
local last_profile = nil

function profile_window_on_load_template(window)
	local w = ConvertToCListWidget(window:GetWidget("profiles"))
	if not w then return end

	w:AddLine(string_table():GetString(65))
	local size = profile_manager():EnumProfiles()
	local i = 0
	while i<size do
		w:AddLine(profile_manager():GetProfile(i):GetName())
		i = i + 1
	end

	w:SelectLine(w:FindLine(profile_manager():GetCurrentProfile():GetName()))
	last_profile = profile_manager():GetCurrentProfile()
end

-------------------------------------------------------------------------------------------------

function create_profile(window, widget, hide_cancel, text)
	local res = -1
	widget = ConvertToCListWidget(widget)

	local dialog = create_profile_dialog(hide_cancel, text)
	dialog:MoveTo( (window:GetRect().mWidth - dialog:GetRect().mWidth)/2, (window:GetRect().mHeight - dialog:GetRect().mHeight)/2 )
	window:AddWidget( dialog )
	res = dialog:WaitForResult(true)
	if res==0 then
		local name = ConvertToCEditWidget(dialog:GetWidget("name"))
		if name then
			name = name:GetText()
			profile_manager():CreateProfile(name)
			profile_manager():SetCurrentProfile(name)
			local profile = profile_manager():GetCurrentProfile()

			local god_list = {"image_gui_re", "image_gui_hnum", "image_gui_hathor", "image_gui_neit"}
			local god = 4
			while god>0 do
				profile:SetGodImage(god-1, god_list[god])
				god = god - 1
			end
		end
	else
		widget:SelectLine(widget:FindLine(profile_manager():GetCurrentProfile():GetName()))
	end
	return res
end

-------------------------------------------------------------------------------------------------

function profile_window_generic_handler(window, action, widget)
	standard_generic_handler(window, action, widget)

	if action=="pressed" then
		if widget:GetId()=="ok" then
			window:Close()
			on_profile_changed(g_MainMenu)
		elseif widget:GetId()=="cancel" then
			if last_profile then profile_manager():SetCurrentProfile(last_profile:GetName()) end
			window:Close()
			on_profile_changed(g_MainMenu)
		elseif widget:GetId()=="rename" then
			local dialog = rename_profile_dialog(profile_manager():GetCurrentProfile():GetName())
			dialog:MoveTo( (window:GetRect().mWidth - dialog:GetRect().mWidth)/2, (window:GetRect().mHeight - dialog:GetRect().mHeight)/2 )
			window:AddWidget(dialog)
			local res = dialog:WaitForResult(true)
			if res==0 then
				local name = ConvertToCEditWidget(dialog:GetWidget("name"))
				if name then
					name = name:GetText()
					local line = profile_manager():GetCurrentProfile():GetName()

					local list  = ConvertToCListWidget(window:GetWidget("profiles"))
					if list then
						line = list:FindLine(line)
						list:SetLine(line, name)
					end
					profile_manager():GetCurrentProfile():SetName(name)
				end
			end		
			on_profile_changed(g_MainMenu)
		elseif widget:GetId()=="delete" then
			local list  = ConvertToCListWidget(window:GetWidget("profiles"))
			if list then
				local dlg = create_dialog(window, "profile_delete_dialog")
				local text = ConvertToCLabelWidget(dlg:GetWidget("text"))
				if text then
					text:SetText(string.format(text:GetText(), list:GetLine(list:SelectedLine())))
				end
				local res = dlg:WaitForResult(true)
				if res==1 then return end

				if last_profile and last_profile:GetName()==list:GetLine(list:SelectedLine()) then
					last_profile = nil
				end
				profile_manager():DeleteProfile(list:GetLine(list:SelectedLine()))
				list:RemoveLine(list:SelectedLine())
				profile_manager():SetCurrentProfile(list:GetLine(list:SelectedLine()))
				if not last_profile then last_profile = profile_manager():GetCurrentProfile() end
			end
			on_profile_changed(g_MainMenu)
		end
	elseif action=="line_selected" then
		widget = ConvertToCListWidget(widget)
		if widget:SelectedLine()==0 then 
			local hide_cancel = nil
			local text = nil
			if profile_manager():EnumProfiles()==0 then
				hide_cancel = true
				text=string_table():GetString(98)
			end
			if create_profile(window, widget, hide_cancel, text)==0 then 
				window:Close() 
			end 
		else profile_manager():SetCurrentProfile(widget:GetLine(widget:SelectedLine())) end
		on_profile_changed(g_MainMenu)
	end
end


-------------------------------------------------------------------------------------------------

function rename_profile_dialog(text)
	local dialog = CLuaWindow(g_Loader:GetTemplate("rename_profile_window"), g_Lua)

	if text then
		local w = ConvertToCEditWidget(dialog:GetWidget("name"))
		if w then
			w:SetText(text)
			w:SelectText(0, 1000)
		end
	else
		local w = ConvertToCButtonWidget(dialog:GetWidget("ok"))
		if w then w:DisableButton(true) end
	end

	return dialog
end

-------------------------------------------------------------------------------------------------


function create_profile_dialog(hide_cancel, text)
	local dialog = CLuaWindow(g_Loader:GetTemplate("create_profile_window"), g_Lua)

	if hide_cancel then
		local w = ConvertToCButtonWidget(dialog:GetWidget("cancel"))
		if w then 
			w:Hide(true)
			w:Disable(true)
		end
		local ok = ConvertToCButtonWidget(dialog:GetWidget("ok"))
		if ok then
			ok:MoveTo((dialog:GetRect().mWidth - ok:GetRect().mWidth)/2, ok:GetRect().mY)
		end

	end

	if text then
		local w = ConvertToCEditWidget(dialog:GetWidget("name"))
		if w then
			w:SetText(text)
			w:SelectText(0, 1000)
		end
	else
		local w = ConvertToCButtonWidget(dialog:GetWidget("ok"))
		if w then w:DisableButton(true) end
	end

	return dialog
end

------------------------------------------------------------------------------------------------

-- отключает обработку клавиш в окнах создания и редактирования пользователя
local generic_profile_key_shutter = false

function base_profile_window_generic_handler(window, action, widget)
	standard_generic_handler(window, action, widget)

	if action=="text_changed" then
		if ConvertToCEditWidget(widget):GetText()=="" then
			ConvertToCButtonWidget(window:GetWidget("ok")):DisableButton(true)
		else
			ConvertToCButtonWidget(window:GetWidget("ok")):DisableButton(false)
		end
	end
end

local function generic_profile_apply_changes(window, rename)
	local name = ConvertToCEditWidget(window:GetWidget("name"))
	if profile_manager():GetProfile(name:GetText()) 
	and (profile_manager():GetCurrentProfile():GetName()~=name:GetText() or not rename) then 
		generic_profile_key_shutter = true
		dialog_do_modal(window, "profile_name_conflict_dialog") 
		generic_profile_key_shutter = false
		return 
	end
	window:ReturnResult(0)
end

function create_profile_window_generic_handler(window, action, widget)
	base_profile_window_generic_handler(window, action, widget)
	if action=="pressed" then
		if widget:GetId()=="ok" then
--[[			local name = ConvertToCEditWidget(window:GetWidget("name"))
			if profile_manager():GetProfile(name:GetText()) then 
				dialog_do_modal(window, "profile_name_conflict_dialog") 
				return 
			end
			window:ReturnResult(0)]]
			generic_profile_apply_changes(window)
		elseif widget:GetId()=="cancel" then
			window:ReturnResult(-1)
		end
	end
end

function rename_profile_window_generic_handler(window, action, widget)
	base_profile_window_generic_handler(window, action, widget)
	if action=="pressed" then
		if widget:GetId()=="ok" then
--[[			local name = ConvertToCEditWidget(window:GetWidget("name"))
			if profile_manager():GetProfile(name:GetText()) and profile_manager():GetCurrentProfile():GetName()~=name:GetText() then 
				dialog_do_modal(window, "profile_name_conflict_dialog") 
				return 
			end
			window:ReturnResult(0)]]
			generic_profile_apply_changes(window, true)
		elseif widget:GetId()=="cancel" then
			window:ReturnResult(-1)
		end
	end
end

function create_profile_on_key(window, key, state)
	if generic_profile_key_shutter then return end
	if key==13 then
		generic_profile_apply_changes(window)
	end
end

function rename_profile_on_key(window, key, state)
	if generic_profile_key_shutter then return end
	if key==13 then
		generic_profile_apply_changes(window, true)
	end
end

-------------------------------------------------------------------------------------------------

local g_RecordsCached = false
local g_CurrentRecordTable = "local"
local gems_template = "x%i"

local function show_records_from(window, start)

	local record_table = 0 -- локальная таблица
	if g_CurrentRecordTable=="daily" then record_table = 1
	elseif g_CurrentRecordTable=="global" then record_table = 2 end

	local base_score = start
	local name = profile_manager():GetCurrentProfile():GetName()

	local ids = {"rank", "name", "level", "gems", "score"}
	local score = 0
	while score<=9 do
		local record = records_manager():GetRecord(record_table, base_score + score)

		local w = ConvertToCImageWidget(window:GetWidget( "row"..(score+1) ))
		if (not record.generated) and record.name==name then		
			w:SetImage("image_gui_records_row_glow")
		else
			w:SetImage("image_gui_records_row")
		end

		local label = table.getn(ids)
		while label>0 do
			local id = ids[label]
			local w = ConvertToCLabelWidget(window:GetWidget(score..id))
			if id=="rank" then
				w:SetText((base_score + score + 1).."")
			elseif id=="name" then
				w:SetText(record.name)
			elseif id=="level" then
				w:SetText(record.level.."")
			elseif id=="gems" then
				w:SetText(string.format(gems_template, record.gems))
			elseif id=="score" then
				w:SetText(record.score.."")
			end
			label = label - 1
		end
		
		local sat = record.satisfaction
		local eye = 1
		while eye<=5 do
			local w = ConvertToCImageWidget(window:GetWidget(score.."eye"..eye))
			if sat>=2 then	
				w:SetImage("image_game_gui_reeye")
			elseif sat==1 then
				w:SetImage("image_game_gui_reeye_half")
			else
				w:SetImage("image_game_gui_reeye_gray")
			end
			eye = eye + 1
			sat = sat - 2
		end
		score = score + 1
	end

end

local function show_records(window, records)
	if records~="local" and not g_RecordsCached then
		records_manager():UpdateOnlineScores()
		local res = dialog_do_modal(window, "connecting_dialog")
		if res==-1 then
			play_sound("sound_connection_error")
			dialog_do_modal(window, "connection_failed_dialog")
			return
		elseif res==0 then
			records_manager():AbortOnlineUpdate()
			return
		end
		g_RecordsCached = true
	end

	g_CurrentRecordTable = records

	local norm_layer = 20
	local top_layer = 25

	local bookmarks = {"local", "daily", "global"}
	local count = table.getn(bookmarks)

	while count >0 do
		local w = ConvertToCButtonWidget(window:GetWidget(bookmarks[count]))
		if w then
			w:DisableButton(records==w:GetId())
			if records==w:GetId() then w:SetLayer(top_layer )
			else w:SetLayer(norm_layer) end
		end
		count = count - 1
	end

	local w = ConvertToCButtonWidget(window:GetWidget("clear"))
	w:DisableButton(records~="local")

	local scroll = ConvertToCScrollWidget(window:GetWidget("scroll"))
	scroll:Disable(records=="local")
	scroll:Hide(records=="local")
	local max = CRecords.max_local
	if records=="daily" then max = CRecords.max_daily
	elseif records=="global" then max = CRecords.max_global end
	scroll:SetMaxValue(max)
	scroll:SetPageSize(10)

	local record_table = 0 -- локальная таблица
	if g_CurrentRecordTable=="daily" then record_table = 1
	elseif g_CurrentRecordTable=="global" then record_table = 2 end

	local name = profile_manager():GetCurrentProfile():GetName()
	local record = nil
	local score = 0
	while score<max do
		record = records_manager():GetRecord(record_table, score)
		if not record.generated and record.name==name then break end
		score = score + 1
	end

	if score>=max then score = 0 end
	scroll:SetValue(score)	
end

-------------------------------------------------------------------------------------------------

function records_window_on_load_template(window)

	g_RecordsCached  = false

	local deltay = 41
	local deye = 5

	local labels = {"records_rank_label", "records_name_label", "records_level_label", "records_gems_label", "records_score_label"}
	local ids = {"rank", "name", "level", "gems", "score"}
	local score = 0
	while score<=9 do
		local label = table.getn(labels)
		while label>0 do
			local w = CLabelWidget(g_Loader:GetTemplate(labels[label]))
			w:SetId(score..ids[label])
			w:MoveTo(w:GetRect().mX, w:GetRect().mY + score*deltay)
			window:AddWidget(w)
			label = label - 1
		end
		
		local eye = 5
		while eye>0 do
			local w = CImageWidget(g_Loader:GetTemplate("records_eye_image"))
			w:SetId(score.."eye"..eye)
			w:MoveTo(w:GetRect().mX + (w:GetRect().mWidth + deye)*(eye-1), w:GetRect().mY + score*deltay)
			window:AddWidget(w)
			eye = eye - 1
		end
		score = score + 1
	end

	show_records(window, "local")

	if not records_manager():IsOnlineAvailable() then
		local w = window:GetWidget("daily")
		w:Disable(true)
		w:Hide(true)
		local w = window:GetWidget("global")
		w:Disable(true)
		w:Hide(true)
	end
end

-------------------------------------------------------------------------------------------------

function records_window_generic_handler(window, action, widget)
	standard_generic_handler(window, action, handler)
	if action=="pressed" then
		if widget:GetId()=="local" or widget:GetId()=="daily" or widget:GetId()=="global" then 
			show_records(window, widget:GetId())
		elseif widget:GetId()=="close" then
			window:Close()
		elseif widget:GetId()=="clear" then
			if dialog_do_modal(window, "clear_records_dialog")==1 then return end
			records_manager():ClearRecords()
			show_records(window, "local")
		end
	elseif action=="value_changed" then
		if widget:GetId()=="scroll" then
--			show_records(window, g_CurrentRecordTable)
			show_records_from( window, math.floor( ConvertToCScrollWidget(widget):GetValue() ) )
		end
	end
end
