local wtChat = nil
local chatRows = 0

function createMsg(msg, color)
	msgs[msgIndex] = mainForm:CreateWidgetByDesc(wtLogMsg:GetWidgetDesc())
  if color == nil then
    color = "0xffffffff"
  end
  msgs[msgIndex]:GetChildChecked("Message", false):SetFormat(userMods.ToWString(
    "<html color='"..color.."' fontname='AllodsWest' fontsize='8' alignx='left' outline='1'><r name='message'/></html>")) --- edited by icreator
  msgs[msgIndex]:GetChildChecked("Message", false):SetVal("message", msg)
	
	wtMainPanel:AddChild(msgs[msgIndex])
	msgs[msgIndex]:Show(true)
  msgIndex = msgIndex + 1
  local Now = GetCurrentDateTime()
  local timestamp = string.format( "%d-%02d-%02d %02d:%02d:%02d ", Now.y, Now.m, Now.d, Now.h, Now.min, Now.s )
  local msg =  userMods.ToWString(timestamp..userMods.FromWString(msg));
  LogInfo(msg)
  return msg;
end

function LocateChat()
	
	if not wtChat then
		local w = stateMainForm:GetChildUnchecked("ChatLog", false)
		if not w then
			--- главня форма не найдена - найден по ребенку
			w = stateMainForm:GetChildUnchecked("Chat", true)
		else
			w = w:GetChildUnchecked("Container", true) -- w = w:GetChildUnchecked("Chat", true);
		end
		wtChat = w
	end
	return wtChat;
end

function Log(message, color, fontSize)

	wtChat = LocateChat();
	if (not wtChat) then
		LogInfo("No chat");
		return;
	end;

	local valuedText = common.CreateValuedText()
	--- fontname=\"AllodsWest\"
	local format = "<body alignx='left' fontname='AllodsSystem' fontsize='"..(fontSize or GlobalFontSize)
	format = format.."' shadow='1' ><rs class='color'><r name='text'/></rs></body>"
	valuedText:SetFormat(userMods.ToWString(format))
	if color then
		valuedText:SetClassVal( "color", color )
	else
		valuedText:SetClassVal( "color", "LogColorYellow" )
	end
	
	message = TimeToStr(Now()) ..' ' .. ChatPrefix .. ' > '.. message;
	if not common.IsWString( message ) then 
		message = userMods.ToWString(message) 
	end

	valuedText:SetVal( "text", message )
	chatRows =  chatRows + 1
	wtChat:PushFrontValuedText( valuedText )
end
	
--- call by "EVENT_SECOND_TIMER" - for clear messages from chat
function ClearChat( size )
	for i=1, size or math.ceil( chatRows / 30 ) + 1 do
	if chatRows < 1 then break end
		chatRows = chatRows - 1
		wtChat:PopBack()
	end
end
------------------------------------------------------------------------------------