main_menu = {}

main_menu.name_title_string_id = _T("$42")
main_menu.simple_title_string_id = _T("$41")
main_menu.main_background_widget = nil
main_menu.update_game_suggested = false

main_menu.small_back_grounds = {}
main_menu.small_back_grounds["not_button"] = {}
main_menu.small_back_grounds["not_button"].widget = nil
main_menu.small_back_grounds["not_button"].widget_id = _T("small_background_main")
main_menu.small_back_grounds["not_button"].offset_x = 315
main_menu.small_back_grounds["not_button"].offset_y = 175

main_menu.small_back_grounds["ancient_button"] = {}
main_menu.small_back_grounds["ancient_button"].widget = nil
main_menu.small_back_grounds["ancient_button"].widget_id = _T("small_background_ancient")
main_menu.small_back_grounds["ancient_button"].offset_x = -130
main_menu.small_back_grounds["ancient_button"].offset_y = 180

main_menu.small_back_grounds["original_button"] = {}
main_menu.small_back_grounds["original_button"].widget = nil
main_menu.small_back_grounds["original_button"].widget_id = _T("small_background_original")
main_menu.small_back_grounds["original_button"].offset_x = 300
main_menu.small_back_grounds["original_button"].offset_y = 150

main_menu.small_back_grounds["hi_tech_button"] = {}
main_menu.small_back_grounds["hi_tech_button"].widget = nil
main_menu.small_back_grounds["hi_tech_button"].widget_id = _T("small_background_hi_tech")
main_menu.small_back_grounds["hi_tech_button"].offset_x = 300
main_menu.small_back_grounds["hi_tech_button"].offset_y = 100

main_menu.small_back_grounds["planets_button"] = {}
main_menu.small_back_grounds["planets_button"].widget = nil
main_menu.small_back_grounds["planets_button"].widget_id = _T("small_background_planets")
main_menu.small_back_grounds["planets_button"].offset_x = 300
main_menu.small_back_grounds["planets_button"].offset_y = 120

main_menu.campaign = {}
main_menu.campaign["ancient_button"] = {}
main_menu.campaign["ancient_button"].GUID = _T("8c4308e577fb466c83c21b2decef7658")
main_menu.campaign["planets_button"] = {}
main_menu.campaign["planets_button"].GUID = _T("b5f96dd57e484a81a39a14a8acba1bc6")
main_menu.campaign["hi_tech_button"] = {}
main_menu.campaign["hi_tech_button"].GUID = _T("409fcdc8176e4edd84c475311e97bfc")
main_menu.campaign["original_button"] = {}
main_menu.campaign["original_button"].GUID = _T("9e767ef69efd40c28e837dfd928f38c")

function main_menu.show_main_menu(_start_main_menu, _alpha) -- '_alpha == true' означает, что окно запущенно первый раз
        local app = sf.core.g_Application
                
        local window = s4.CMainMenu()
        
        window.Load(
        
                app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_main_menu"), true), --
                app.GetSettings().GetChild(_T("GUITemplates"), false))

        if      (window.GetWidget(_T("main_background"), true) ~= nil) then
                if      (__cast(window.GetWidget(_T("main_background"), true), s4.CBackgroundWidget) ~= nil) then
                        main_menu.main_background_widget = __cast(window.GetWidget(_T("main_background"), true), s4.CBackgroundWidget)
                end
        end     
        
        for background_id in pairs(main_menu.small_back_grounds) do
                local temp_window = window.GetWidget(main_menu.small_back_grounds[background_id].widget_id, true)
                if      (temp_window ~= nil) then
                        if      (__cast(temp_window, s4.CBackgroundWidget) ~= nil) then
                                main_menu.small_back_grounds[background_id].widget = __cast(temp_window, s4.CBackgroundWidget)
                                main_menu.small_back_grounds[background_id].widget.SetOffset(main_menu.small_back_grounds[background_id].offset_x, main_menu.small_back_grounds[background_id].offset_y)
                        end
                end
        end
        
        window.UpdateLayout()
        local main_menu_size = window.GetSize()
        window.SetOffset(g_ScreenResolution.X/2 - main_menu_size.X/2, g_ScreenResolution.Y/2 - main_menu_size.Y/2)
        
        if ( _start_main_menu == true) then
                local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
                local num_profiles = s4.g_ProfileManager.Instance().EnumProfiles()
                if num_profiles ~= 0 and not current_profile then
                        s4.g_ProfileManager.Instance().SetCurrentProfile(0);
                end
        end

        local window_ptr = sf.gui.CBaseWindowPtrT(window)
        app.SetMainWindow(window_ptr)
		local s4app = __cast(app, s4.CS4App)
		local branch = s4.CBranch(s4app.GetGameFolder(), _T("branch\\branch.xml"), _T("mainmenu"))
		local branch_ptr = sf.gui.CWidgetPtrT(branch)
		window.AddWidget(branch_ptr)
		
	s4.le.g_Campaigns.Instance().ClearCache()
	
	s4.g_GameOptions.Instance().ApplyOptionsChanges()
	main_menu.init_welcome(window)
    main_menu.start_main_menu_playing()
	
        if _alpha then
                local move_time = 500
                local hide_time = 500           
                
                local group = sf.core.g_Application.GetSettings().GetChild(_T("GUI"),false).GetChildByAttribute(_T("window"), _T("id"), _T("loading"), true).GetChildByAttribute(_T("image_widget"), _T("id"), _T("animation"), true)
                local widget = sf.gui.CWidgetPtrT(sf.gui.CImageWidget(_T(""), _T(""), 0, 0))
                widget.Load(group, sf.core.g_Application.GetSettings().GetChild(_T("Templates"),false))
                widget.SetOffset(tonumber(group.GetValue(_T("x")).c_str()), tonumber(group.GetValue(_T("y")).c_str()))
                local color = sf.graphics.Color(widget.GetColor().Alpha, widget.GetColor().Red, widget.GetColor().Green, widget.GetColor().Blue)
                color.Alpha = 0
                widget.AddEffect(sf.gui.CEffectPtrT(s4.CColorChangeEffect(color, hide_time, move_time)))
                widget.AddEffect(sf.gui.CEffectPtrT(s4.CRemoveWidgetEffect(hide_time + move_time)))
                window_ptr.AddWidget(widget)

                group = sf.core.g_Application.GetSettings().GetChild(_T("GUI"),false).GetChildByAttribute(_T("window"), _T("id"), _T("loading"), true).GetChildByAttribute(_T("image_widget"), _T("id"), _T("black"), true)
                widget = sf.gui.CWidgetPtrT(sf.gui.CImageWidget(_T(""), _T(""), 0, 0))
                widget.Load(group, sf.core.g_Application.GetSettings().GetChild(_T("Templates"),false))
                widget.SetOffset(tonumber(group.GetValue(_T("x")).c_str()), tonumber(group.GetValue(_T("y")).c_str()))
                color = sf.graphics.Color(widget.GetColor().Alpha, widget.GetColor().Red, widget.GetColor().Green, widget.GetColor().Blue)
                color.Alpha = 0
                widget.AddEffect(sf.gui.CEffectPtrT(s4.CColorChangeEffect(color, hide_time, move_time)))
                widget.AddEffect(sf.gui.CEffectPtrT(s4.CRemoveWidgetEffect(hide_time + move_time)))
                window_ptr.AddWidget(widget)
                
                group = sf.core.g_Application.GetSettings().GetChild(_T("GUI"),false).GetChildByAttribute(_T("window"), _T("id"), _T("loading"), true).GetChildByAttribute(_T("image_widget"), _T("id"), _T("logo"), true)
                widget = window_ptr.GetWidget(_T("logo"))
                widget.SetLayer(tonumber(group.GetValue(_T("layer")).c_str()))
                local offset = sf.misc.FloatVector(widget.GetOffset().X, widget.GetOffset().Y)
                widget.SetOffset(tonumber(group.GetValue(_T("x")).c_str()), tonumber(group.GetValue(_T("y")).c_str()))
                widget.AddEffect(sf.gui.CEffectPtrT(s4.CPositionChangeEffect(sf.misc.FloatVector(offset.X, offset.Y), move_time, 0)))
                window_ptr.AddWidget(widget)
        end 
        
        window_ptr = nil
        collectgarbage()

        --[[local s4app = __cast(app, s4.CS4App)
        local level_editor_button = __cast(window.GetWidget(_T("level_editor_button"), true), sf.gui.CButtonWidget)
        if level_editor_button then level_editor_button.DisableButton(s4app.IsPlayTest()) end]]
        
        if ( _start_main_menu == true) then
        
                if not main_menu.update_game_suggested and update_game.try(window) then
                        main_menu.update_game_suggested = true
                end
        end
end

function main_menu.play_background(_name)
        for background_id in pairs(main_menu.small_back_grounds) do
                if      (main_menu.small_back_grounds[background_id].widget ~= nil) then
                        if      (_name == background_id) then
                                --main_menu.small_back_grounds[background_id].widget.Reset()
                                main_menu.small_back_grounds[background_id].widget.Play()
                        else
                                main_menu.small_back_grounds[background_id].widget.Stop()
                        end
                end
        end

        local main_window = sf.core.g_Application.GetMainWindow()
        if main_window ~= nil then
                local game_window = __cast(main_window, sf.gui.CBaseWindow)
                if      game_window ~= nil then 
                        local widget = game_window.GetWidget(_T("welcome_label"), true).get()
                        if      widget ~= nil then
                                local label = __cast(widget, sf.gui.CLabelWidget)
                                if label ~= nil then
                                        local flag = sf.misc.BitwiseOr(sf.gui.CBaseWidget.FlagHidden, sf.gui.CBaseWidget.FlagDisabled)
                                        if      _name == "not_button" then
                                                label.RemFlags(flag)
                                        else
                                                label.AddFlags(flag)
                                        end
                                end
                        end
                        local widget = game_window.GetWidget(_T("change_player_button"), true).get()
                        if      widget ~= nil then
                                local button = __cast(widget, sf.gui.CButtonWidget)
                                if button ~= nil then
                                        local flag = sf.misc.BitwiseOr(sf.gui.CBaseWidget.FlagHidden, sf.gui.CBaseWidget.FlagDisabled)
                                        if      _name == "not_button" then
                                                button.RemFlags(flag)
                                        else
                                                button.AddFlags(flag)
                                        end
                                end
                        end
                end
        end
end

function main_menu.stop_background(_name)
        if      (main_menu.small_back_grounds[_name].widget ~= nil) then
                if      (main_menu.small_back_grounds[_name].widget.Stop() == true) then
                        main_menu.play_background("not_button")
                end
        end
end

function main_menu.start_main_menu_sound()
        s4.g_MusicPlayer.Instance().PlayWithoutSlide(sf.misc.AppendPath(_T("music"), _T("menu.ogg")))
end

function main_menu.stop_main_menu_sound()
        s4.g_MusicPlayer.Instance().StopWithoutSlide()
end

function main_menu.start_main_menu_background()
        if      (main_menu.main_background_widget ~= nil) then
                main_menu.main_background_widget.Play()
        end
        main_menu.play_background("not_button")
end

function main_menu.stop_main_menu_background(_release)
        if      (main_menu.main_background_widget ~= nil) then
                main_menu.main_background_widget.Stop()
                if      (_release == true) then
                        main_menu.main_background_widget = nil
                        collectgarbage()
                end
        end
        for background_id in pairs(main_menu.small_back_grounds) do
                if      (main_menu.small_back_grounds[background_id].widget ~= nil) then
                        main_menu.small_back_grounds[background_id].widget.Stop()
                        if      (_release == true) then
                                main_menu.small_back_grounds[background_id].widget = nil
                                collectgarbage()
                        end
                end
        end
end

function main_menu.start_main_menu_playing()
        main_menu.start_main_menu_sound()
        main_menu.start_main_menu_background()
end

function main_menu.stop_main_menu_playing(_release)
        main_menu.stop_main_menu_sound()
        main_menu.stop_main_menu_background(_release)
end

function main_menu.start_select_campaign_window(_owner, _dif_level)
        local app = sf.core.g_Application
        local window = s4.COnKeyDownWindow()
        window.Load(
                app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_select_campagin"), true), 
                app.GetSettings().GetChild(_T("GUITemplates"), false))
        window.UpdateLayout()
        MoveWindowToCenter(_owner, window)
        
        local tab_widget = __cast(window.GetWidget(_T("difficulty_levels_tab")).get(), "sf.gui.CTabWidget")
        tab_widget.SelectPanel(_dif_level)
        
        select_campaign.form_select_campaign_window(window, true)
        
        local window_ptr = sf.gui.CBaseWindowPtrT(window)
        _owner.AddChildWindow(window_ptr) 
        
        --window_ptr = nil
end

function main_menu.create_profile(_owner)
        local modal_res = user_profiles.run_create_new_profile_dialog(_owner)
        if modal_res == 1 then
                main_menu.init_welcome(_owner)
                s4.g_ProfileManager.Instance().Save()
        elseif modal_res == 0 then
        end
        
        --[[
        local window = sf.gui.CWindow()
        window.Load(
                app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_new_user"), true), 
                app.GetSettings().GetChild(_T("GUITemplates"), false))
        window.UpdateLayout()
        MoveWindowToCenter(_owner, window)

        local window_ptr = sf.gui.CBaseWindowPtrT(window)
        
        local modal_res = _owner.DoModal(window_ptr)
        window_ptr = nil
        collectgarbage()

        ]]
end

main_menu.get_lua_time = function(_time)
    return os.time{year=_time.wYear, month=_time.wMonth, day=_time.wDay, 
                   hour=_time.wHour, min=_time.wMinute, sec=_time.wSecond}
end


function main_menu.start_campaign(_campaign_name, _owner)
        local num_profiles = s4.g_ProfileManager.Instance().EnumProfiles()
        
        if num_profiles == 0 then
                main_menu.create_profile(_owner)
                num_profiles = s4.g_ProfileManager.Instance().EnumProfiles()
        end
        if num_profiles ~= 0 then
                local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
                local campaign_GUID = main_menu.campaign[_campaign_name].GUID
                local default_difficulty = s4.g_Difficulty.Instance().GetDifficultyLevel()
                local user_difficulty = current_profile.GetLastPlayedDifficultyLevelId()
                if      user_difficulty == nil then
                        user_difficulty = s4.g_Difficulty.Instance().GetDifficultyLevelId()
                end
                local game_camapgins = get_camapigns_info()
                
                -- Существует ли компания с указанным GUID'ом
                if game_camapgins[T_(campaign_GUID).c_str()] then
                        local p_c_h = get_profile_info(current_profile)
                        local camp_info  = p_c_h[T_(campaign_GUID).c_str()]
                        
                        -- Если пользователь уже играл эту кампанию
                        if camp_info then
                                local last_difficulty = ""
                                local last_year = 0
                                local last_month = 0
                                local last_day = 0
                                local last_hour = 0
                                local last_minut = 0
                                local last_second = 0
                                local game_info = nil
                                for difficulty in pairs(difficulty_list) do
                                        game_info = camp_info.dif_levels[difficulty]
                                        if game_info ~= nil then
                                                local temp = false
                                                if game_info.LastGD ~= nil then
                                                        if game_info.LastGD.wYear > last_year then
                                                                temp = true
                                                        elseif game_info.LastGD.wYear == last_year then
                                                                if game_info.LastGD.wMonth > last_month then
                                                                        temp = true
                                                                elseif game_info.LastGD.wMonth == last_month then
                                                                        if game_info.LastGD.wDay > last_day then
                                                                                temp = true
                                                                        elseif game_info.LastGD.wDay == last_day then
                                                                                if game_info.LastGD.wHour > last_hour then
                                                                                        temp = true
                                                                                elseif game_info.LastGD.wHour == last_hour then
                                                                                        if game_info.LastGD.wMinute > last_minut then
                                                                                                temp = true
                                                                                        elseif game_info.LastGD.wMinute == last_minut then
                                                                                                if game_info.LastGD.wSecond > last_second then
                                                                                                        temp = true
                                                                                                elseif game_info.LastGD.wSecond == last_second then
                                                                                                        if T_(current_profile.GetLastPlayedDifficultyLevelId()).c_str() == difficulty then
                                                                                                                temp = true
                                                                                                        end
                                                                                                end
                                                                                        end
                                                                                end
                                                                        end
                                                                end
                                                        end
                                                end
                                                if temp then
                                                        last_difficulty = difficulty
                                                        last_year = game_info.LastGD.wYear
                                                        last_month = game_info.LastGD.wMonth
                                                        last_day = game_info.LastGD.wDay
                                                        last_hour = game_info.LastGD.wHour
                                                        last_minut = game_info.LastGD.wMinute
                                                        last_second = game_info.LastGD.wSecond
                                                end
                                        end
                                end

                                game_info = camp_info.dif_levels[last_difficulty]

                                -- Если пользователь уже играл эту кампанию
                                if game_info and game_info.LevelsFinished ~= 0 then
                                        -- Если пользователь прошёл эту кампанию
                                        if camp_info.common_info.NumLevels == game_info.LevelsFinished then
                                                select_level.run_select_level_window(_owner, camp_info, last_difficulty, 0)
                                        else
                                        -- Если пользователь нe прошёл эту кампанию
                                                local my_time = os.date("%X", main_menu.get_lua_time(game_info.LastGD))
                                                local my_date = os.date("%x", main_menu.get_lua_time(game_info.LastGD))
                                                
                                                local app = sf.core.g_Application
                                                local window = s4.COnKeyDownWindow()
                                                window.Load(
                                                        app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_continue_or_new_game_with_date"), true), 
                                                        app.GetSettings().GetChild(_T("GUITemplates"), false))
                                                window.UpdateLayout()
                                                MoveWindowToCenter(_owner, window)
                                                local lable_widget = __cast(window.GetWidget(_T("message_label")).get(), "sf.gui.CLabelWidget")
                                                
                                                local format_string = lable_widget.GetText()
                                                local text = string.format(T_(format_string).c_str(), T_(camp_info.Id).c_str() , game_info.LastGameLevel + 1 , my_date, my_time)
                                                lable_widget.SetText(_T(text))
                                                
                                                local window_ptr = sf.gui.CBaseWindowPtrT(window)
                                                local modal_result = _owner.DoModal(window_ptr) 
                                                window_ptr = nil
                                                collectgarbage()
                                                
                                                if modal_result == 1 then 
                                                        s4.g_Difficulty.Instance().SetDifficultyLevel(diff_levels_enum[last_difficulty])
                                                        log(tostring(game_info.LevelsFinished), 0)
														local show_dif_dialog = false
														if game_info.LastGameLevel == 0 then
															show_dif_dialog = true
														end
                                                        main_menu.start_game(_owner, campaign_GUID, game_info.LastGameLevel, game_info.LastGamePoints, game_info.LastGameGems, game_info.LastGameLifes, show_dif_dialog) 
                                                elseif modal_result == 2 then
                                                        select_level.run_select_level_window(_owner, camp_info, last_difficulty, 0)
                                                end
                                        end
                                else
                                -- Если не играл, начать на стандартном уровне сложности
                                        s4.g_Difficulty.Instance().SetDifficultyLevel(default_difficulty)
                                        main_menu.start_game(_owner, campaign_GUID, 0, 0, 0, game.StartLivesNum, true) 
                                end
                        else
                        -- Если не играл, начать на стандартном уровне сложности
                                s4.g_Difficulty.Instance().SetDifficultyLevel(default_difficulty)
                                main_menu.start_game(_owner, campaign_GUID, 0, 0, 0, game.StartLivesNum, true) 
                        end
                        
                        
--[[                    if      camp_info and user_difficulty then
                                local game_info = camp_info.dif_levels[T_(user_difficulty).c_str()]
                                if      game_info then
                                        -- Если пользователь прошёл эту кампанию
                                        if  camp_info.NumLevels == game_info.LastGameLevel then
                                                select_level.run_select_level_window(_owner, camp_info, user_difficulty, 0)
                                        else
                                                local modal_result = main_menu.ask_continue_campaign(_owner, game_info, last_played_campaign_id, last_played_dif_level)
                                                if      modal_result == 1 then
                                                        s4.g_Difficulty.Instance().SetDifficultyLevel(diff_levels_indexes[T_(user_difficulty).c_str()])
                                                        main_menu.start_game(_owner, campaign_GUID, game_info.LastGameLevel, game_info.LastGamePoints, game_info.LastGameGems, game_info.LastGameLifes) 
                                                elseif modal_result == 2 then
                                                        select_level.run_select_level_window(_owner, camp_info, user_difficulty, 0)
                                                end
                                        end
                                else
--                                      main_menu.ask_continue_campaign(_owner, game_info)
                                end
                        else
                                s4.g_Difficulty.Instance().SetDifficultyLevel(default_difficulty)
                                main_menu.start_game(_owner, campaign_GUID, 0, 0, 0, game.StartLivesNum) 
                        end  --]]
                else
                        main_menu.start_select_campaign_window(_owner, defaulf_dificulty)
                end
        end
end

function main_menu.ask_continue_campaign(_owner, _game_info, _last_played_campaign_id, _last_played_dif_level)
        local app = sf.core.g_Application
        local window = s4.COnKeyDownWindow()
        window.Load(
                app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_continue_or_change_campaign"), true), 
                app.GetSettings().GetChild(_T("GUITemplates"), false))
        window.UpdateLayout()
        MoveWindowToCenter(_owner, window)
        local lable_widget = __cast(window.GetWidget(_T("message_label")).get(), "sf.gui.CLabelWidget")
        
        if game.is_correct_time(_game_info.LastGD) then
                out_string = os.date("%x", game.get_lua_time(_game_info.LastGD))
        else
                out_string = ""
        end

        local format_string = lable_widget.GetText()
        local text = string.format(T_(format_string).c_str(), T_(_last_played_campaign_id).c_str() , _game_info.LastGameLevel + 1 , T_(_last_played_dif_level).c_str(), out_string )
        lable_widget.SetText(_T(text))
        
        local window_ptr = sf.gui.CBaseWindowPtrT(window)
        local modal_result = _owner.DoModal(window_ptr) 
        window_ptr = nil
        collectgarbage()
        return modal_result
end

function main_menu.main_menu_script(_owner, _action, _child)

        if not main_menu.update_game_suggested and update_game.try(_owner) then
                main_menu.update_game_suggested = true
                return
        end
        
        local app = sf.core.g_Application
        if _action==_T("pressed") then   
                if main_menu.campaign[T_(_child.GetId()).c_str()] ~= nil then
                        main_menu.start_campaign(T_(_child.GetId()).c_str(), _owner)
                elseif _child.GetId()==_T("change_player_button") then
                        user_profiles.run_profiles_dialog(_owner)
                elseif _child.GetId()==_T("play_button") then
                        local num_profiles = s4.g_ProfileManager.Instance().EnumProfiles()
                        
                        if num_profiles == 0 then
                                main_menu.create_profile(_owner)
                        else
                                local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
--                              local last_played_campaign = current_profile.GetLastPlayedCampaignId()
                                local last_played_campaign = current_profile.GetLastPlayedCampaignGUID()
                                local last_played_campaign_id = current_profile.GetLastPlayedCampaignId()
                                local last_played_dif_level = current_profile.GetLastPlayedDifficultyLevelId()
                                local game_camapgins = get_camapigns_info()
                                local p_c_h = get_profile_info(current_profile)
                                
                                local camp_info  = p_c_h[T_(last_played_campaign).c_str()] --T_()
                                local campaign = s4.le.g_Campaigns.Instance().GetCampaignByGUID(last_played_campaign)
                                if camp_info ~= nil and campaign ~= nil then
                                        
                                        local game_info = camp_info.dif_levels[T_(last_played_dif_level).c_str()]
                                        if game_info then
                                
--[[                                            local modal_res = main_menu.ask_continue_campaign(_owner, game_info, last_played_campaign_id, last_played_dif_level)
                                                
                                                if modal_res == 1 then
                                                        local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
--                                                      local last_played_campaign = current_profile.GetLastPlayedCampaignId()
                                                        local last_played_campaign = current_profile.GetLastPlayedCampaignGUID()
                                                        local last_played_dif_level = current_profile.GetLastPlayedDifficultyLevelId()
                                                        local game_camapgins = get_camapigns_info()
                                                        local p_c_h = get_profile_info(current_profile)
                                                        
                                                        local camp_info  = p_c_h[T_(last_played_campaign).c_str()]
                                                        if camp_info then
                                                                local game_info = camp_info.dif_levels[T_(last_played_dif_level).c_str()]
                                                                if game_info then
                                                                        
                                                                        s4.g_Difficulty.Instance().SetDifficultyLevel(diff_levels_enum[T_(last_played_dif_level).c_str()])
                                                                        main_menu.start_game(_owner, last_played_campaign, game_info.LastGameLevel, game_info.LastGamePoints, game_info.LastGameGems, game_info.LastGameLifes) 
                                                                end
                                                        end
                                                elseif modal_res == 2 then
                                                        ]]
                                                        local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
                                                        local last_played_dif_level_idx = diff_levels_indexes[T_(current_profile.GetLastPlayedDifficultyLevelId()).c_str()]
                                                        main_menu.start_select_campaign_window(_owner, last_played_dif_level_idx)
--                                              end
                                        else
                                                local curent_dif = s4.g_Difficulty.Instance().GetDifficultyLevel()
                                                main_menu.start_select_campaign_window(_owner, curent_dif)
                                        end
                                        
                                else
                                        local curent_dif = s4.g_Difficulty.Instance().GetDifficultyLevel()
                                        main_menu.start_select_campaign_window(_owner, curent_dif)
                                end
                                
                        end
                elseif _child.GetId()==_T("options_button") then
                        local num_profiles = s4.g_ProfileManager.Instance().EnumProfiles()
                        
                        if num_profiles == 0 then
                                main_menu.create_profile(_owner)
                                num_profiles = s4.g_ProfileManager.Instance().EnumProfiles()
                        end
                        if num_profiles ~= 0 then
                                options_window.run_options_window(_owner, true)
                        end
                elseif _child.GetId()==_T("level_editor_button") then
                        main_menu.start_le(_owner)
                elseif _child.GetId()==_T("scores_button") then
                       	set_widget_flag_value(_owner, sf.gui.CBaseWidget.FlagHidden, true)
						record_table.run_record_table_window(_owner)
						set_widget_flag_value(_owner, sf.gui.CBaseWidget.FlagHidden, false)
                elseif _child.GetId()==_T("help_button") then
                        help_window.run_help_window(_owner)
                elseif _child.GetId()==_T("quit_button") then

                        local window = s4.COnKeyDownWindow()
                        window.Load(
                                app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_quit_dialog"), true), 
                                app.GetSettings().GetChild(_T("GUITemplates"), false))
                        window.UpdateLayout()   
                        MoveWindowToCenter(_owner, window)
                        
                        local window_ptr = sf.gui.CBaseWindowPtrT(window)
                        
                        local modal_res = _owner.DoModal(window_ptr)
                        window_ptr = nil
                        collectgarbage()                        
                        if  modal_res == 1  then
                                app.Shutdown()
                        else
                        end
                end
        elseif (_action == _T("overed")) then   
                if (main_menu.small_back_grounds[T_(_child.GetId()).c_str()] and main_menu.small_back_grounds[T_(_child.GetId()).c_str()].widget ~= nil) then
                        main_menu.play_background(T_(_child.GetId()).c_str())
                end
        elseif (_action == _T("lost_over")) then
                if (main_menu.small_back_grounds[T_(_child.GetId()).c_str()] and main_menu.small_back_grounds[T_(_child.GetId()).c_str()].widget ~= nil) then
                        main_menu.stop_background(T_(_child.GetId()).c_str())
                end
        end
end

function main_menu.start_le(_owner)
        local window = s4.le.CLevelEditorMainWindow()
        local window_ptr = sf.gui.CBaseWindowPtrT(window)
        local offset = _owner.GetOffset()
        window.SetOffset(-offset.X, -offset.Y)
        set_widget_flag_value(_owner, sf.gui.CBaseWidget.FlagHidden, true)
        main_menu.stop_main_menu_background(false)
        _owner.DoModal(window_ptr)
        main_menu.start_main_menu_playing()
        set_widget_flag_value(_owner, sf.gui.CBaseWidget.FlagHidden, false)
        window_ptr = nil
        collectgarbage()
end

function main_menu.start_game(_owner, _campaign_guid, level_num, _points, _games, _lives, _show_dif_level_dialog)
        local app = sf.core.g_Application
        
        local s4app = __cast(app, s4.CS4App) 
        if s4app.IsPlayTest()==true then
                s4.g_Statistics.Instance().Save()
                s4.g_Statistics.Instance().Clear()
                local max_count_no_sended_records = tonumber(T_(app.GetSettings().GetChild(_T("settings"), false).GetValue(_T("max_count_no_sended_records"))).c_str())
                local count_no_sended = s4.g_Statistics.Instance().GetCountNoSendedRecords()
                if count_no_sended~=0 and math.mod(count_no_sended, max_count_no_sended_records)==0 then
                        game_window.need_send_statistics(_owner);
                end
        end
        
        local window = s4.CGameWindow()
        
        main_menu.stop_main_menu_playing(true)
        window.SetShowDifDialog(_show_dif_level_dialog)
        window.InitGame(_campaign_guid, level_num, _points, _games, _lives)
        local window_ptr = sf.gui.CBaseWindowPtrT(window)
        
        app.SetMainWindow(window_ptr)
        window_ptr = nil
        collectgarbage()
end
         
function main_menu.init_welcome(_target_window)
        local label_widget = __cast(_target_window.GetWidget(_T("welcome_label")).get(), "sf.gui.CLabelWidget")
        local change_button_widget = __cast(_target_window.GetWidget(_T("change_player_button")).get(), "sf.gui.CButtonWidget")
        if label_widget then
                local num_profiles = s4.g_ProfileManager.Instance().EnumProfiles()
                local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
                if num_profiles ~= 0 and current_profile then
                        local profile_name = s4.g_ProfileManager.Instance().GetCurrentProfile().GetName()
                        label_widget.SetText(_T(
                        string.format(sf.misc.g_StringTable.Instance().FormatByStringsID(main_menu.name_title_string_id).c_str(), T_(profile_name).c_str())
                        ))
                        set_widget_flag_value(change_button_widget, sf.gui.CBaseWidget.FlagHidden, false)
                        set_widget_flag_value(change_button_widget, sf.gui.CBaseWidget.FlagDisabled, false)
                else
                        label_widget.SetText(sf.misc.g_StringTable.Instance().FormatByStringsID(main_menu.simple_title_string_id))
                        set_widget_flag_value(change_button_widget, sf.gui.CBaseWidget.FlagHidden, true)
                        set_widget_flag_value(change_button_widget, sf.gui.CBaseWidget.FlagDisabled, true)
                end
        end
end

function main_menu.continue_or_change_campaign_script(_owner, _action, _child)
        if _action==_T("pressed") then
                if _child.GetId()==_T("change_campaign") then
                        _owner.EndModal(2)
                elseif _child.GetId()==_T("continue") or _action == _T("key_down_enter") then
                        _owner.EndModal(1)
                elseif _child.GetId()==_T("cancel") and _action==_T("pressed") or _action == _T("key_down_escape") then
                        _owner.EndModal(0)
                end
        end
end

function main_menu.continue_or_change_campaign_script_with_time(_owner, _action, _child)
        if _child.GetId()==_T("new_game") and _action==_T("pressed") then
                _owner.EndModal(2)
        elseif _child.GetId()==_T("continue") and _action==_T("pressed") or _action == _T("key_down_enter") then
                _owner.EndModal(1)      
        elseif _child.GetId()==_T("cancel") and _action==_T("pressed") or _action == _T("key_down_escape") then
                _owner.EndModal(0)      
        end
end

