
require "LP_Logic.lua"
require "gui.lua"

FirstTimeNoItems = true;
ShowMiddleHist = false; -- показывать ли сейчас "историю в середине итерации"?
CurHistTextWasShown = false;
Done = false

function ClearAllParam()
	FirstTimeNoItems = true;
	ShowMiddleHist = false;
	CurHistTextWasShown = false;
	Done = 0;
	gameInfo:setLocalString("NameLetter", "")
	gameInfo:setLocalString("TalkHistoryISpyText", "");
end

function RandomHistory()
	local r = Random("StrangePhone", 1, 3);
	if (Random("rrr", 1, 2) == 1) then 
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetDialog("StrangePhone"..r, 1)	
		gameInfo:setLocalInt("RandomPhone", r)
	else 
		if (LP_GetPurchaseProgress("Golf") > 0 and math.random(1, 3) == 1) then 
			gameInfo:setLocalString("NameNewspaper", "StrangeNewspaper3");
			gameInfo:setLocalString("NameLastNewspaper", "StrangeNewspaper3");
		elseif (LP_GetPurchaseProgress("Kennel") > 0 and math.random(1, 3) == 2) then 
			gameInfo:setLocalString("NameNewspaper", "StrangeNewspaper2");
			gameInfo:setLocalString("NameLastNewspaper", "StrangeNewspaper2");
		end;
	end;
end;

function HistoryToNewIter()
	local Iter = gameInfo:getGardenIter()
	local LastHistory = gameInfo:getLocalStringOrDef("LastHistory", "StartIter1");
	local s
	if FirstTimeNoItems or math.random(1, 5) < 3 then
		s = "HistoryToNewIter"..Iter+1
	else
		s = "ToNewIter"..math.random(1, 5)
	end;
	LP_ClearTalkAction(0.5);
	LP_FastFinishCurrentBehav();
	LP_WalkTo(Point(740, 353), 5, 3.5);
	LP_PlayAnim("Tutorial4", 0.7, 1, true, true);
	AddTalkWindowToLastAction(0.0, s, 7.0); 
	LP_WalkTo(Point(641, 73), 5, 3.5);
	LP_PlayAnim("Joy2", 0.7, 1, true, true);
	AddTalkWindowToLastAction(0.0, "ToNewIterStartButton"..math.random(1,4), 7.0); 
	FirstTimeNoItems = false;
end;

function OstinCommentAfterLevel(v, i, money, TotalIterCount, AfterLevel, AfterTalkAboutSell, isStop, ClearTalkWindow)
	local LevelMoney = gameInfo:getLocalIntOrDef("MoneyInLevel", 0)			-- сколько игрок заработал за последний уровень
	local PlayerAwayFromLeave = gameInfo:getLocalBoolOrDef("PlayerAwayFromLeave", false) -- игрок вышел через меню, не закончил уровень
	local LevelTime = gameInfo:getLocalIntOrDef("OldLevelTime", 500) -- время установленное на уровень 
	local passTime = gameInfo:getLocalIntOrDef("passTime", 100) -- сколько потратили на уровень
	local remainingTime = LevelTime - passTime;
	local GardenProgress = gameInfo:getLocalStringOrDef("GardenProgress", "00000000000000000000");
	local RelaxMode = gameInfo:isRelaxMode();
	local txt = "";
	local t3 = "";
	local t2 = "";
	local t1 = "";
	
	local CanBuyTexts = {0, 0, 0, 0}
	local StoreToTexts = {0, 0, 0, 0}
	local NoMoneyTexts = {0, 0, 0, 0}
		
	local x = 2;
	for j = 1, 4 do
		if (v[j] == 1 and money >= GetPrice(i[j]) and (money - LevelMoney) < GetPrice(i[j])) then CanBuyTexts[j] = 1 else CanBuyTexts[j] = 0 end;
		if  (v[j] == 1 and money >= GetPrice(i[j]) and (money - x*LevelMoney) > GetPrice(i[j])) then StoreToTexts[j] = 1 else StoreToTexts[j] = 0 end;
		if  (v[j] == 1 and money < GetPrice(i[j]) and (money + 0.5*x*LevelMoney) > GetPrice(i[j])) then NoMoneyTexts[j] = 1 else NoMoneyTexts[j] = 0 end;
	end;
	-- для тех, кто плохо играет 
	local r = Random("NoMoneyItem", 1,TotalIterCount);	-- который по счету из тех что можно текстов взять 
	local k = 0;
	local j = 1;
	while (k < r and j < 5) do
		if NoMoneyTexts[j] == 1 then k = k+1; end;
		j = j+1;
	end;
	if (k == r) then t3 = "NoMoney"..i[j - 1]..Random("NoMoney", 1, 2); else t3 = "" end;
				
	--специально для тех, кто копит деньги
	r = Random("StoreToItem", 1,TotalIterCount);	-- который по счету из тех что можно текстов взять 
	k = 0;
	j = 1;
	while (k < r and j < 5) do
		if StoreToTexts[j] == 1 then k = k+1; end;
		j = j+1;
	end;
	if (k == r) then t2 = "StoreTo"..i[j - 1]..Random("StoreTo", 1, 3); else t2 = "" end;
	
	--------------------------------------------------------
	k = 0;
	j = 1;
	while (k == 0 and j < 5) do
		if CanBuyTexts[j] == 1 then k = 1 else k = 0 end;
		j = j+1;
	end;
	if (k == 1) then t1 = "CanBuy"..i[j - 1]; else t1 = "" end;
	
	local CanShowComment = true;	
	local AboutSellText = "";
	-- Денег стало хватать на новую покупку? Радуемся. Нет? Ворчим про то, что деньги копит
	local CanShowComment = true;
	if (TotalIterCount == 0) then 
		HistoryToNewIter();
		CanShowComment = false;
--[[	elseif (TotalIterCount == 0) and (math.random(1, 5) > 1) then 
		txt = "ToNewIter"..Random("ToNewIter", 1, 7)
		AboutSellText = "ToNewIter"..Random("ToNewIter", 1, 7)
]]	elseif (t1 > "" and (AfterLevel or (not AfterLevel and math.random(1, 3) == 2))) then txt = t1; 
	elseif t3 > "" then 
		AboutSellText = "AboutSell"..t3; 
		txt = t3; 
	elseif t2 > "" then 
		txt = t2;
		 AboutSellText = "AboutSell"..t2;
	end;
	
	if CanShowComment then 
		if not AfterTalkAboutSell then
			if (LevelMoney == 0 and AfterLevel) then 
				if ClearTalkWindow then
					LP_ClearTalkAction(0.5);
					LP_FastFinishCurrentBehav();
				end;
				LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
				AddTalkWindowToLastAction(0, "PlayerNoMoney", 6);				
		
			elseif (PlayerAwayFromLeave and AfterLevel) then 
				if ClearTalkWindow then
					LP_ClearTalkAction(0.5);
					LP_FastFinishCurrentBehav();
				end;
				LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
				AddTalkWindowToLastAction(0, "PlayerAwayFromLeave"..math.random(1,10), 6);				
			elseif (not PlayerAwayFromLeave and remainingTime == 0 and AfterLevel and not RelaxMode) then 
				if ClearTalkWindow then
					LP_ClearTalkAction(0.5);
					LP_FastFinishCurrentBehav();
				end;
				LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
				TalkPhrase("NoTimePhrases"); 
			elseif (LevelMoney < 200 and AfterLevel) then 
				if ClearTalkWindow then
					LP_ClearTalkAction(0.5);
					LP_FastFinishCurrentBehav();
				end;
				LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
				AddTalkWindowToLastAction(0, "LittleLevelMoney"..math.random(1,5), 5);	
			elseif math.random(1, 3) == 2 and (GardenProgress ~= "00000000000000000000") then 
				if isStop then 
					if ClearTalkWindow then
						LP_ClearTalkAction(0.5);
						LP_FastFinishCurrentBehav();
					end;
					LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
					AddTalkWindowToLastAction(0, "AfterISpy"..Random("AfterISpyTexts", 1, 10), 6);				
				else
					if math.random(1, 2) == 1 then 
						LP_AddTalkAction(0, "AfterISpy"..Random("AfterISpyTexts", 1, 10), 6, false);
					end;
				end
			elseif (txt > "") then --есть что сказать
				if isStop then 
					if ClearTalkWindow then
						LP_ClearTalkAction(0.5);
						LP_FastFinishCurrentBehav();
					end;
					LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
					AddTalkWindowToLastAction(0, txt, 6);				
				else
					if math.random(1, 3) > 1 then 
						LP_AddTalkAction(0, txt, 6, false);
					end;
				end;
			end;
		else
			if AboutSellText > "" then 
				if isStop then 
					LP_PlayAnim("HandUp1", 0.7, 1, true, true);
					AddTalkWindowToLastAction(0, AboutSellText, 6);		
				else
					if math.random(1, 3) > 1 then 
						LP_AddTalkAction(0, AboutSellText, 6, false);
					end;
				end;
			end;
		end;
	end;
end
function CanShowHelpLetter()
	return false;
end;
function CanShowCollector()
	local CountAfter = gameInfo:getLocalIntOrDef("CountAfter", 1)	
--	return true;

	if CountAfter > 4 then --еще надо проверять есть ли вообще непройденные коллекционеры.
		return true
	else
		return false;
	end;

end;

function ItWasCollector(LevelName)
	return
		((LevelName == "Bar20") or
		(LevelName == "Blue_hall20") or 
		(LevelName == "Bathroom20") or
		(LevelName == "Garage20") or
		(LevelName == "Hall20") or 
		(LevelName == "Bedroom20") or
		(LevelName == "Childroom20") or
		(LevelName == "China20") or
		(LevelName == "Drawingroom20") or
		(LevelName == "Garret20") or
		(LevelName == "Kitchen20") or
		(LevelName == "Kladovaya20") or
		(LevelName == "Office20") or
		(LevelName == "Veranda20") or
		(LevelName == "Veranda2_20"))
end;

function GetCollectorNameLevel(numLevel)
	return GetFileLevel(numLevel, false)
end;

function SetGoodPos()
	local GoodPosition = Random("RandomPosition", 1, 5);
	local EnableRain = gameInfo:getLocalBoolOrDef("EnableRain", false);
	if not EnableRain then 
		if GoodPosition == 1 then 
			LP_SetPosition(Point(561, 202))
			RunIdle(3, -1, false);
		elseif GoodPosition == 2 then 
			LP_SetPosition(Point(704, 229))
			RunIdle(3, -1, false);
		elseif GoodPosition == 3 then 
			LP_SetPosition(Point(408, 118))
			RunIdle(3, -1, false);
		elseif GoodPosition == 4 then 
			LP_SetPosition(Point(311, 247))
			RunIdle(3, -1, false);
		elseif GoodPosition == 5 then 
			LP_SetPosition(Point(525, 265))
			RunIdle(3, -1, false);
		elseif GoodPosition == 6 then 
			LP_SetPosition(Point(150, 295))
			RunIdle(3, -1, false);
		elseif GoodPosition == 7 then 
			LP_SetPosition(Point(587, 384))
			RunIdle(3, -1, false);
		elseif GoodPosition == 8 then 
			LP_SetPosition(Point(713, 225))
			RunIdle(3, -1, false);
		else
			LP_SetPosition(Point(435, 104))
			RunIdle(3, -1, false);
		end;
	else
		LP_SetPosition(Point(257, 483))
		RunIdle(3, -1, false);
	end;
end;

function SetCollGoodPos(LevelName)
	local LevelTime = gameInfo:getLocalIntOrDef("OldLevelTime", 500) -- время установленное на уровень 
	local passTime = gameInfo:getLocalIntOrDef("passTime", 100) -- сколько потратили на уровень
	local remainingTime = LevelTime - passTime;
	local PlayerAwayFromLeave = gameInfo:getLocalBoolOrDef("PlayerAwayFromLeave", false) -- игрок вышел через меню, не закончил уровень
	if (LevelName == "Bar20") then 
		LP_SetPosition(GetColActivePos());
	elseif (LevelName == "Blue_hall20") then 
		LP_SetPosition(Point(740, 353));
	elseif (LevelName == "Bathroom20") then
		LP_SetPosition(Point(534, 296));
	elseif (LevelName == "Garage20") then
		LP_SetPosition(Point(632, 158));
	elseif (LevelName == "Hall20") then
		LP_SetPosition(GetColActivePos());
	elseif (LevelName == "Bedroom20") then
		if (LP_GetPurchaseProgress("Golf") == 0) then 
			LP_SetPosition(Point(731, 358));
		elseif (LP_GetPurchaseProgress("Bench") > 0) then
			LP_SetPosition(Point(668, 292));
		end;
	elseif (LevelName == "Childroom20") then
		LP_SetPosition(GetColActivePos());
	elseif (LevelName == "China20") then
		LP_SetPosition(GetColActivePos());
	elseif (LevelName == "Drawingroom20") then
		LP_SetPosition(Point(534, 296));
	elseif (LevelName == "Garret20") then
		LP_SetPosition(Point(408, 384));
	elseif (LevelName == "Kitchen20") then
		LP_SetPosition(Point(408, 384));
	elseif (LevelName == "Kladovaya20") then
		LP_SetPosition(Point(408, 384));
	elseif (LevelName == "Office20") then
		LP_SetPosition(Point(740, 353));
	elseif (LevelName == "Veranda20") then
		LP_SetPosition(Point(408, 384));
	elseif(LevelName == "Veranda2_20") then 
		LP_WalkTo(Point(740, 353), 5, 3.5);
	end;
	if (PlayerAwayFromLeave or remainingTime == 0) then 
		LP_PlayAnim("Tutorial3", 0.7, 1, true, false);
		AddTalkWindowToLastAction(0.0, "SkipCollector", 4.0); 
	end;
end;

function ActionAfterCollector(LevelName)
	SetCollGoodPos(LevelName);	
	if (gameInfo:LetterWasRead("Collector"..LevelName) ~= false) then
		if (LevelName == "Bar20") then 
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorBar20_1", 5.0); 
			LP_PlayAnim("Tutorial1", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorBar20_2", 5.0); 
		elseif (LevelName == "Blue_hall20") then 
			LP_PlayAnim("Sit1", 1.5, 1, true, false);
			LP_PlayAnim("SatToLetter", 1.5, 1, true, false);	
			LP_PlayAnim("Letter", 0.7, 1, true, false);	
			AddTalkWindowToLastAction(0.0, "AfterCollectorBlue_hall20_1", 4.0); 
			LP_PlayAnim("Letter", 0.7, 3, true, false);	
			LP_PlayReversedAnim("SatToLetter", 1.5, 1, true, false);
			LP_PlayReversedAnim("Sit1", 1.5, 1, true, false);
			LP_WalkTo(Point(686, 362), 5, 3.5);
			LP_PlayAnim("Tutorial1", 1.0, 1, true, false);	
			AddTalkWindowToLastAction(0.0, "AfterCollectorBlue_hall20_2", 4.0); 
		elseif (LevelName == "Bathroom20") then
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorBathroom20_1", 5.0); 
			LP_WalkTo(Point(392, 278), 5, 3.5);
			LP_PlayAnim("Tutorial2", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorBathroom20_2", 5.0); 
		elseif (LevelName == "Garage20") then
			LP_PlayAnim("Tutorial3", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorGarage20_1", 5.0); 
			LP_WalkTo(Point(498, 162), 5, 3.5);
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorGarage20_2", 5.0); 
		elseif (LevelName == "Hall20") then
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorHall20", 5.0); 
		elseif (LevelName == "Bedroom20") then
			LP_PlayAnim("Sit1", 1.5, 1, true, false);
			LP_PlayAnim("SatToLetter", 1.5, 1, true, false);	
			LP_PlayAnim("Letter", 0.7, 1, true, false);	
			AddTalkWindowToLastAction(0.0, "AfterCollectorBedroom20_1", 4.0); 
			LP_PlayAnim("Letter", 0.7, 3, true, false);	
			LP_PlayReversedAnim("SatToLetter", 1.5, 1, true, false);
			LP_PlayReversedAnim("Sit1", 1.5, 1, true, false);
			LP_WalkTo(Point(686, 362), 5, 3.5);
			LP_PlayAnim("Tutorial1", 0.7, 1, true, false);	
			AddTalkWindowToLastAction(0.0, "AfterCollectorBedroom20_2", 4.0); 
		elseif (LevelName == "Childroom20") then
			LP_PlayAnim("Tutorial3", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorChildroom20_1", 5.0); 
			LP_PlayAnim("Tutorial1", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorChildroom20_2", 5.0); 
		elseif (LevelName == "China20") then
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorChina20_1", 5.0); 
			LP_PlayAnim("Tutorial1", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorChina20_2", 5.0); 
		elseif (LevelName == "Drawingroom20") then
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorDrawingroom20_1", 5.0); 
			LP_WalkTo(Point(392, 278), 5, 3.5);
			LP_PlayAnim("Tutorial2", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorDrawingroom20_2", 5.0); 
		elseif (LevelName == "Garret20") then
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorGarret20_1", 5.0); 
			LP_WalkTo(Point(275, 519), 5, 3.5);
			LP_PlayAnim("Joy2", 0.7, 1, true, false);
			LP_WalkTo(Point(392, 278), 5, 3.5);
			LP_PlayAnim("Tutorial3", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorGarret20_2", 5.0); 
		elseif (LevelName == "Kitchen20") then
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorKitchen20_1", 5.0); 
			LP_WalkTo(Point(392, 278), 5, 3.5);
			LP_PlayAnim("Tutorial1", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorKitchen20_2", 5.0); 
		elseif (LevelName == "Kladovaya20") then
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorKladovaya20_1", 5.0); 
			LP_WalkTo(Point(392, 278), 5, 3.5);
			LP_PlayAnim("Tutorial1", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorKladovaya20_2", 5.0); 
		elseif (LevelName == "Office20") then
			LP_PlayAnim("Sit1", 1.5, 1, true, false);
			LP_PlayAnim("SatToLetter", 1.5, 1, true, false);	
			LP_PlayAnim("Letter", 0.7, 1, true, false);	
			AddTalkWindowToLastAction(0.0, "AfterCollectorOffice20_1", 4.0); 
			LP_PlayAnim("Letter", 0.7, 3, true, false);	
			LP_PlayReversedAnim("SatToLetter", 1.5, 1, true, false);
			LP_PlayReversedAnim("Sit1", 1.5, 1, true, false);
			LP_WalkTo(Point(686, 362), 5, 3.5);
			LP_PlayAnim("Tutorial1", 0.7, 1, true, false);	
			AddTalkWindowToLastAction(0.0, "AfterCollectorOffice20_2", 4.0); 
		elseif (LevelName == "Veranda20") then
			LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorVeranda20_1", 5.0); 
			LP_WalkTo(Point(392, 278), 5, 3.5);
			LP_PlayAnim("Tutorial2", 0.7, 1, true, false);
			AddTalkWindowToLastAction(0.0, "AfterCollectorVeranda20_2", 5.0); 
		elseif(LevelName == "Veranda2_20") then 
			LP_PlayAnim("Tutorial1", 0.7, 1, true, false);	
			AddTalkWindowToLastAction(0.0, "AfterCollectorVeranda2_20", 4.0); 
		end;
	end;
end;


function Diff(Iter, TotalMoney, TotalTime)
	local a = 0.000208
	if 		Iter == 1 then a = a/1
	elseif	Iter == 2 then a = a/3.8
	elseif 	Iter == 3 then a = a/7.9
	elseif 	Iter == 4 then a = a/13.6
	elseif 	Iter == 5 then a = a/25.8
	end;
	return Div(math.sqrt(TotalTime/a) - TotalMoney, 10) * 10 	
end;

function ActionAfterPearls(WhatFound)
	if WhatFound == "Pearls" and (gameInfo:LetterWasRead("PearlsLetter") ~= false) then
		LP_SetPosition(Point(408, 384));
		LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
		AddTalkWindowToLastAction(0.0, "AfterFoundAllPearls", 5.0); 
	elseif WhatFound == "Candy" and (gameInfo:LetterWasRead("CandyLetter") ~= false) then
		LP_SetPosition(Point(408, 384));
		LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
		AddTalkWindowToLastAction(0.0, "AfterFoundAllCandy", 5.0); 
	elseif WhatFound == "Buttons" and (gameInfo:LetterWasRead("ButtonsLetter") ~= false) then
		LP_SetPosition(Point(408, 384));
		LP_PlayAnim("Tutorial4", 0.7, 1, true, false);
		AddTalkWindowToLastAction(0.0, "AfterFoundAllButtons", 5.0); 
	end;
end;

function CanShowPearls()
	local CountAfter = gameInfo:getLocalIntOrDef("CountAfterLastBeads", 0)	
	local TypeCount = gameInfo:getLocalIntOrDef("PearlsTypeCount", 0)
	if (CountAfter > 15 and (gameInfo:getLocalIntOrDef("GardenLevelNumber",0) > 15) and TypeCount < 3) then 
		gameInfo:setLocalInt("CountAfterLastBeads", 0)
		gameInfo:setLocalInt("PearlsTypeCount", TypeCount + 1);
		return true
	else
		gameInfo:setLocalInt("CountAfterLastBeads", CountAfter+1)
		return false;
	end;

end;

function StartFindingPearls()
		local TypeCount = gameInfo:getLocalIntOrDef("PearlsTypeCount", 1)
		LP_FastFinishCurrentBehav();
		if TypeCount == 1 then  
			gameInfo:setLocalString("NameLetter", "PearlsLetter")
			gameInfo:setLocalString("namePearls", "Pearls");			-- имя предмета которое ищем (пока только бусинки)	
			gameInfo:setLocalString("TalkHistoryISpyText", "IspyStartFindingPearls");
		elseif TypeCount == 2 then 
			gameInfo:setLocalString("NameLetter", "CandyLetter")
			gameInfo:setLocalString("namePearls", "Candy");			-- имя предмета которое ищем (пока только бусинки)	
			gameInfo:setLocalString("TalkHistoryISpyText", "IspyStartFindingCandy");
		elseif TypeCount == 3 then
			gameInfo:setLocalString("NameLetter", "ButtonsLetter")
			gameInfo:setLocalString("namePearls", "Buttons");			-- имя предмета которое ищем (пока только бусинки)	
			gameInfo:setLocalString("TalkHistoryISpyText", "IspyStartFindingButtons");
		end;	
		gameInfo:setLocalInt("NeedPearls", 20);						-- количество бусинок которое нужно найти
		gameInfo:setLocalInt("ColPearls", 0);						-- количество бусинок которое уже нашли
		gameInfo:setLocalInt("levelPearls", 7);						-- количество уровней за которое надо найти бусинки

end;

function GetMaxS(i, v, n)
	local S = 0;
	if n == 4 then S = GetPrice(i[1]) + GetPrice(i[2]) + 0.25*GetPrice(i[3]);
	elseif n == 3 then
		if 		(v[1] == 0) then S = GetPrice(i[2]) + 0.25*GetPrice(i[3])
		elseif 	(v[2] == 0) then S = GetPrice(i[1]) + 0.25*GetPrice(i[3])
		elseif 	(v[3] == 0) then S = GetPrice(i[1]) + 0.25*GetPrice(i[2])
		else	S = GetPrice(i[1]) + 0.25*GetPrice(i[2])
		end;
	end;
	return S;
end;

function ClearIterParam()
	gameInfo:setLocalInt("AddHistCount", 0)	
	FirstTimeNoItems = true;
	gameInfo:setLocalInt("DoneMiddleHist", 0)
	Done = 0;
	ShowMiddleHist = false;
end;
function ppp()

end;

function AdditionalHistory(HalfIterMoney, TotalIterMoney, v, money)
	local Iter = gameInfo:getGardenIter()									-- номер итерации в саду (1 - 5)
	local AddHistCount = gameInfo:getLocalIntOrDef("AddHistCount", 0)
	local LastHistory = gameInfo:getLocalStringOrDef("LastHistory", "StartIter1");
	local Level = gameInfo:getLocalIntOrDef("GardenLevelNumber",0)		-- порядковый номер следующего ISpy
	local prevStrenght = gameInfo:getLocalFloatOrDef("GardenRain", 0);		

	if (Iter == 2 and AddHistCount == 0 and LastHistory == "StartIter2" and money > 0.40*HalfIterMoney) then 
	-- садовница о том, что было бы не плохо в клуб садоводов вступить
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("StrangePhoneWomen", 1)	
		gameInfo:setLocalString("LastPhoneDialog", "StrangePhoneWomen");
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 2 and AddHistCount == 1 and LastHistory == "StartIter2" and money >= 0.65*HalfIterMoney) then 
		--значит она уже звонила. Остин собирается сходить в клуб садоводов, рассказать о саде
		gameInfo:setLocalString("NameMult", "StartIter2Mult2")
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 2 and AddHistCount == 0 and LastHistory == "MiddleIter2" and money > 0.70*TotalIterMoney) then 
		-- звонит садовница уточнить, как у нас дела
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("StrangePhoneWomenMiddleIter2", 1)	
		gameInfo:setLocalString("LastPhoneDialog", "StrangePhoneWomenMiddleIter2");
		--после звонка Остин комментирует ситуацию с садом
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 3 and AddHistCount == 0 and LastHistory == "StartIter3" and money > 0.40*HalfIterMoney) then 
		--звонит садовница, говорит про конкурс
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("StartIter3PhoneWomen", 1)	
		gameInfo:setLocalString("LastPhoneDialog", "StartIter3PhoneWomen");
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 3 and AddHistCount == 1 and LastHistory == "StartIter3" and money >= 0.7*HalfIterMoney) then 
		--приходит письмо с правилами конкурса
		gameInfo:setLocalString("NameLetter", "StartIter3Rules")
		gameInfo:setLocalInt("MoneyLetter", 0)
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 3 and AddHistCount == 0 and LastHistory == "MiddleIter3" and money >= 0.25*TotalIterMoney) then 
		--Остин заполняет заявку участника
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
		gameInfo:setLocalString("NameMult", "MiddleIter3Mult1")
	elseif (Iter == 3 and AddHistCount == 1 and LastHistory == "MiddleIter3" and money >= 0.40*TotalIterMoney) then 
		--один раз пропустим
		startRain = true;
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 3 and AddHistCount == 2 and LastHistory == "MiddleIter3" and money >= 0.65*TotalIterMoney) then 
		--звонит садовница, говорит что приняли нашу заявку
		if v[1] == 1 then N = 1 
		elseif v[2] == 1 then N = 2
		elseif v[3] == 1 then N = 3
		elseif v[4] == 1 then N = 4
		else N = 0;
		end;
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("MiddleIter3PhoneWomen"..N, 1)	
		gameInfo:setLocalString("LastPhoneDialog", "MiddleIter3PhoneWomen"..N);
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 4 and AddHistCount == 0 and LastHistory == "StartIter4" and money > 0.25*HalfIterMoney) then 
		-- звонит редактор газеты и рассказывает, что необходимо сделать прежде всего
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("AdditionalPhoneMenStartIter4", 1)	
		gameInfo:setLocalString("LastPhoneDialog", "AdditionalPhoneMenStartIter4");
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 4 and AddHistCount == 1 and LastHistory == "StartIter4" and money > 0.45*HalfIterMoney) then 
		--Остин рассказывает о победителе прошлого года
		gameInfo:setLocalString("NameMult", "StartIter4Mult1")
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 4 and AddHistCount == 2 and LastHistory == "StartIter4" and money > 0.65*HalfIterMoney) then 
		--один раз пропустим
		startRain = true;
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 4 and AddHistCount == 3 and LastHistory == "StartIter4" and money > 0.8*HalfIterMoney) then 
		--Остину друг звонил
		gameInfo:setLocalString("NameMult", "StartIter4Mult2")
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 4 and AddHistCount == 0 and LastHistory == "MiddleIter4" and money >= 0.20*TotalIterMoney) then 
		--Остину звонит редактор с промежуточными итогами
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("AdditionalPhoneMiddleIter4", 1)	
		gameInfo:setLocalString("LastPhoneDialog", "AdditionalPhoneMiddleIter4");
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 4 and AddHistCount == 1 and LastHistory == "MiddleIter4" and money >= 0.40*TotalIterMoney) then 
		-- звонит садовница, хвалит последнюю покупку.
		local LastItem = gameInfo:getLocalStringOrDef("LastBuying", "");
		if v[1]+v[2]+v[3]+v[4] == 4 then s = "Empty"
		else s = LastItem
		end;
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("AddPhoneMiddleIter4Women"..s, 1)	
		gameInfo:setLocalString("LastPhoneDialog", "AddPhoneMiddleIter4Women"..s);
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 4 and AddHistCount == 2 and LastHistory == "MiddleIter4" and money >= 0.70*TotalIterMoney) then 
		-- маленький мальчик присылает немного денег, говорит, что болеет за нас.
		if v[1] == 1 then N = 1 
		elseif v[2] == 1 then N = 2
		elseif v[3] == 1 then N = 3
		elseif v[4] == 1 then N = 4
		else N = 0;
		end;
		gameInfo:setLocalString("NameLetter", "Iter4ChildLetter"..N)
		gameInfo:setLocalInt("MoneyLetter", 50)
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 5 and AddHistCount == 0 and LastHistory == "StartIter5" and money > 0.20*HalfIterMoney) then 
		-- звонит редактор, успокаивает. говорит, что постарается все уладить
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("AddPhoneStartIter5Men", 1)	
		gameInfo:setLocalString("LastPhoneDialog", "AddPhoneStartIter5Men");
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 5 and AddHistCount == 1 and LastHistory == "StartIter5") then 
		-- один раз пропускаем
		startRain = true;
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 5 and AddHistCount == 2 and LastHistory == "StartIter5" and money > 0.55*HalfIterMoney) then 
		-- приходит письмо от садовницы, что ок, пока выгонять не будут
		gameInfo:setLocalString("NameLetter", "StartIter5AdditionalLetter1")
		gameInfo:setLocalInt("MoneyLetter", 0)
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 5 and AddHistCount == 3 and LastHistory == "StartIter5" and money > 0.70*HalfIterMoney) then 
		-- дворецкий приходит из города и рассказывает, что там говорят
		gameInfo:setLocalString("NameMult", "StartIter5Mult1")
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 5 and AddHistCount == 0 and LastHistory == "MiddleIter5" and money >= 0.20*TotalIterMoney) then 
		-- звонит редактор, сообщает что конкурс вот-вот состоится, спрашивает можно ли пофоткать
		LP_FastFinishCurrentBehav();
		LP_ClearTalkAction(0.0);
		LP_SetPosition(Point(435, 389))
		RunIdle(3, -1, false);
		LP_SetDialog("MiddleIter5MenPhone", 1)	
		gameInfo:setLocalString("LastPhoneDialog", "MiddleIter5MenPhone");
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 5 and AddHistCount == 1 and LastHistory == "MiddleIter5" and money >= 0.40*TotalIterMoney) then 
		--один раз пропускаем
		startRain = true;
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 5 and AddHistCount == 2 and LastHistory == "MiddleIter5" and money >= 0.60*TotalIterMoney) then 
		-- приходит газета с обзором последних покупок в саду
		if v[3] == 1 then N = 3 
		elseif v[2] == 1 then N = 2
		elseif v[4] == 1 then N = 4
		elseif v[1] == 1 then N = 1
		end;
		gameInfo:setLocalString("NameNewspaper", "MiddleIter5Newspaper"..N);
		gameInfo:setLocalString("NameLastNewspaper", "MiddleIter5Newspaper"..N);
		gameInfo:setLocalInt("AddHistCount", AddHistCount+1);
	elseif (Iter == 5 and AddHistCount == 3 and LastHistory == "MiddleIter5" and money >= 0.80*TotalIterMoney) then 
		-- дворецкий подписывает открытки друзьям. мол уже выиграли
		gameInfo:setLocalString("NameMult", "MiddleIter5Mult1")
		gameInfo:setLocalInt("AddHistCount", AddHistCount + 1);
	elseif (Random("RandomHist", 1, 10) == 1 and Iter > 3) then 
		RandomHistory();
	elseif (Level > 3) then 
		startRain = true;
	--	SetRainInGarden()
	end;
end;

function SolveFinancialProblem(Done, Iter, i, v, money, newIter, TotalIterMoney, TotalIterCount, numLevel)
	local TotalMoney = gameInfo:getLocalIntOrDef("TotalMoney", money)		-- количество денег за всю игру
	local TotalISpyTime = gameInfo:getLocalIntOrDef("TotalISpyTime", 0)		
	local DiffMoney = Diff(Iter, TotalMoney, TotalISpyTime)					--столько  игроку необходимо денег, чтоб вернуться к графику			
	local numLevel = gameInfo:getLocalIntOrDef("GardenLevelNumber",0)		-- порядковый номер следующего ISpy
	local LetterMoney = 0;
	local MaxDiff = 200; 	--максимальная разница в том сколько денег есть с тем, сколько должно быть, которую еще согласны терпеть
	local S = GetMaxS(i, v, TotalIterCount);
	local CountAfter = gameInfo:getLocalIntOrDef("CountAfter", 0)	
	local LevelMoney = gameInfo:getLocalIntOrDef("MoneyInLevel", 0)
	
	if (CanShowCollector()) then 
		gameInfo:setLocalInt("ISpyMode", 2);
		gameInfo:setLocalInt("CountAfter", 0)
		nameLevel = GetCollectorNameLevel(numLevel)
		DoneCollectorResponse = false;
		gameInfo:setLocalInt("CollectorResponse", 0) -- надо будет ответить на письмо коллекционера. 
		gameInfo:setLocalString("NameLetter", "Collector"..nameLevel)
		gameInfo:setLocalString("TalkHistoryISpyText", "IspyCollector"..nameLevel);

		if DiffMoney > MaxDiff then 		
			if Done == 1 or money+DiffMoney < 0.75*S then
				LetterMoney = 0.75*DiffMoney;
			elseif money+DiffMoney >= 0.75*S then 
				LetterMoney = DiffMoney - (money+DiffMoney - 0.8*S);
			end;
			if LetterMoney < 0 then LetterMoney = 0; end;
		else
			LetterMoney = 0;
		end;
		if LetterMoney > 0 then 
			gameInfo:setLocalInt("MoneyLetter", LetterMoney)
		end;
	elseif CanShowHelpLetter() then
		--здесь написать, что делать, если все коллекционеры уже закончились
		gameInfo:setLocalInt("CountAfter", 0)
	else
--		if LevelMoney > 0 then 
			gameInfo:setLocalInt("CountAfter", CountAfter+1)
--		end;
		if CanShowPearls() then 
			StartFindingPearls();		
		else AdditionalHistory(S, TotalIterMoney, v, money)
		end;
	end;
end;	

function GetLevelTime(level)
	return gameInfo:getLocalIntOrDef("OldLevelTime", 250)
end;

function StartMainMenu()
	local LastHistory = gameInfo:getLocalStringOrDef("LastHistory", "StartIter1");
	SetEnableRain(false);
	LP_SetPosition(Point(565, 198));
	LP_WalkTo(Point(561, 193), 7, 1.0);	
	AddTalkWindowToLastAction(0.5, "GreetingAfter"..LastHistory, 8.0);
	LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true); 
	LP_PlayAnim("TutorialHandUp", 1.3, 1, true, true);
	LP_PlayAnim("TutorialStand", 0.4, 1, true, true);
	LP_PlayReversedAnim("TutorialHandUp", 1.3, 1, true, true); 
	LP_PlayAnim("Tutorial3", 1.0, 1, true, true);
	LP_PlayAnim("TutorialHandUp", 1.3, 1, true, true);
	LP_PlayAnim("TutorialStand", 0.4, 1, true, true);
	LP_PlayReversedAnim("TutorialHandUp", 1.3, 1, true, true);
end


function AfterFirstLevelNoTutorial()
	LP_SetPosition(Point(132, 277));
	LP_WalkTo(Point(132, 277), 7, 1.0);	
	AddTalkWindowToLastAction(0.0, "OstinTextAfterISpy1", 7.0); 
	LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
	LP_PlayAnim("Tutorial4", 0.7, 1, true, true);
	RunIdle(3, -1, false);
end

function AfterFirstLevel(money)
	--LP_SetPosition(Point(565, 198));
	--[[
	LP_SetPosition(Point(132, 277));
	LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
	AddTalkWindowToLastAction(0.0, "OstinTextAfterISpy1", 7.0); 
	LP_PlayAnim("Tutorial4", 1, 1, true, true);
	RunIdle(3, -1, false);
	]]--
	LP_WalkTo(Point(471, 317), 5, 1.0);
	LP_PlayAnim("Tutorial1", 0.7, 1, true, true);
	AddTalkWindowToLastAction(0.0, "OstinAfterFirstISpy1", 7.0); 
	LP_WalkTo(Point(311, 247), 5, 1.0);
	LP_PlayAnim("Tutorial2", 0.7, 1, true, true);
	if (LP_GetPurchaseProgress("Bench") == 0) then 
		AddTalkWindowToLastAction(0.0, "OstinAfterFirstISpy2Bench", 7.0); 
	elseif (LP_GetPurchaseProgress("Wall") == 0 and money > GetPrice("Wall")) then 
		AddTalkWindowToLastAction(0.0, "OstinAfterFirstISpy2Wall", 7.0); 
	else
		AddTalkWindowToLastAction(0.0, "OstinAfterFirstISpy2", 7.0); 
	end;
	LP_WalkTo(Point(311, 247), 5, 1.0);
	LP_PlayAnim("Tutorial4", 0.7, 1, true, true);
	AddTalkWindowToLastAction(0.0, "OstinAfterFirstISpy3", 7.0); 
end;

function AboutCurrentHistory()
	local LastHistory = gameInfo:getLocalStringOrDef("LastHistory", "StartIter1");
	LP_PlayAnim("Tutorial4", 0.7, 1, true, true);
	if (not CurHistTextWasShown or math.random(1, 7) == 1) then 
		AddTalkWindowToLastAction(0.0, "AboutCurrentHistory"..LastHistory, 7.0); 
		CurHistTextWasShown = true;
	end;
end;
function LP_SetLastHistory(justShowHistory)
	local LastLetterName = gameInfo:getLocalStringOrDef("LastLetter", "")
	local LastNewspaperName = gameInfo:getLocalStringOrDef("NameLastNewspaper", "")
	local Iter = gameInfo:getGardenIter();
	local money = gameInfo:getLocalIntOrDef("Cash", 0)						-- количество денег у игрока
	local i = GetI(Iter);
	
	local p = {0, 0, 0, 0};
	
	for j = 1, 4 do 
		if (LP_GetPurchaseProgress(i[j]) > 0) then p[j] = 1 else p[j] = 0; end;
	end; 
	local RandomPhone = gameInfo:getLocalIntOrDef("RandomPhone", 0)
	local LastPhone = gameInfo:getLocalStringOrDef("LastPhoneDialog", "");
	if (justShowHistory == "Phone") then
		if (RandomPhone > 0) then
		elseif LastPhone == "StrangePhoneWomen" then 
		elseif LastPhone == "StrangePhoneWomenMiddleIter2" then
		elseif LastPhone == "AdditionalPhoneMiddleIter4" then
		elseif LastPhone == "StartIter3PhoneWomen" then 
		elseif  (LastPhone == "MiddleIter3PhoneWomen0") or
				(LastPhone == "MiddleIter3PhoneWomen1") or
				(LastPhone == "MiddleIter3PhoneWomen2") or
				(LastPhone == "MiddleIter3PhoneWomen3") or
				(LastPhone == "MiddleIter3PhoneWomen4") 
		then 
		elseif (LastPhone == "AdditionalPhoneMenStartIter4") then 
		elseif (LastPhone == "MiddleIter5MenPhone") then 
		elseif (LastPhone == "AddPhoneStartIter5Men") then 
		else
			if (Iter == 1) then 
				gameInfo:setLocalString("LastHistory", "MiddleIter1");
			else
			end;
		end;
	elseif (justShowHistory == "Letter") then
		if (LastLetterName == "NewIterLetter3") then 
			gameInfo:setLocalString("LastHistory", "StartIter3");			
		elseif 	(LastLetterName == "NewIterLetter5") then
			gameInfo:setLocalString("LastHistory", "StartIter5");						
		elseif (LastLetterName == "Middle4"..p[1]..p[2]..p[3]..p[4]) then 
			gameInfo:setLocalString("LastHistory", "MiddleIter4");						
		elseif (LastLetterName == "Iter4ChildLetter0" or
				LastLetterName == "Iter4ChildLetter1" or
				LastLetterName == "Iter4ChildLetter2" or
				LastLetterName == "Iter4ChildLetter3" or
				LastLetterName == "Iter4ChildLetter4") 
		then
		else
		end;
	elseif (justShowHistory == "Newspaper") then
		if (LastNewspaperName == "NewIterNewspaper2") then 
				gameInfo:setLocalString("LastHistory", "StartIter2");						
		elseif (LastNewspaperName == "NewIterNewspaper4") then 
				gameInfo:setLocalString("LastHistory", "StartIter4");
		elseif (LastNewspaperName == "MiddleNewspaper3"..p[1]..p[2]..p[3]..p[4]) then 
				gameInfo:setLocalString("LastHistory", "MiddleIter3");			
		elseif (LastNewspaperName == "StrangeNewspaper2") then
		elseif (LastNewspaperName == "StrangeNewspaper3") then
		elseif (LastNewspaperName == "LastNewspaper") then 
				gameInfo:setLocalString("LastHistory", "AfterAllHistory");						
		else
		end;
	elseif (justShowHistory == "PeopleTalk") then
		if (Iter == 2) then gameInfo:setLocalString("LastHistory", "MiddleIter2")
		elseif (Iter == 5) then gameInfo:setLocalString("LastHistory", "MiddleIter5");			
		end;
	end
end

function GetComeLetter()
	local LevelMoney = gameInfo:getLocalIntOrDef("MoneyInLevel", 0)

	local Iter = gameInfo:getGardenIter()											-- номер итерации в саду (1 - 5)
	local money = gameInfo:getLocalIntOrDef("Cash", 0)								-- количество денег у игрока
	local numLevel = gameInfo:getLocalIntOrDef("GardenLevelNumber",0)					-- порядковый номер следующего ISpy
	DoneCollectorResponse = (gameInfo:getLocalIntOrDef("CollectorResponse", 0) == 1) 	-- уже ответили на последнее письмо коллекционера?
	local LevelTime = GetLevelTime(numLevel);
	local TotalISpyTime = gameInfo:getLocalIntOrDef("TotalISpyTime", 0)		
	TotalISpyTime = TotalISpyTime + gameInfo:getLocalIntOrDef("passTime", LevelTime)	-- время, потраченное на ispy за всю игру
	gameInfo:setLocalInt("TotalISpyTime", TotalISpyTime)
	local mode = 1;
			
	startRain = false;
	gameInfo:setLocalString("NameLetter", "")
	gameInfo:setLocalString("TalkHistoryISpyText", "");
	
	if (gameInfo:getBool("OldLevelSystem")) then
		mode = GetISpyMode(numLevel)										-- режим следующего ISpy (возвращает номер)
		nameLevel = GetISpyLevelName(numLevel,mode)							-- имя следующего ISpy(возвращает строку)
	else	
		nameLevel = GetFileLevel(numLevel, false)
		mode = GetISpyMode(numLevel)
	end
	
	
	local letterMoney = 0													-- количество денег, которое должно быть в письме
	local nameLetter = ""													-- имя письма (все письма храняться в Letter_Setting.xml
																			-- в закладке Letter\Letters\)
	local newIter = gameInfo:getLocalBoolOrDef("FirstInNewIter", true)
	Done = gameInfo:getLocalIntOrDef("DoneMiddleHist", 0)				-- уже показывали историю в середине итерации?
	
	local i = GetI(Iter);
	local v = {0, 0, 0, 0};
	local TotalIterMoney = 0; 	--сколько игроку необходимо денег, чтобы завершить итерацию.
	local TotalIterCount = 0 	--сколько еще необходимо купить предметов 
	SetGoodPos();	

	for j = 1, 4 do 
		if (LP_GetPurchaseProgress(i[j]) > 0) then v[j] = 0 else v[j] = 1; end;
		TotalIterCount = TotalIterCount + v[j];
		TotalIterMoney = TotalIterMoney + GetPrice(i[j])*v[j]
	end; 
	local S = GetMaxS(i, v, TotalIterCount);
	if (TotalIterCount<= 2 or money >= S) then 	ShowMiddleHist = true
	else ShowMiddleHist = false; end;
	
	if (LevelMoney > 0) then
		gameInfo:setLocalInt("ISpyMode", 1);				-- назначаем по-умолчанию, что у нас не коллекционер
	end

	local noHistoryNow = not (ShowMiddleHist or newIter) or (ShowMiddleHist and Done == 1)
	local inMainMenu = Ostin_InMainMenu()

	
	-- идентификатор сообщения, которое надо получить в середине итерации.	
	local s = Iter..1-v[1]..1-v[2]..1-v[3]..1-v[4] --потому, что сделала у идентификаторов писем вероятности наоборот и не хочу переписывать, слишком много
	
	--комментарии Остина о деньгах после уровня, реакция на коллекционера
	local ostinExcited = true;
	if (money > TotalIterMoney * 1.5 and (Random("SetStore", 1, 7) == 1)) then 
		ostinExcited = true
		gameInfo:setLocalInt("Store", 1) 
	else
		gameInfo:setLocalInt("Store", 0); 
		ostinExcited = false
	end;
	
	-- если перед этим был уровень коллекционер
	DoneCollectorResponse = (gameInfo:getLocalIntOrDef("CollectorResponse", 0) == 1)
	local WhatFound = gameInfo:getLocalStringOrDef("FindAllPearls", "")
	local OldLevelName = gameInfo:getLocalStringOrDef("PrevLevelName", "")
	if false and numLevel <= 1 then 
		AfterFirstLevel(money);
	elseif	ItWasCollector(OldLevelName) and not DoneCollectorResponse 	then 
		DoneCollectorResponse = true;
		gameInfo:setLocalInt("CollectorResponse", 1)
		ActionAfterCollector(OldLevelName);
	elseif (WhatFound ~= "") then
		gameInfo:setLocalString("FindAllPearls", "");
		local colPearls = gameInfo:getLocalIntOrDef("NeedPearls", 0);
		gameInfo:setLocalInt("NeedPearls", 0);
		gameInfo:setLocalInt("ColPearls", 0);
		ActionAfterPearls(WhatFound)
	elseif noHistoryNow	and not inMainMenu then 
		OstinCommentAfterLevel(v, i, money, TotalIterCount, true, false, false, true);
		SolveFinancialProblem(Done, Iter, i, v, money, newIter, TotalIterMoney, TotalIterCount, numLevel); 
	elseif not inMainMenu then 
		gameInfo:setLocalInt("CountAfter", gameInfo:getLocalIntOrDef("CountAfter", 1) +1)
	elseif ostinExcited then 
		LP_SetPosition(Point(565, 198));
		LP_PlayAnim("HandUp1", math.random(70, 200)/100.0, math.random(1,4), true, true);
		AddTalkWindowToLastAction(0.0, "OstinExcited1", 6.0); 
		LP_PlayAnim("Tutorial4", 0.7, 1, true, true);
		AddTalkWindowToLastAction(0.0, "OstinExcited2", 7.0); 
		RunIdle(3, -1, false);
	else
		OstinCommentAfterLevel(v, i, money, TotalIterCount, true, false, false, true);
		AboutCurrentHistory();
	end;
	---------------------------------------------------------------------------------------
	-- Основная история. 	
	local justShowHistory = "";
	if (gameInfo:GetNumberOfPurchase() < 20) then	
		if newIter then 
			ClearIterParam()
			if (money > 0.75*TotalIterMoney) then 
			-- и еще в этот момент дворецкий должен рассказать суть истории в середине итерации или телефон должен позвонить, 
			-- но что-то должно случится, потому что при таком количестве денег мы можем запросто пролететь мимо истории в середине уровня.
			-- можно вообще сразу получить письмо с суммарной историей за начало и за середину итерации.
			-- или можно просто пропустить историю в середине
				Done = 1
			end;
			if (Iter == 1) then
			-- перед первой итерацией мы должны уже посмотреть мультик
			elseif (Iter == 2) then 
			-- дворецкий говорит что-то о газете
			--газетка приходит (в нашем городе началась распродажа, здорово, прекрасно)
				gameInfo:setLocalString("NameNewspaper", "NewIterNewspaper2");
				gameInfo:setLocalString("NameLastNewspaper", "NewIterNewspaper2");
				justShowHistory = "Newspaper";
			elseif (Iter == 4) then 
				--приходит газета "наш сад участвует в конкурсе"
				gameInfo:setLocalString("NameNewspaper", "NewIterNewspaper4");
				gameInfo:setLocalString("NameLastNewspaper", "NewIterNewspaper4");
				justShowHistory = "Newspaper";
				--[[
				LP_FastFinishCurrentBehav();
				LP_ClearTalkAction(0.0);
				LP_SetPosition(Point(435, 389))
				RunIdle(3, -1, false);
				LP_SetDialog("TalkNewIter"..s, 1)	
				]]
			elseif (Iter == 3) then 

				LP_PlayAnim("Tutorial2", 0.7, 1, true, false);	
				AddTalkWindowToLastAction(0.0, "OstinBeforeNewIter3Hist", 7.0); 
				gameInfo:setLocalString("NameLetter", "NewIterLetter"..Iter)
				gameInfo:setLocalInt("MoneyLetter", 0)
	
				justShowHistory = "Letter";
			else
				gameInfo:setLocalString("NameLetter", "NewIterLetter"..Iter)
				gameInfo:setLocalInt("MoneyLetter", 0)
				justShowHistory = "Letter";
			end;
		elseif (Done == 0 and ShowMiddleHist and TotalIterCount >= 2) then 
			if (Iter == 1) then 
				LP_FastFinishCurrentBehav();
				LP_ClearTalkAction(0.0);
				LP_SetPosition(Point(435, 389))
				RunIdle(3, -1, false);
				LP_SetDialog("TalkMiddle"..s, 1)	
				justShowHistory = "Phone";
			elseif (Iter == 2) then 
				gameInfo:setLocalString("TalkHistoryText", "TalkMiddle"..s);
				justShowHistory = "PeopleTalk";
			elseif (Iter == 3) then 
				--приходит газета 
				gameInfo:setLocalString("NameNewspaper", "MiddleNewspaper"..s);
				gameInfo:setLocalString("NameLastNewspaper", "MiddleNewspaper"..s);
				justShowHistory = "Newspaper";
			elseif (Iter == 5) then 
				gameInfo:setLocalString("TalkHistoryText", "TalkMiddle"..s);
				justShowHistory = "PeopleTalk";
			else			
				gameInfo:setLocalString("NameLetter", "Middle"..s)
				gameInfo:setLocalInt("MoneyLetter", 0)
				justShowHistory = "Letter";
			end;
			Done = 1;
			gameInfo:setLocalInt("AddHistCount", 0)	
			gameInfo:setLocalInt("DoneMiddleHist", 1)
		end;	
	else
		--приходит газета 
		-- поздравляем с победой в конкурсе
		NoCongratulationBefore = gameInfo:getLocalBoolOrDef("NoCongratulationBefore", true)
		if NoCongratulationBefore then 
			gameInfo:setLocalString("NameNewspaper", "LastNewspaper");
			gameInfo:setLocalString("NameLastNewspaper", "LastNewspaper");
			gameInfo:setLocalBool("NoCongratulationBefore", false)
			justShowHistory = "Newspaper";
		end;
	end; -- от (gameInfo:GetNumberOfPurchase() < 20)
	gameInfo:setLocalString("LastLetter", gameInfo:getLocalStringOrDef("NameLetter", ""));
	LP_SetLastHistory(justShowHistory) -- Это для Остина. На случай, если выйдем из игры, не читая историю!!! нельзя удалять! 
end;
