gGameMode=0;
life_cycle = {};
-- массив для сохранения бонусных очков, должен соответствовать BonusMoney на уровнях
bonuses = {
    Goal=0;
    Car=0;
    Telephon=0;
};
DayFramesCount = 52;
StopFrames     = 6; -- количество фреймов .которые проигруются уже после окончания всех дел на уровне
StopFramesTime = 3; -- время, за которое проигрываются отложеные фреймы

--combos={};
def_preview_table=
{
    initor= {
                not_disabled=1; -- туториал работает даже тогда, когда туториалы отключены из меню опций
            },

    message={
                stop=1,
            }, 
    post_block = 1; -- после закрытия туториала игра остаётся заплакирыванной до появления следующего туториала        
};
-------------------------------------------------------------------------------------------------------
combos = {
    ignore_obj = {
        eatmachine=1;
        eatmachine_m=1;
        eatmachine4=1;
        eatmachine_m4=1;
        telephon=1;  
        lemonad=1;  
        telephon4=1;  
        lemonad4=1;
        dog_point=1;
        dog=1;
        wolf=1;
        crow=1;
        brother=1;
        plank = 1;
        firewood = 1;
        chopping = 1;
    };
    actions = {
        all = { 10, 10, 20, 30 };
    };
    objects = {
        all = { 0, 15, 25, 35 };
    };
};
-------------------------------------------------------------------------------------------------------
-- это для преобразования грядки в помидоры,кукурузу или тыквы
--для создания ворон
TomatoChilds = { crow1 = { {0, params=CustomCrow} },tomatos = { {0, params=""} } };
--создание corn
CornChilds = { corns = { {0, params=""} } };
--создание corn
PumpkinChilds = { pumpkin = { {0, params=""} } };

function ChangeOnTomato(aSubID)
    CPP_ReplaceObject(aSubID,'tomato',CustomTomato,'TomatoChilds');
end
function ChangeOnCorn(aSubID)
    CPP_ReplaceObject(aSubID,'corn',CustomCorn,'CornChilds');
end
function ChangeOnPumpkin(aSubID)
    CPP_ReplaceObject(aSubID,'pumpkins',CustomPumpkin,'PumpkinChilds');
end

function CheckProductsCount(aKey, aValue)
    ProductsCount = ProductsCount + 1;
    return nil;
end

function CreateNeedProductsList(aKey, aValue)
    CPP_GameMessage(8,aKey,aValue);
    return nil;
end


function ShowPreloadScreen()
    obj = GameObject:Get();
--[[    
    if( Preload_tutorial_table ==nil )then
        if( obj.Params.PreviewMessage )then
            Preload_tutorial_table=def_preview_table;
            Preload_tutorial_table.message.msg = obj.Params.PreviewMessage;           
            ShowPreloadScreen();
        end
    else
        CPP_GameMessage(11,"Preload_tutorial_table",0);
    end   
--]]    
    if (obj.Params.PreviewMessage == nil) then aMessage = "";
    else    aMessage = obj.Params.PreviewMessage;   end
    if (obj.Params.PreviewImage == nil) then aImage = "";
    else    aImage = obj.Params.PreviewImage;       end
    if (obj.Params.WinScoresLimit == nil) then aGoal = 0;
    else    aGoal = obj.Params.WinScoresLimit;      end
    if (obj.Params.ExpertScoresLimit == nil) then aExpert = 0;
    else    aExpert = obj.Params.ExpertScoresLimit; end
        
    if(obj.Params.StartTutorialWait==1)then
        CPP_GameMessage(11,"def_preview_table",0);
    end;

    CPP_GameMessage(29,"ShowPreviewWnd('"..aMessage.."','"..aImage.."',"..aGoal..","..aExpert..");",0);
end
-------------------------------------------------------------------------------------------------------
function OnInit()

    obj = GameObject:Get();
    obj.Params.deltaDay = obj.Params.levelTime / DayFramesCount;
    
    obj.WaitPreview = (obj.PreviewMessage ~= nil);
    
    CPP_GameMessage(111,"day",-1);

    bonuses.Goal=0;
    bonuses.Car=0;
    bonuses.Telephon=0;

-- Выставляем солнышко
    obj.Params.CountFrames = CPP_GameMessage(25, "", obj.Params.levelTime - StopFramesTime+1);
    CPP_GameMessage(26, "", obj.Params.CountFrames - StopFrames);
    CPP_GameMessage(27, "", 1);
    
    --ScriptDump("1");
    if(aObj.NeedProducts)then
        ProductsCount =0;
        table.foreach( aObj.NeedProducts, CheckProductsCount );
        --ScriptDump("deflevel.lua:OnInit():ProductsCount:"..ProductsCount);
        if( ProductsCount>0)then
            CPP_GameMessage(6,"",ProductsCount);
            table.foreach( aObj.NeedProducts, CreateNeedProductsList );
        end          
    end    
end
-------------------------------------------------------------------------------------------------------
AngerScores = {
-- при потере меньше одного первый раз очки=first_minus, а дальше к этому прибавляется еще по delta за каждый раз, пока в минусах
--сколько сердечек сейчас, после потери
--           1    2   3   4   5  
    all = {  25, 0, 0,  0,  0, delta = 5, first_minus = 25 };  
};
-- реакция на потерю сердечка
-- aObjId - обьект, aCurHearts - сколько счас стало сердечек, -1 если 0 и меньше
function OnAngerScore(aObjId, aCurHearts,aKoef)
    local tableScore;
    if (AngerScores[aObjId]) then 
        tableScore = AngerScores[aObjId]; 
    else
        tableScore = AngerScores["all"]; 
    end
    local ind = 1;
    local score = 0;
    if (aCurHearts <= 0) then
        score = tableScore.first_minus + tableScore.delta * (aKoef - 1);
    else
        if (aCurHearts <= table.getn(tableScore)) then
            score = tableScore[aCurHearts];
        end
    end
    if (score ~= 0) then
        local aNullCombo = {score=0;koef=1;value=0;};
        OnSetScore( -score, aNullCombo, aNullCombo, 0,"",0);
    end
    return score;
end
-------------------------------------------------------------------------------------------------------
function OnCombos(aSubObjId, aSubObActionID)
    local aObj = GameObject:Get();
    if (aSubObjId ~= "") then
        if (combos.ignore_obj[aSubObjId] == nil) then
            local indexCombo = 0;
            --за повторение действия
            if (aObj.Params.LastActionSeries == nil or aObj.Params.LastActionName == nil) then
                aObj.Params.LastActionSeries = 1;
                aObj.Params.LastActionName = aSubObActionID;           
            else
                if (aObj.Params.LastActionName == aSubObActionID) then
                    aObj.Params.LastActionSeries = aObj.Params.LastActionSeries + 1;
                else
                    aObj.Params.LastActionSeries = 1;
                    aObj.Params.LastActionName = aSubObActionID;           
                end
            end
            --за повторение действия над обьектом одного типа
            if (aObj.Params.LastObjSeries == nil or aObj.Params.LastObjName == nil) then
                aObj.Params.LastObjSeries = 1;
                aObj.Params.LastObjName = aSubObjId;           
            else
                if (aObj.Params.LastObjName == aSubObjId) then
                    aObj.Params.LastObjSeries = aObj.Params.LastObjSeries + 1;
                else
                    aObj.Params.LastObjSeries = 1;
                    aObj.Params.LastObjName = aSubObjId;           
                end
            end
        end
    end
end

function ClearCombos()
    local aObj = GameObject:Get();
    aObj.Params.LastActionSeries = 0;
    aObj.Params.LastActionName = "";
    aObj.Params.LastObjSeries = 0;
    --aObj.Params.LastObjName = "";
end

StatParamsActions=
{
    eating   = "FoodChain";
    watering = "WaterChain";
    keeping  = "StockChain";
    egging = "EggsChain";
    milking = "MilkChain";
}

StatParamsObj=
{
    egg="EggsChain";
    milk="MilkChain";
}
-------------------------------------------------------------------------------------------------------
function OnAction(aAction, aId, aParam, aSubObjKoef, aSubObActionKoef,aWhatDoing)


    local aObj = GameObject:Get();
    local aStat = aObj.Scores;  
    local aComboActionScores = {score=0;koef=1;value=0;};
    local aComboObjScores = {score=0;koef=1;value=0;};
    local aKoof = 0;    
    

    
    if( aStat[aId.."__"..aAction] == nil )then
        if(aStat[aAction] ~= nil)then
            aKoof = aStat[aAction];
        end
    else
        aKoof = aStat[aId.."__"..aAction];
    end
    if (aSubObActionKoef > 1) then
        
        if StatParamsActions[aWhatDoing] then
            AddStatParamI(StatParamsActions[aWhatDoing],1);
        end
        
        SetStatParamMaxI("MaxChains", aSubObActionKoef);
        --считаем комбо
        if (aKoof ~= 0) then
            aComboActionScores.koef = aSubObActionKoef;
            aComboActionScores.value = aKoof * aParam;
            aComboActionScores.score = aComboActionScores.value * aSubObActionKoef;
        end
    end
    if (aSubObjKoef > 1) then
        
        --за повторение действия над обьектом одного типа
        --считаем комбо
        --local comboObjArr = combos.objects[aSubObjId];
        --if (comboObjArr == nil) then
        comboObjArr = combos.objects["all"];
        --end
        if (comboObjArr) then
            indexCombo = aSubObjKoef;
            --начисление очков по таблице
            --if (indexCombo > table.getn(comboObjArr)) then
            --    indexCombo = table.getn(comboObjArr);
            --end
            --aComboObjScores = comboObjArr[indexCombo];
            aComboObjScores.koef = aSubObjKoef;
            aComboObjScores.value = comboObjArr[1];
            aComboObjScores.score = comboObjArr[1] * aSubObjKoef;
        end
    end
    local bonus_score = 0;
    if (GameObject.temp_bonus_score ~= nil) then 
        bonus_score = GameObject.temp_bonus_score;
-- ScriptDump("temp_bonus_score"..bonus_score);        
        GameObject.temp_bonus_score = 0;
    end
    local product_score = 0;
    if (GameObject.temp_product_score ~= nil) then
        product_score = GameObject.temp_product_score;
-- ScriptDump("temp_product_score"..product_score);
        GameObject.temp_product_score = 0;
    end
    --if (bonus_score > 0) then
        --ScriptDump("bonus_score="..bonus_score);
        --ScriptDump("aParam="..aParam);
        --ScriptDump("aKoof="..aKoof);
        --ScriptDump("aComboActionScores="..aComboActionScores.." aComboObjScores="..aComboObjScores);
    --end
    if (aKoof ~= 0 or product_score ~= 0)then
        local bon_sco = 0; --aComboActionScores.score - aKoof * aParam + aComboObjScores.score + bonus_score;
        if (aComboActionScores.score <= 0) then
            bon_sco = aComboActionScores.score + aComboObjScores.score + bonus_score;
            GameObject.Statics.bonus_score = GameObject.Statics.bonus_score + bon_sco;
            OnSetScore( aKoof * aParam + product_score, aComboActionScores, aComboObjScores, bonus_score,aWhatDoing,0);
        else
            bon_sco = aComboActionScores.score - aComboActionScores.value + aComboObjScores.score + bonus_score;
            if (bon_sco >= 0) then
                GameObject.Statics.bonus_score = GameObject.Statics.bonus_score + bon_sco;
            end
            OnSetScore( product_score, aComboActionScores, aComboObjScores, bonus_score,aWhatDoing,1);
        end
    end
end
-------------------------------------------------------------------------------------------------------
function BonusMoneyVisit(aKey, aValue)
    if (aValue["active"] == 0) then return; end
    if (aValue[searchID] == nil) then return; end
    local score_bonus_BMV = 0;
    if (aValue["addition"] == 0) then
        score_bonus_BMV = aValue[searchID] * searchCount;
    else
        score_bonus_BMV = aValue[searchID];
    end
    searchValue = searchValue + score_bonus_BMV;
    if (bonuses[aKey] ~= nil) then
        bonuses[aKey] = bonuses[aKey] + score_bonus_BMV;
    end
end

function OnPreCalcProductScore(aProdId,aCount)
    if (GameObject.Money[aProdId] == nil) then return; end
    --по сути это вызов CPP_CreateProduct
    OnCreateProduct(aProdId,aCount);
    
    searchID = aProdId;
    searchCount = aCount;
    searchValue = GameObject.Money[aProdId] * aCount;
    GameObject.temp_product_score = searchValue;
    searchValue = 0;
    -- следим за достижением goal
    if (GameObject.Statics.score >= GameObject.Params.WinScoresLimit) then
        --вкл Goal
        GameObject.BonusMoney.Goal.active = 1;
    else
        GameObject.BonusMoney.Goal.active = 0;
    end
    table.foreach( GameObject.BonusMoney,  BonusMoneyVisit );
    GameObject.temp_bonus_score = searchValue;
    local aNullCombo = {score=0;koef=1;value=0;};
 --ScriptDump(""..aProdId);
    GameObject.Statics.bonus_score = GameObject.Statics.bonus_score + GameObject.temp_bonus_score;
    OnSetScore(GameObject.temp_product_score, aNullCombo, aNullCombo, GameObject.temp_bonus_score,"",2);
    GameObject.temp_product_score = 0;
    GameObject.temp_bonus_score = 0;
end


-- checks if the object can function
function OnEndCycle(aObjectID)
    return 1;
end
--marks cows appearing
function OnCreate(aObjectID,aProductName,aProductValue, aID)
    aObj = GameObject:Get();
    aObj.Statics.create_cow = aObj.Statics.create_cow + 1;
    
    if aObj.FlashObjects and aObj.FlashObjects[aObjectID] ~= nil then
        local must_act = false;
        local obj = aObj.FlashObjects[aObjectID];

        for i = 1, table.getn(obj) do
            obj[i] = obj[i] - 1;
            if obj[i]==0 then
                must_act = true;
            end
        end

        if obj.state then
            state = obj.state;
        else
            state = "particle";               
        end

        --ScriptDump(aObjectID.."   "..aID);
        
        if must_act then
            if aObj.WaitPreview==true then
                if aObj.FlashObjSignals==nil then
                    aObj.FlashObjSignals = {};
                end
                    aObj.FlashObjSignals[aID]=state;
            else
                CPP_RunStringSubId(aID, "CPP_SetAnimState('"..state.."');" );
            end
        end    
        
    end
    
    if (aProductValue ~= 0) then
        if (aObj.Statics[aProductName]) then
            if (aObj.Statics[aProductName] < 0) then
                aObj.Statics[aProductName] = 0;
            end
        end
    end
    return GetUpgradeParams(aObjectID);
end



function GetUpgradeParams(aObjectID)


    if not end_level_info then return ""; end

    if( not UpgradeObjects)then CreateObjectUpgrades();end;
    local ObjUp = UpgradeObjects[aObjectID];
    
    if( not ObjUp )then return ""; end;
    

    -- Список апгрейдов, уже
    local UpgradesInLevel = end_level_info.upgrades;
    if not UpgradesInLevel then return ""; end
    --upgrades={"lemonad"}
    
    local ObjUpgradesCount = table.getn( UpgradesInLevel );
    if(ObjUpgradesCount==0)then return "";end
    
    local inject="aObj=GameObject:Get();";

    --end_level_info={ upgrades={} 
    --
    
    for i = 1, ObjUpgradesCount do
        if ObjUp[UpgradesInLevel[i]] then
    
    
           local upgrade = Upgrades[ UpgradesInLevel[i]];
           
           if upgrade.target then pt = upgrade.target[aObjectID]; end
           
           if( pt and pt~="" and pt ~=1 )then
                inject = inject..pt;
           else      
               if( upgrade.params )then
                inject = inject..upgrade.params;
               end
           end
           
           if(upgrade.unblock)then     
               local UnblockCount = table.getn( upgrade.unblock );
               if( UnblockCount > 0)then
                    for j = 1, UnblockCount do
                        inject = inject.."CPP_AdjournUnblock('"..upgrade.unblock[j].."');";
                    end
               end
           end
        end
    end 
    return inject;
end


function AssignUpgradeToObject( aObj, aUpgrade)
    if not UpgradeObjects[aObj] then UpgradeObjects[aObj]={}; end
    UpgradeObjects[aObj][aUpgrade]="";
end


function UpgradeObjList(aKey, aValue)
    AssignUpgradeToObject( aKey, CurrentKey); 
end


function AddUpgrade(aKey, aValue)
    if not aValue.target then
        aValue.target = {level=""};
    end
    CurrentKey=aKey;
    table.foreach( aValue.target,  UpgradeObjList );
end

function CreateObjectUpgrades()
    UpgradeObjects={};
    
    if not Upgrades then return end
    table.foreach( Upgrades,  AddUpgrade );
    
    
--[[    if( not end_level_info or not end_level_info.upgrades)then return "" end;   

    local count = table.getn( end_level_info.upgrades );
    if( count == 0)then return end;
    
    for i = 1, count do
        local nupgrade = end_level_info.upgrades[i];
        local upgrade  = Upgrades[nupgrade];
    
        if( not upgrade.target )then
            upgrade.target = {"level"}
        end
        local tcount = table.getn( upgrade.target );
        if( tcount > 0)then
            for j = 1, tcount do                        
                local target = upgrade.target[j];
                if( UpgradeObjects[target])then
                    local tttable = UpgradeObjects[target];
                    tttable[ table.getn( upgrade.target ) ] = nupgrade;
                else
                    UpgradeObjects[target]= {nupgrade}
                end             
            end         
        end
    end
--]]
end

--where cows appear 
function WhereBorn(aId)
    if (aId == "cow") then  return "cowshed";  end
    if (aId == "sheep") then return "sheephouse"; end
    return "unknown";
end
--marks cows dissapeared
function OnDieObj(aObjectID,aEndCycle,aSubObjID)
    aObj = GameObject:Get();
    if (aEndCycle == 0) then
        if (aObjectID == "cow") then
            --CPP_SetScore(aObj.Scores.die_cow);
            aObj.Statics.real_die_cow = aObj.Statics.real_die_cow + 1;
        end
        if (aObjectID == "sheep") then
            --CPP_SetScore(aObj.Scores.die_sheep);
            aObj.Statics.real_die_sheep = aObj.Statics.real_die_sheep + 1;
        end
    end
    aObj.Statics.die_cow = aObj.Statics.die_cow + 1;
    if (aObj.Params.gameEnd == 1) then return; end
    
    local idCreator = WhereBorn(aObjectID);
    if (idCreator == "unknown") then return end;
end


--вызывается когда все продукты отнесены и игрок больше не управляет собыотиями на уровне
function OnFinishLevel()
    
    local musik="";
    if( isLevelWin() )then
        musik="win";
    else
        musik="lose";
    end
    --CPP_GameMessage(30, musik, 1);   
    
    CPP_GameMessage(25, "", StopFramesTime);   
    CPP_GameMessage(26, "", obj.Params.CountFrames);
    CPP_GameMessage(27, "", obj.Params.CountFrames - StopFrames);   
end


---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
function StartAjournEffects(aKey, aValue)
   CPP_RunStringSubId(aKey, "CPP_SetAnimState('"..aValue.."');" );
end
--checks the level time
function TimeTrigger()
    aObj = GameObject:Get();
    
    
    if aObj.WaitPreview~=nil then
        if FlashObjSignals~=nil then       
            table.foreach(aObj.FlashObjSignals, StartAjournEffects);
        end;
        aObj.WaitPreview = nil;
    end
    -- если время кончилось. посылаем игре об этом сообщения беспрервывно
    if (aObj.Params.gameEnd == 1) then 
        if( aObj.Params.iDayIsEnd == nil)then
            aObj.Params.iDayIsEnd = true;
        end
        CPP_GameMessage(0,"quit",0);
        return 1;
    end
    
    if( not aObj.Params.CryTime)then
        aObj.Params.CryTime = 10;
    end    
    -- если меньше времени уровня - отменяем создание всех обьектов
    -- если меньше времени будильника - даём звук будильника
    if (aObj.Params.levelTime <= 0) then 
        if( aObj.Params.gameEnd ~= 1)then
            CPP_StopSound("tick_tack");
            CPP_GameMessage( 13,  "", 0);        
        end
    
        aObj.Params.gameEnd = 1;
        CPP_GameMessage(111,"day",2);
    else
        if((aObj.Params.levelTime <= aObj.Params.CryTime) and (RoosterCry~=1))then
            RoosterCry = 1;
            CPP_PlaySound("tick_tack", 0);
        end
    end
    aObj.Params.levelTime = aObj.Params.levelTime - 1;
    return 1;
end

-- set score from cheat key
function SetScoreCheat(aScore)
    local aNullCombo = {score=0;koef=1;value=0;};
    OnSetScore( aScore, aNullCombo, aNullCombo, 0,"",0);
end


-- set score
--[[
aType=0 - обычные очки, aType=1 - комбо действия, aType=2 - продукт, aType=3 - комбо обьект - не используется
--]]
function OnSetScore(aScore,aComboActionScores, aComboObjScores, bonus_score,aActionName,aType)
--ScriptDump("OnSetScore="..aScore.."  aComboActionScores="..aComboActionScores.score.." aComboObjScores="..aComboObjScores.score);

    aObj = GameObject:Get();
    aObj.Statics.score = aObj.Statics.score + aScore + aComboActionScores.score + aComboObjScores.score + bonus_score;
    if( aObj.Statics.score < 0 )then aObj.Statics.score = 0; end;

    if (aType == 2) then  --продукт
        CPP_GameMessage(28, "a", aScore + bonus_score);  --очки за продукт + бонус вместе
    else
        if (aType == 1 or aComboActionScores.score > 0) then  --комбо действие
            CPP_GameMessage(24, aActionName, aComboActionScores.koef * 1000 + aComboActionScores.score);
        else
            if (aType == 3 or aComboObjScores.score > 0) then  --комбо обьект
                CPP_GameMessage(24, aActionName, aComboObjScores.koef * 1000 + aComboObjScores.score);
            else
                CPP_GameMessage(22, "a", aScore);
            end
        end
        if bonus_score~= 0 then 
            CPP_GameMessage(22, "d", bonus_score);
        end
    end
    if (gGameMode == 0) then
        if( aObj.Statics.score >= aObj.Params.WinScoresLimit and aObj.Params.winflag==nil )then
            aObj.Params.winflag=true;
            CPP_GameMessage(5,"WinGame",0);
            CPP_GameMessage(5,"WinParticle",0);                                    
            CPP_PlaySound("achieved_goal",0);
        end   
        if( aObj.Statics.score >= aObj.Params.ExpertScoresLimit and aObj.Params.expertflag==nil )then
            aObj.Params.expertflag=true;
            CPP_GameMessage(5,"ExpertGame",0);
            CPP_GameMessage(5,"ExpertParticle",0);            
            CPP_PlaySound("achieved_expert",0);
        end
    end
    CPP_GameMessage(2, "", aObj.Statics.score);
    OnScoreChanged(aObj.Statics.score);
    return aObj.Statics.score;
end

--для бесконечного уровня
function OnScoreChanged(aScore)
end 

--collect products statistics
function OnCreateProduct(aId,aCount)
    aObj = GameObject:Get();
    if(aObj.Statics[aId])then
        aObj.Statics[aId] = aObj.Statics[aId]+ aCount;
    else
        aObj.Statics[aId] = aCount; 
    end 
    
    if( aObj.NeedProducts and aObj.NeedProducts[aId] )then
        CPP_GameMessage(7,aId, aObj.Statics[aId]);
    end
end

function CheckWinParameter(aKey, aValue)
    if( not aObj.Statics[aKey] or aObj.Statics[aKey] < aValue)then
        WinFlag = 0;
        return nil;
    end
    return 1;
end

-- winning level conditions
function isLevelWin()
    aObj = GameObject:Get();
    WinFlag = 1;
    if(aObj.NeedProducts)then
        table.foreach( aObj.NeedProducts, CheckWinParameter );
    end
    if(aObj.Params.WinScoresLimit and GetStatics().score < aObj.Params.WinScoresLimit) then
        return 0;
    end
    return WinFlag;    
end
-- если aLevelEnd = 0 то это вызов перед уровнем
function setLevelInfo(aLevelEnd)
    aObj = GameObject:Get();
    setDefLevelInfo(aObj,1);
end
-- для читов
function setCheatLevelInfo(aSetWin)
    aObj = GameObject:Get();
    setDefLevelInfo(aObj,1);
    if (aSetWin == 0) then  --мы проиграли
        end_level_info.level_text.value = "result_description_lose";
        end_level_info.level_result.value = "0";
        SetStatParamI("EndState", 1);       
    else
        end_level_info.level_text.value = "result_description_win";
        end_level_info.level_result.value = "1";
        SetStatParamI("EndState", 0);
    end
end

-- для бесконечного уровня
function UpgradesForBuyingToCPP(aLastIndex)
    aObj = GameObject:Get();
    available_upgrades = { };
    local index_available_upgrades = 1;
    if (aObj.UpgradesForBuying == nil) then return; end
    for i = 1, aLastIndex do
        if (aObj.UpgradesForBuying[i].was_used == 0) then
            available_upgrades[index_available_upgrades] = {};
            available_upgrades[index_available_upgrades].text = aObj.UpgradesForBuying[i].upgrade.text;
            available_upgrades[index_available_upgrades].image = aObj.UpgradesForBuying[i].upgrade.image;
            available_upgrades[index_available_upgrades].doit = aObj.UpgradesForBuying[i].upgrade.doit;
            available_upgrades[index_available_upgrades].index = ""..i;
            index_available_upgrades = index_available_upgrades + 1;
            --ScriptDump("CheckUpgradesForBuying:"..aObj.UpgradesForBuying[aKey].upgrade.text);
        end
    end
end

-- получить след.жизненный цикл для обьекта из списка его жизненных циклов
function GetLifeCycleAsStr(aObjectID)
    if (life_cycle[aObjectID] == nil) then return ""; end
    local objTables = life_cycle[aObjectID];
    if (life_cycle.indexes == nil) then life_cycle.indexes = {}; end
    if (life_cycle.indexes[aObjectID] == nil) then life_cycle.indexes[aObjectID] = 0; end
    local index = life_cycle.indexes[aObjectID] + 1;
    if (index < 1 or index > table.getn(objTables))  then index = 1; end
    life_cycle.indexes[aObjectID] = index;
    local objTable = objTables[index];
    local sizeObjTable = table.getn(objTable);
    s = "life_cycle={";
    local row;
    local count = 0;
    for ind = 2, sizeObjTable, 1 do
        row = objTable[ind];
        s = s.."{ '"..row[1].."', "..row[2].." };";
        count = count + 1;
    end
    local firstDelay = 0;
    if (sizeObjTable > 0) then
        row = objTable[1];
        firstDelay = row[2];
    end
    s = s.."}; GameObject.Params.first_delay_desire={ "..firstDelay.." };";
    if (count == 0) then s = ""; end
    return s;
end

--НЕ УДАЛЯЙТЕ, заказ по телефону по умолчанию
function TelephoneOrder()
    if (GameObject.BonusMoney.Telephon == nil) then return; end;
    GameObject.BonusMoney.Telephon.active=1;
end
-- проинитить кресло
function GetRelaxPersCount()
    aObj = GameObject:Get();
    local relaxPers = 0;
    if (aObj.Objects.mother ~= nil) then 
        relaxPers = relaxPers + 1;
    end
    if (aObj.Objects.dad ~= nil) then 
        relaxPers = relaxPers + 1;
    end
    return relaxPers;
end

function GetLevelScore()
    return GameObject.Statics.score;
end

-- получить ИД обьекта куда нести продукт aProdID
function WhereCarryProduct(aProdID)
    if (aProdID == nil) then return; end
    aObj = GameObject:Get();
    if (aObj.BonusMoney.Telephon.active == 1 and aObj.BonusMoney.Car.active == 1) then
        if (aObj.BonusMoney.Telephon[aProdID] > 0) then
            --разрулить car или car1
            if (GameObject.Params.CarSubID == nil) then
                GameObject.Params.CarSubID = CPP_FindObj("car");
                if (GameObject.Params.CarSubID == 0) then
                    GameObject.Params.CarSubID = CPP_FindObj("car1");
                end
            end
            if (GameObject.Params.CarSubID > 0) then
                CPP_RunStringSubId(GameObject.Params.CarSubID,"IncProduct();");
            end
        end
    end
end
