require( "scripts/style.lua" );
require( "scripts/game/level_params.lua" );
require( "scripts/game/trophyes.lua" );

local scores = gScoresValue;
LastLevelIsNowWin = nil;

musicWIN = 1;
musicLOSE = 2;

isButtonPressed = false;

function CheckBtnClick()
    if (isButtonPressed == true) then return 0; end
    isButtonPressed = true;
    return 1;
end

MyFont = {
    standardFont,
    22,
    BlackColor
};
LevCompBtnFont = {
    standardFont,
    22,
    WhiteColor
};

iState = 6;
step = 1;
step2 = 1;
is_empty=1;
all_game_complete = 0;

gTextX1 = 255;
gTextX1W = 140;
gTextX3W = 110;
gTextX2 = 350;
gTextX3 = 380;
gTextH = 24;
gTextResDelta=10;
gTextResDelta1=20;

pref = "e_";
if (gGameMode==0) then
    pref = "";
    gTextY = 190;       --110; без разделения бонусов
    gTextSpising = 18;  --24;  без разделения бонусов
else
    gTextSpising = 22;  --24;  без разделения бонусов
    gTextY = 180;       --110; без разделения бонусов
end

coord_img_res = { 
    dad = { 
        win = { x=100,y=138,image="slider/res_dad_win.png"}; 
        lose = {x=67, y = 160,image="slider/res_dad_lose.png"};  
    };  
    mother = { 
        win = { x=100,y=122,image="slider/res_mother_win.png"}; 
        lose = {x=100, y = 133,image="slider/res_mother_lose.png"};  
    };  
    sister = { 
        win = { x=100,y=108,image="slider/res_sister_win.png"}; 
        lose = {x=120, y = 130,image="slider/res_sister_lose.png"};  
    };  
};

MakeDialog
{
    name="level_complete_dialog",
    LevelComplete
    {
        name="level_complete",
        Button
        {
            x=435,
            y=465,
            name="replay_level",
            label="", --next_level",
            font = StandardButtonFont,
            sound=kDefaultButtonSound,                        
            graphics = {
                        "buttons/res_but.png",
                        "buttons/res_but.png",
                        "buttons/res_but.png"
                        },
            command=
                function()
                    if (CheckBtnClick() == 0) then return; end
                    --if (levelnum_was_inc == 1) then 
                    --    gGlobalPlayerInfo.gLevelNum = gGlobalPlayerInfo.gLevelNum - 1;
                    --end
                    SayEndTrial();
                    PopModal("level_complete_dialog");                                          
                    if(isMinigame==1)then
                        CloseWindow();
                    end;
                    CheckLoadingWindow();
                    LoadLevel(gGlobalPlayerInfo.gLevelNum);                                    
                end;
            Bitmap
            { 
                name="icon_btn_replay",
                image="buttons/res_replay_icon.png",
                x=0,
                y=46;
            };
            Text
            {
                flags = kHAlignCenter + kVAlignCenter,
                font = LevCompBtnFont,
                name = "txtBtnRL",
                x=60,y=50,w=118,h=42,
                label = "replay_level";
            };
        },    
        Button
        {
            name="next_level_button",
            x=435,
            y=465,
            label="", --next_level",
            font = StandardButtonFont,
            sound=kDefaultButtonSound,                        
            graphics = {
                        "buttons/res_but.png",
                        "buttons/res_but.png",
                        "buttons/res_but.png"
                        },
              
            command=
                function()       
                    if (CheckBtnClick() == 0) then return; end
                    SayEndTrial();
                    PopModal( "level_complete_dialog");
                    if(isMinigame==1)then
                        PopModal("bonus_dialog");
                    end
                    CheckLoadingWindow();
                    
                    if(StopGame)then
                        StopGame(0);
                    end
                    if (gGameMode == 0)  then
                        st = table.getn(gGlobalGameInfo.gFarm);
                        for gi = 2,st,1 do  --2,st,1 do
                            if (gGlobalGameInfo.gFarm[gi] == gGlobalPlayerInfo.gLevelNumMax) then
                                if (gGlobalPlayerInfo["lev"..gGlobalPlayerInfo.gLevelNumMax] == nil) then
                                    --если надо тут проверить в gGlobalPlayerInfo что был показан туториал
                                    if (gGlobalPlayerInfo["show_tut_"..gi] == nil or gGlobalPlayerInfo["show_tut_"..gi] == 0) then
                                        DoModal("scripts/tutorial"..gi..".lua");
                                        gGlobalPlayerInfo["show_tut_"..gi] = 1;
                                        --если надо тут запомнить в gGlobalPlayerInfo что показан туториал
                                    end
                                end
                                break;
                            else
                                if (gGlobalPlayerInfo.gLevelNumMax > gGlobalGameInfo.gLevelCount[1]) then
                                    --если надо тут проверить в gGlobalPlayerInfo что был показан туториал
                                    if (gGlobalPlayerInfo.show_end_tut == nil or gGlobalPlayerInfo.show_end_tut == 0) then
                                        gGlobalPlayerInfo.show_end_tut = 1;
										CPP_WriteGO();

                                        DoModal("scripts/tutorial_end.lua");
                                        --если надо тут запомнить в gGlobalPlayerInfo что показан туториал
										return;
                                    end
                                    break;
                                end
                            end
                        end
                        DoModal("scripts/game_map.lua");
                    else
                        DoModal("scripts/game_map_endless.lua");
                    end
                    
                end;
            Bitmap
            { 
                name="icon_btn_next",
                image="buttons/res_next_but.png",
                x=0,
                y=46;
            };
            Text
            {
                flags = kHAlignCenter + kVAlignCenter,
                font = LevCompBtnFont,
                name = "txtBtnNL",
                x=55,y=50,w=118,h=42,
                label = "next_level";
            };
        },          
        
        Button
        {
            x=172,
            y=468,
            name="main_menu_btn",
            label="", 
            font = StandardButtonFont,
            sound=kDefaultButtonSound,                        
            --close=true, --вернуться в main menu
            graphics = {
                        "buttons/res_but.png",
                        "buttons/res_but.png",
                        "buttons/res_but.png"
                        },
            command=
                function()
                    if (CheckBtnClick() == 0) then return; end
                    -- Pop up an options screen
                    SayEndTrial();
                    end_level_info={}; --надо очистить структуру данных
--[[                    
                    if (is_empty == 0) then --вернуться в main menu
                        PopModal("thegame");            
                    end
--]]

                    PopModal( "level_complete_dialog");
                    if(isMinigame==1)then
                        PopModal( "bonus_dialog");
                    end
                    CheckLoadingWindow();

                    if(StopGame)then
                        StopGame(0);
                    end

                    if (gGameMode == 0)  then
                        DoModal("scripts/game_map.lua");
                    else
                        DoModal("scripts/game_map_endless.lua");
                    end
                end;
            Bitmap
            { 
                name="icon_btn_map",
                image="buttons/res_map_icon.png",
                x=0,
                y=46;
            };
            Text
            {
                flags = kHAlignCenter + kVAlignCenter,
                font = LevCompBtnFont,
                name = "txtBtnMM",
                x=70,y=50,w=108,h=42,
                label = "back_to_menu";
            };
        },  
        Button
        {
            x=172,
            y=468,
            name="replay_level_win",
            label="", --next_level",
            font = StandardButtonFont,
            sound=kDefaultButtonSound,                        
            graphics = {
                        "buttons/res_but.png",
                        "buttons/res_but.png",
                        "buttons/res_but.png"
                        },
            command=
                function()
                    if (CheckBtnClick() == 0) then return; end
                    --if (levelnum_was_inc == 1) then 
                    --    gGlobalPlayerInfo.gLevelNum = gGlobalPlayerInfo.gLevelNum - 1;
                    --end
                    SayEndTrial();
                    PopModal("level_complete_dialog");                                          
                    if(isMinigame==1)then
                        CloseWindow();
                    end;                    
                    CheckLoadingWindow();
                    LoadLevel(gGlobalPlayerInfo.gLevelNum);                 
                end;
            Bitmap
            { 
                name="icon_btn_replay",
                image="buttons/res_replay_icon.png",
                x=0,
                y=46;
            };
            Text
            {
                flags = kHAlignCenter + kVAlignCenter,
                font = LevCompBtnFont,
                name = "txtBtnRLwin",
                x=60,y=50,w=118,h=42,
                label = "replay_level";
            };
        },    
        Bitmap
        { 
            name="backgroundimage",
            image="backgrounds/res_win.png", --level_complete",
            x=105,
            y=10,   
            SetStyle(TutorialButton),
            
            Bitmap
            { 
                name="image_res_win",
                image="slider/res_dad_win.png",
                x=100,
                y=138;
            };
            Bitmap
            { 
                name="image_res_lost",
                image="slider/res_dad_lose.png",
                x=67,
                y=160;
            };
            Bitmap
            { 
                name="line_delim_top",
                image="slider/res_orn_top.png",
                x=325,
                y=263;
            };
            Bitmap
            { 
                name="line_delim_bot",
                image="slider/res_orn_bot.png",
                x=325,
                y=397;
            };
            Bitmap
            { 
                name="speech_panel",
                image="panels/res_speech.png",
                x=250,
                y=120;
            };
--ТЕКСТОВЫЕ СТРОКИ     
--[[   
            Text
            {
                font = MyFont,
                name = "description_line1",
                x=gTextX1,y=gTextY + gTextSpising*1,w=gTextX1W,h=gTextH,
                label = "";--sheep_shear_text";
            };
            Text
            {
                font = MyFont,
                name = "value_line1",
                flags = kHAlignRight,
                x=gTextX2,y=gTextY + gTextSpising*1,w=75,h=gTextH,
                label = ""; --"level_score";
            };
            Text
            {
                font = MyFont,
                name = "money_line1",
                x=gTextX3,y=gTextY + gTextSpising*1,w=70,h=gTextH,
                label = ""; --"level_score";
            };
            
        
            Text
            {
                font = MyFont,
                name = "description_line2",
                x=gTextX1,y=gTextY + gTextSpising*2,w=gTextX1W,h=gTextH,
                label = ""; --"milk_collected_text";
            };
            Text
            {
                font = MyFont,
                name = "value_line2",
                flags = kHAlignRight,
                x=gTextX2,y=gTextY + gTextSpising*2,w=75,h=gTextH,
                label = ""; --"level_score";
            };
            Text
            {
                font = MyFont,
                name = "money_line2",
                x=gTextX3,y=gTextY + gTextSpising*2,w=70,h=gTextH,
                label = ""; --"level_score";
            };
            
            Text
            {
                font = MyFont,
                name = "description_line3",
                x=gTextX1,y=gTextY + gTextSpising*3,w=gTextX1W,h=gTextH,
                label = ""; --"cows_lost_text";
            };
            Text
            {
                font = MyFont,
                name = "value_line3",
                flags = kHAlignRight,
                x=gTextX2,y=gTextY + gTextSpising*3,w=75,h=gTextH,
                label = ""; --"level_score";
            };
            Text
            {
                font = MyFont,
                name = "money_line3",
                x=gTextX3,y=gTextY + gTextSpising*3,w=70,h=gTextH,
                label = ""; --"level_score";
            };

---
            Text
            {
                font = MyFont,
                name = "description_line4",
                x=gTextX1,y=gTextY + gTextSpising*4,w=gTextX1W,h=gTextH,
                label = ""; --"cows_lost_text";
            };
            Text
            {
                font = MyFont,
                name = "value_line4",
                flags = kHAlignRight,
                x=gTextX2,y=gTextY + gTextSpising*4,w=75,h=gTextH,
                label = ""; --"level_score";
            };
            Text
            {
                font = MyFont,
                name = "money_line4",
                x=gTextX3,y=gTextY + gTextSpising*4,w=70,h=gTextH,
                label = ""; --"level_score";
            };

            Text
            {
                font = MyFont,
                name = "description_line5",
                x=gTextX1,y=gTextY + gTextSpising*5,w=gTextX1W,h=gTextH,
                label = ""; --"cows_lost_text";
            };
            Text
            {
                font = MyFont,
                name = "value_line5",
                flags = kHAlignRight,
                x=gTextX2,y=gTextY + gTextSpising*5,w=75,h=gTextH,
                label = ""; --"level_score";
            };
            Text
            {
                font = MyFont,
                name = "money_line5",
                x=gTextX3,y=gTextY + gTextSpising*5,w=70,h=gTextH,
                label = ""; --"level_score";
            };
            Text
            {
                font = MyFont,
                name = "description_line6",
                x=gTextX1,y=gTextY + gTextSpising*6,w=gTextX1W,h=gTextH,
                label = ""; --"cows_lost_text";
            };
            Text
            {
                font = MyFont,
                name = "value_line6",
                flags = kHAlignRight,
                x=gTextX2,y=gTextY + gTextSpising*6,w=75,h=gTextH,
                label = ""; --"level_score";
            };
            Text
            {
                font = MyFont,
                name = "money_line6",
                x=gTextX3,y=gTextY + gTextSpising*6,w=70,h=gTextH,
                label = ""; --"level_score";
            };
--]]            
--bonus score 1
            Window
            {
                name="control_story";
                x=0, y=0,
                w=800,
                h=600,
                Text
                {
                    font = {  standardFont, 20, DarkRedColor },
                    name = "bonus_description_line1",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*4,w=gTextX1W,h=gTextH,
                    label = "";
                },
                Text
                {
                    font = MyFont,
                    name = "bonus_value_line1",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*4,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--bonus score 2
                Text
                {
                    font = {  standardFont, 20, DarkRedColor },
                    name = "bonus_description_line2",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*5,w=gTextX1W,h=gTextH,
                    label = "";
                },
                Text
                {
                    font = MyFont,
                    name = "bonus_value_line2",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*5,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--bonus score 3
                Text
                {
                    font = {  standardFont, 20, DarkRedColor },
                    name = "bonus_description_line3",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*6,w=gTextX1W,h=gTextH,
                    label = "";
                },
                Text
                {
                    font = MyFont,
                    name = "bonus_value_line3",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*6,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--bonus score
                Text
                {
                    font = {  standardFont, 20, DarkRedColor },
                    name = "description_line7",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*7,w=gTextX1W,h=gTextH,
                    label = "";
                },
                Text
                {
                    font = MyFont,
                    name = "value_line7",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*7,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--level score
                Text
                {
                    font = MyFont,
                    name = "description_line8",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*8,w=gTextX1W,h=gTextH,
                    label = "level_score_text";
                },
                Text
                {
                    font = MyFont,
                    name = "score_without_bonus",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*8,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--level total score
                Text
                {
                    font = MyFont,
                    name = "description_total_score",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*9,w=gTextX1W,h=gTextH,
                    label = "level_total_score_text";
                },
                Text
                {
                    font = MyFont,
                    name = "value_line8",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*9,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--total score            
                Text
                {
                    font = {  standardFont, 20, DarkBlueColor },
                    name = "description_line9",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*10,w=gTextX1W,h=gTextH,
                    label = "total_score_text";
                },
                Text
                {
                    font = MyFont,
                    name = "value_line9",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*10,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
            },
            Window
            {
                name="control_endless";
                x=0, y=0,
                w=800,
                h=600,
--bonus score 1
                Text
                {
                    font = {  standardFont, 20, DarkRedColor },
                    name = "e_bonus_description_line1",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*4,w=gTextX1W,h=gTextH,
                    label = "";
                },
                Text
                {
                    font = MyFont,
                    name = "e_bonus_value_line1",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*4,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--bonus score 2
                Text
                {
                    font = {  standardFont, 20, DarkRedColor },
                    name = "e_bonus_description_line2",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*5,w=gTextX1W,h=gTextH,
                    label = "";
                },
                Text
                {
                    font = MyFont,
                    name = "e_bonus_value_line2",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*5,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--bonus score
                Text
                {
                    font = {  standardFont, 20, DarkRedColor },
                    name = "e_description_line7",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*6,w=gTextX1W,h=gTextH,
                    label = "";
                },
                Text
                {
                    font = MyFont,
                    name = "e_value_line7",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*6,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--level score
                Text
                {
                    font = MyFont,
                    name = "e_description_line8",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*7,w=gTextX1W,h=gTextH,
                    label = "level_score_text";
                },
                Text
                {
                    font = MyFont,
                    name = "e_score_without_bonus",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*7,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
--level total score
                Text
                {
                    font = MyFont,
                    name = "e_description_total_score",
                    x=gTextX1,y=gTextY + gTextResDelta + gTextSpising*8,w=gTextX1W,h=gTextH,
                    label = "level_total_score_text";
                },
                Text
                {
                    font = MyFont,
                    name = "e_value_line8",
                    x=gTextX3-10,y=gTextY + gTextResDelta + gTextSpising*8,w=gTextX3W,h=gTextH,
                    flags = kHAlignRight,
                    label = "";
                },
            },
--это описание задачи для след.уровня
            Text
            {
                font = {  standardFont, 20, BlackColor },
                name = "level_text",
                flags = kHAlignCenter + kVAlignCenter,
                x=274,y=133,w=170,h=115,
                label = "";
            },
--первое название            
            Text
            {
                font = {  bigButtonFont, 50, DarkBlueColor },
                name = "title1_win",
                flags = kHAlignCenter + kVAlignCenter,
                x=187,y=49,w=225,h=60,
                label = "title_levcomp_1_win";--sheep_shear_text";
            };
            Text
            {
                font = {  bigButtonFont, 45, DarkBlueColor },
                name = "title1_lose",
                flags = kHAlignCenter + kVAlignCenter,
                x=187,y=55,w=100,h=60,
                label = "title_levcomp_1_lose";--sheep_shear_text";
            };
            Text
            {
                font = {  bigButtonFont, 45, DarkBlueColor },
                name = "title2_lose",
                flags = kHAlignCenter + kVAlignCenter,
                x=300,y=55,w=140,h=60,
                label = "title_levcomp_2_lose";--sheep_shear_text";
            };
        };
--expert medal        
        Bitmap
        { 
            name="level_res_img",
            image="slider/expert_medal.png",
            x=594,
            y=37;
        };
        Swarm
        {
            name="swarm",
            x=0,
            y=0,
            w=800, 
            h=600
        };
    };
};

function SetControlParameters(aName,aParam,aNeedTranslate)
    if (aParam == nil) then 
        return; 
    end
    if (aParam.visible ~= nil) then
        if (aParam.visible == "0") then
            EnableWindow(aName,false);
            return;
        end
    end
    if (aParam.value ~= nil) then
        if (aParam.value == "") then
            SetLabel(aName,GetString("empty_text"));
        else
            if (aNeedTranslate == 1) then
                SetLabel(aName,GetString(aParam.value));
            else
                SetLabel(aName,aParam.value);
            end
        end
        return;
    end
    if (aParam.image ~= nil) then
        SetBitmap(aName,aParam.image,1);
    end
 end

function SetControlNumParameters(aName,aParam)
    SetLabel(aName,aParam);
    if (aParam == "-1") then 
        EnableWindow(aName,false);
        return; 
    end
 end

function IteratorTrophyProducts(aKey,aValue)
    has_records_trophy = 1; -- есть записи 
    --если уже не входим по одному из продуктов незачем дальше проверять
--ScriptDump("aKey="..aKey.."  aValue="..aValue);
    if (resultTrophyProducts == -1) then return; end
    if (LevelsProductsIterators[aKey] ~= nil) then
        if (aValue <= LevelsProductsIterators[aKey]) then
            resultTrophyProducts = 1;
        else
            --требуемого продукта не набрали
            resultTrophyProducts = -1;
        end
    else
        resultTrophyProducts = 0;
    end
end
 
-- проверяет трофеи уровня
-- ВЫЗЫВАТЬ ПОСЛЕ ВЫЗОВА SetGotScoresAndProducts
function CheckTrophyes(aScore)
    --отметим взятые трофеи в trophyes
    SetGotTrophyes();
    local countTrophyes = table.getn(trophyes);
    local now_taking = 0;
    local trophy;
    local lev = gGlobalPlayerInfo["lev"..gGlobalPlayerInfo.gLevelNum];
    local got_trophy = 0;
    local only_for_level = 0;
    CurrentLevelTrophy=0;
	CurrentLevelTrophysIndexses = {};	
	
    for ind = 1, countTrophyes, 1 do
        trophy = trophyes[ind];
        got_trophy = 0;
        only_for_level = 0; -- условия проверяются только для уровня
--got_trophy: если =0 продолжать проверять условия, 
--                 =-1 - не подходит, дальнейшая проверка не нужна,
--                 =1 - условие ок,продолжать проверять условия
        if (trophy.taking == 0) then
            --проверка по номеру уровня
            if (trophy.level ~= nil and trophy.level > 0) then
                if (trophy.level == gGlobalPlayerInfo.gLevelNum) then
                    only_for_level = 1;
                    got_trophy = 1;
                else
                    got_trophy = -1;
                end
            end
            if (got_trophy >= 0) then
                -- проверка по очкам
                if (trophy.score ~= nil and trophy.score > 0) then  --очки указаны
                    if (only_for_level == 0) then
                        if (trophy.score <= aScore) then got_trophy = 1;
                        else                             got_trophy = -1;  end
                    else
                        if (trophy.score <= lev.score) then got_trophy = 1;
                        else                                got_trophy = -1;  end
                    end
                end
            end
            if (got_trophy >= 0) then
                -- проверка по эксперту
                if (trophy.expert ~= nil and trophy.expert > 0) then  --очки указаны
                    if (only_for_level == 0) then
                        if (trophy.expert <= gGlobalPlayerInfo.gExpert) then got_trophy = 1;
                        else                                                 got_trophy = -1;  end
                    else
                        if (lev.expert ~= nil and lev.expert ~= 0)      then got_trophy = 1;
                        else                                                 got_trophy = -1;  end
                    end
                end
            end
            if (got_trophy >= 0) then
                -- проверка по эксперту
                if (only_for_level == 0) then
                    if (trophy.expert_levels ~= nil) then  --очки указаны
                        local size_expert_levels = table.getn(trophy.expert_levels);
                        for e_ind = 1, size_expert_levels,1 do
                            if (gGlobalPlayerInfo["lev"..trophy.expert_levels[e_ind]] ~= nil) then
                                if (gGlobalPlayerInfo["lev"..trophy.expert_levels[e_ind]].expert == 0 or gGlobalPlayerInfo["lev"..trophy.expert_levels[e_ind]].expert == nil) then
                                    got_trophy = -1;
                                    break;
                                else
                                    got_trophy = 1;
                                end
                            else
                                got_trophy = -1;
                                break;
                            end
                        end
                    end
                end
            end
            if (got_trophy >= 0) then
                --проверка по продуктам
                if (trophy.products ~= nil) then
                    indexTrophyProducts = ind;
                    resultTrophyProducts = 0;
                    has_records_trophy = 0; --есть ли записи в секции trophyes[...].products
                    if (only_for_level == 0) then
                        LevelsProductsIterators = gGlobalPlayerInfo.gProducts;
                    else
                        LevelsProductsIterators = lev.prods;
                    end
                    if (LevelsProductsIterators ~= nil) then
                        -- пройдемся по продуктам трофея и сравним их с взятыми нами продуктами
                        table.foreach( trophy.products, IteratorTrophyProducts );
                        if (has_records_trophy > 0) then
                            --секция products не пуста
                            if (resultTrophyProducts == 1) then got_trophy = 1;
                            else                                got_trophy = -1;  end
                        end
                    else
                        got_trophy = -1;
                    end
                end
            end
            if (got_trophy == 1) then --трофей получен, т.к. ВСЕ условия трофея выполнены
                now_taking = now_taking + 1;
                trophy.taking = 1;
				table.insert( CurrentLevelTrophysIndexses, ind);
                table.insert(lev.trophy,ind);
                table.insert(gGlobalPlayerInfo.gTrophyes,ind);
                if (gGlobalPlayerInfo.gNotSubmittedMedals == nil) then
                    gGlobalPlayerInfo.gNotSubmittedMedals = {};
                end
                gGlobalPlayerInfo.gNotSubmittedMedals[trophy.medal] = 1; --надо отсылать
            end
        end
    end
    if (now_taking > 0) then
        CurrentLevelTrophy=1;
    end
end
 
-- запишем очки уровня и продукты взятые на уровне
-- ВЫЗЫВАТЬ ДО ВЫЗОВА CheckTrophyes
function SetGotScoresAndProducts(aScore, aLevelNum,aIsExpert)
    local val;
    local old_lev_score = 0;
    local old_lev_expert = 0;
    local first_run_level = 1;
    if (gGlobalPlayerInfo["lev"..aLevelNum] ~= nil) then
        first_run_level = 0;
        if (aIsExpert ~= nil and aIsExpert ~= 0) then
            old_lev_expert = gGlobalPlayerInfo["lev"..aLevelNum].expert;
            if (old_lev_expert == nil or old_lev_expert == 0) then
                if (gGlobalPlayerInfo.gExpert == nil) then
                    gGlobalPlayerInfo.gExpert = 0;
                end
                gGlobalPlayerInfo.gExpert = gGlobalPlayerInfo.gExpert + 1;
            end
        end
        old_lev_score = gGlobalPlayerInfo["lev"..aLevelNum].score;
        if (old_lev_score >= aScore) then         
            -- новое прохождение уровня не побило рекорд предыдущего
            gGlobalPlayerInfo.gScore = gGlobalPlayerInfo.gScore - aScore;        
            return;
            -- передать карте что на уровне количество очков стало больше
        end
        --очки за уровень уже добавлены, вычтем пред.очки
        gGlobalPlayerInfo.gScore = gGlobalPlayerInfo.gScore - old_lev_score;
    else
        gGlobalPlayerInfo["lev"..aLevelNum] = { };
        gGlobalPlayerInfo["lev"..aLevelNum].trophy = { };
        gGlobalPlayerInfo["lev"..aLevelNum].prods = { };
    end
    LevelResultBetter = 1;
    local lev = gGlobalPlayerInfo["lev"..aLevelNum];
    lev.score = aScore;
    lev.expert = aIsExpert;
    if (first_run_level == 1) then
        if (aIsExpert ~= 0 and aIsExpert ~= nil) then
            if (gGlobalPlayerInfo.gExpert == nil) then
                gGlobalPlayerInfo.gExpert = 0;
            end
            gGlobalPlayerInfo.gExpert = gGlobalPlayerInfo.gExpert + 1;
        end
    end
    lev.prods = { };
    local old_prod_count;
    for ind = 1,6,1 do
        val = end_level_info["value_line"..ind];
        if (val ~= nil) then
            if (tonumber(val.score) > 0) then
                prod_count = 0;
                if (gGlobalPlayerInfo.gProducts[val.name] ~= nil) then
                    prod_count = gGlobalPlayerInfo.gProducts[val.name];
                end
                old_prod_count = 0;
                if (lev.prods[val.name] ~= nil) then
                    old_prod_count = lev.prods[val.name];
                end
                gGlobalPlayerInfo.gProducts[val.name] = prod_count + tonumber(val.value) - old_prod_count;
                lev.prods[val.name] = tonumber(val.value);
            end
        end
    end
end

function SayEndTrial()
    if (all_game_complete == 1) then
        if (GetConfig("firstpeek") == "1") then
            DisplayDialog { "scripts/ok.lua", body ="end_trial_message",title = "title_end_trial_message"};
        end
    end
end

function InitControlsValue()
    
    if (gGameMode==0) then
        EnableWindow("control_endless",false);
        EnableWindow("control_story",true);
    else
        EnableWindow("control_endless",true);
        EnableWindow("control_story",false);
    end
    iState = 6;
    -- если нету информации то значит это окно перед уровнем
    is_empty = 0;
    --levelnum_was_inc = 0;
    --CPP_FlashButton("TrophyRoomButton",0);
    if (end_level_info == nil) then
        is_empty = 1;
    else
        if (end_level_info.level_result == nil) then
            is_empty = 1;
        end
    end
    if (is_empty == 1) then
        setDefLevelInfo(nil,0); -- произведем установку значений
        iState = 99; --отключим таймер
    end
--[[    
    if (end_level_info.description_line1~=nil and end_level_info.description_line1.value ~= "empty_text") then
        SetControlNumParameters("value_line1","0"); --end_level_info.value_line1.value);
        SetLabel("money_line1"," x "..end_level_info.value_line1.score);
    end
    if (end_level_info.description_line2~=nil and end_level_info.description_line2.value ~= "empty_text") then
        SetControlNumParameters("value_line2","0"); --end_level_info.value_line2.value);
        SetLabel("money_line2"," x "..end_level_info.value_line2.score);
    end
    if (end_level_info.description_line3~=nil and end_level_info.description_line3.value ~= "empty_text") then
        SetControlNumParameters("value_line3","0"); --end_level_info.value_line3.value);
        SetLabel("money_line3"," x "..end_level_info.value_line3.score);
    end
    if (end_level_info.description_line4~=nil and end_level_info.description_line4.value ~= "empty_text") then
        SetControlNumParameters("value_line4","0"); --end_level_info.value_line4.value);
        SetLabel("money_line4"," x "..end_level_info.value_line4.score);
    end
    if (end_level_info.description_line5~=nil and end_level_info.description_line5.value ~= "empty_text") then
        SetControlNumParameters("value_line5","0"); --end_level_info.value_line5.value);
        SetLabel("money_line5"," x "..end_level_info.value_line5.score);
    end
    if (end_level_info.description_line6~=nil and end_level_info.description_line6.value ~= "empty_text") then
        SetControlNumParameters("value_line6","0"); --end_level_info.value_line6.value);
        SetLabel("money_line6"," x "..end_level_info.value_line6.score);
    end
--]]
    if (end_level_info.bonuses_score ~= nil) then 
        if (end_level_info.bonuses_score.line1 ~= nil) then
            SetLabel(pref.."bonus_value_line1",end_level_info.bonuses_score.line1.value);
            SetLabel(pref.."bonus_description_line1",GetString(end_level_info.bonuses_score.line1.description));
        else
            SetLabel(pref.."bonus_value_line1","");
            SetLabel(pref.."bonus_description_line1","");
        end
        if (end_level_info.bonuses_score.line2 ~= nil) then
            SetLabel(pref.."bonus_value_line2",end_level_info.bonuses_score.line2.value);
            SetLabel(pref.."bonus_description_line2",GetString(end_level_info.bonuses_score.line2.description));
        else
            SetLabel(pref.."bonus_value_line2","");
            SetLabel(pref.."bonus_description_line2","");
        end
        if (end_level_info.bonuses_score.line3 ~= nil) then
            SetLabel(pref.."bonus_value_line3",end_level_info.bonuses_score.line3.value);
            SetLabel(pref.."bonus_description_line3",GetString(end_level_info.bonuses_score.line3.description));
        else
            if (gGameMode==0) then
                SetLabel(pref.."bonus_value_line3","");
                SetLabel(pref.."bonus_description_line3","");
            end
        end
    end

    if (end_level_info.description_line7~=nil) then    
        SetControlNumParameters(pref.."value_line7",end_level_info.value_line7.value);
    end    
    SetControlNumParameters(pref.."value_line8","0"); --end_level_info.value_line5.value);
    SetControlNumParameters(pref.."score_without_bonus","0");
    --SetLabel("total_money",""..gGlobalPlayerInfo.gMoney);
    if (gGameMode==0) then
        SetLabel("value_line9",""..gGlobalPlayerInfo.gScore); --total_scores
        SetControlParameters("description_line9",end_level_info.description_line9,1);
    end
--[[
    SetControlParameters("description_line1",end_level_info.description_line1,1);
    SetControlParameters("description_line2",end_level_info.description_line2,1);
    SetControlParameters("description_line3",end_level_info.description_line3,1);
    SetControlParameters("description_line4",end_level_info.description_line4,1);
    SetControlParameters("description_line5",end_level_info.description_line5,1);
    SetControlParameters("description_line6",end_level_info.description_line6,1);
--]]    
    SetControlParameters(pref.."description_line7",end_level_info.description_line7,1);
    SetControlParameters(pref.."description_line8",end_level_info.description_line8,1);
    
    if (is_empty ~= 1) then
        end_level_info.with_bonus_score = tonumber(end_level_info.value_line8.value);
        
        local expert_true = 0;
        --SetLabel(pref.."value_line8",""..end_level_info.value_line8.value);
        
        local pers_img = GetPersonageFromLevComp(gGlobalPlayerInfo.gLevelNum);
        if( end_level_info.level_result.value == nil or end_level_info.level_result.value =="0")then
--проигрыщ
            PlayMusic(musicLOSE, 1);   
            local levsco_nobon = end_level_info.with_bonus_score - end_level_info.value_line7.value;
            SetLabel(pref.."score_without_bonus",""..levsco_nobon);
            
            EnableWindow("image_res_win",false);
            EnableWindow("image_res_lost",true);
            EnableWindow("title1_win",false);
            EnableWindow("title1_lose",true);
            EnableWindow("title2_lose",true);
            SetBitmap("backgroundimage","backgrounds/res_lose.png",1);

            SetBitmap("image_res_lost",coord_img_res[pers_img].lose.image,1)
            SetPosition("image_res_lost",coord_img_res[pers_img].lose.x,coord_img_res[pers_img].lose.y);
            
            EnableWindow( "next_level_button", false);  
            EnableWindow( "replay_level", true);  
            EnableWindow( "main_menu_btn", true);
            EnableWindow( "replay_level_win", false);
            iState = 99;
        else
-- выиграли
            PlayMusic(musicWIN, 1); 
            SetBitmap("backgroundimage","backgrounds/res_win.png",1);
            EnableWindow("title1_win",true);
            EnableWindow("title1_lose",false);
            EnableWindow("title2_lose",false);
            
            if (gGameMode == 0) then
                EnableWindow( "replay_level", false);  
                EnableWindow( "next_level_button", true);  
                EnableWindow( "main_menu_btn", false);
                EnableWindow( "replay_level_win", true);
            else
                EnableWindow( "next_level_button", false);  
                EnableWindow( "replay_level", true);  
                EnableWindow( "main_menu_btn", true);
                EnableWindow( "replay_level_win", false);
                SetLabel("txtBtnRL",GetString("replay_level_endless") );
                SetLabel("title1_win",GetString("title_levcomp_1_win_endless"));
            end

            EnableWindow("image_res_win",true);
            EnableWindow("image_res_lost",false);

            SetBitmap("image_res_win",coord_img_res[pers_img].win.image,1)
            SetPosition("image_res_win",coord_img_res[pers_img].win.x,coord_img_res[pers_img].win.y);

            --if( end_level_info.level_result.value == 2)then 
            -- у нас закончился бонус уровень, в нём нельзя выиграть или проиграть
            --end    
            local last_level_num = CPP_GetLastLevelNum();
            if (gGlobalPlayerInfo.gLevelNum <= last_level_num) then
                --levelnum_was_inc = 1;
                --gGlobalPlayerInfo.gMoney = gGlobalPlayerInfo.gMoney + tonumber(end_level_info.total_money.value);
                gGlobalPlayerInfo.gScore = gGlobalPlayerInfo.gScore + end_level_info.with_bonus_score;
                if (gGameMode == 0) then
                    local expert = 0;
                    if (end_level_info.level_result.expert ~= nil) then
                        expert = tonumber(end_level_info.level_result.expert);
                    end
                    
                    if (expert ~= 0 ) then
                        expert_true = 1;
                    end

                    
                    SetGotScoresAndProducts(end_level_info.with_bonus_score,gGlobalPlayerInfo.gLevelNum,expert);
                    CheckTrophyes(gGlobalPlayerInfo.gScore);
                    CPP_LogParams(0,gGlobalPlayerInfo.gScore,gGlobalPlayerInfo.gLevelNum);
                else
                    -- если надо сравним и запишем
                    CPP_LogParams(0,end_level_info.with_bonus_score,gGlobalPlayerInfo.gLevelNum);
                end
                -- для теста перехода gGlobalPlayerInfo.gLevelNum = 13;
                --gGlobalPlayerInfo.gLevelNum = gGlobalPlayerInfo.gLevelNum + 1;
                if ((gGlobalPlayerInfo.gLevelNum + 1 ) > gGlobalPlayerInfo.gLevelNumMax) then
                    gGlobalPlayerInfo.gLevelNumMax = gGlobalPlayerInfo.gLevelNum + 1;
                    SetStatParamMaxI("LatestLevelStory",gGlobalPlayerInfo.gLevelNumMax);
                    LastLevelIsNowWin = true;
                end
                if (gGameMode == 0) then
                    if (gGlobalPlayerInfo.gLevelNum >= last_level_num) then all_game_complete = 1; end
                end
            end
            
        end     
        if (expert_true == 0) then
            EnableWindow("level_res_img",false);
        end

        --gGlobalPlayerInfo.gLevelNum = gGlobalPlayerInfo.gLevelNumMax;
        CPP_WriteGO();
        
    else
        EnableWindow( "replay_level", false);  
        EnableWindow( "next_level_button", true);  
        EnableWindow("level_res_img", false);       
    end
    if (end_level_info.level_text~=nil and end_level_info.level_text.value ~= "") then
        if (gGameMode == 0) then
            end_level_info.level_text.value = end_level_info.level_text.value..gGlobalPlayerInfo.gLevelNum;
        else
            end_level_info.level_text.value = "endl_result_description"..gGlobalPlayerInfo.gLevelNum;
        end
    end
    if (end_level_info.next_level_text~=nil and end_level_info.next_level_text.value ~= "") then
        end_level_info.next_level_text.value = end_level_info.next_level_text.value..gGlobalPlayerInfo.gLevelNum;
    end
    SetControlParameters("level_text",end_level_info.level_text,1);
    --SetControlParameters("next_level_text",end_level_info.next_level_text,1);
    --SetControlParameters("backgroundimage", end_level_info.back_image,0);       
end
calc_step_state = 0;
InitControlsValue();

function CalcStep(Value)
    calc_step_state = 1;
    step2 = 0;
   
    if (Value < 30) then
        step = 2;
        return;
    end
    step = ToInt( Value * 0.1 );
end

function AnimateValue(aControlName,aParam1,aParam2,aNextState)
    local value = 0;
    if (tonumber(aParam2) < 0 or GetLabel(aControlName) == "") then 
        iState = aNextState;
        calc_step_state = 0;
        return; 
    end
    value = tonumber(GetLabel(aControlName));
    if (calc_step_state == 0) then
        CalcStep(tonumber(aParam2) - tonumber(aParam1));
        CPP_PlaySound("counting",1);
    end
    if (value == tonumber(aParam1)) then
        --CalcStep(tonumber(aParam2) - tonumber(aParam1));
        if (value == tonumber(aParam2)) then
            iState = aNextState;
            calc_step_state = 0;
            CPP_StopSound("counting");
            return;
        end
        CPP_LC_SetColor(aControlName,1);
    end
    value = value + step;
    if (value >= tonumber(aParam2)) then
        SetLabel(aControlName,aParam2);
        iState = aNextState;
        calc_step_state = 0;
        CPP_StopSound("counting");
        CPP_LC_SetColor(aControlName,0);
    else
        SetLabel(aControlName,""..value);
    end
end
-- перетекание одновременное одного в другое
-- у первого убывает до 0  увторого растет до до aEndParamAsc
function AnimateValue2(aControlNameDesc,aControlNameAsc,aEndParamAsc,aNextState)
    local value_desc = 0;
    local value_asc = 0;
    value_desc = tonumber(GetLabel(aControlNameDesc));
    value_asc = tonumber(GetLabel(aControlNameAsc));
--[[
    if (tonumber(aEndParamAsc) <= value_asc or step == 0) then 
        SetLabel(aControlNameDesc,"0");
        SetLabel(aControlNameAsc,aEndParamAsc);
        CPP_LC_SetColor(aControlNameAsc,0);
        iState = aNextState;
        calc_step_state = 0;
        return; 
    end
 --]]
    if (calc_step_state == 0) then
        CalcStep(tonumber(GetLabel(aControlNameDesc)));
        if (step == 9) then
            SetLabel(aControlNameDesc,"0");
            SetLabel(aControlNameAsc,aEndParamAsc);
            iState = aNextState;
            calc_step_state = 0;
        end
        step2 = (tonumber(aEndParamAsc) - tonumber(GetLabel(aControlNameAsc)) ) / (tonumber(GetLabel(aControlNameDesc)) / step);
        CPP_LC_SetColor(aControlNameAsc,1);
    end
    value_desc = value_desc - step;
    if (value_desc <= 0) then
        SetLabel(aControlNameDesc,"0");
        SetLabel(aControlNameAsc,aEndParamAsc);
        iState = aNextState;
        calc_step_state = 0;
        CPP_LC_SetColor(aControlNameAsc,0);
    else
        value_asc = value_asc + step2;
        SetLabel(aControlNameDesc,""..value_desc);
        SetLabel(aControlNameAsc,""..value_asc);
    end
end

function OnTimer()
    if (is_empty == 1) then return; end
    temp_bonus_score = 0;
--[[    
    if (iState == 0) then
        if(end_level_info.value_line1==nil)then iState=iState+1;
        else
            AnimateValue("value_line1","0",end_level_info.value_line1.value,1);
            return;
        end
    end
    if (iState == 1) then
        if(end_level_info.value_line2==nil)then iState=iState+1;
        else   
            AnimateValue("value_line2","0",end_level_info.value_line2.value,2);
            return;
        end;        
    end
    if (iState == 2) then
        if(end_level_info.value_line3==nil)then iState=iState+1;
        else   
            AnimateValue("value_line3","0",end_level_info.value_line3.value,3);        
            return;
        end;        
    end
    if (iState == 3) then
        if(end_level_info.value_line4==nil)then iState=iState+1;
        else   
            AnimateValue("value_line4","0",end_level_info.value_line4.value,4);        
            return;
        end;        
    end
    if (iState == 4) then
        if(end_level_info.value_line5==nil)then iState=iState+1;
        else   
            AnimateValue("value_line5","0",end_level_info.value_line5.value,5);        
            return;
        end;        
    end
    if (iState == 5) then
        if(end_level_info.value_line6==nil)then iState=iState+1;
        else   
            AnimateValue("value_line6","0",end_level_info.value_line6.value,6);        
            return;
        end;        
    end
--]]    
    if (iState == 6) then
        --local tVal = gGlobalPlayerInfo.gScore - end_level_info.with_bonus_score;
        local res = tonumber(end_level_info.value_line7.value);
        if(not res)then res = 0; end;
        
        local tVal = end_level_info.with_bonus_score - res;
        AnimateValue(pref.."score_without_bonus","0",""..tVal,7);  -- +gGameMode = чтобы пропустить анимацию посл.блока
        return;
    end
    if (iState == 7) then
        if(end_level_info.with_bonus_score==nil)then iState=iState+1;
        else   
            AnimateValue(pref.."value_line8","0",""..end_level_info.with_bonus_score,8+gGameMode);
        end;    
        return;
    end
    if (iState == 8) then
        --local tVal = gGlobalPlayerInfo.gScore - end_level_info.with_bonus_score;
        if (gGameMode==0) then
            local tVal = GetLabel("value_line9");
            AnimateValue("value_line9",""..tVal,""..gGlobalPlayerInfo.gScore,9);
        end
        return;
    end
end

