local base = _G

module('browser')

Object = 0
local Path = base.m_simpleTV.MainScriptDir .. 'lib\\Browser'
if base.m_simpleTV.User == nil then base.m_simpleTV.User = {} end
if base.m_simpleTV.User.Browser == nil then base.m_simpleTV.User.Browser = {} end

function RuStr(Str, isFrom)
	if Str == nil then return end
	if isFrom == true then
		return base.m_simpleTV.Common.string_fromUTF8(Str, 1251)
	else
		return base.m_simpleTV.Common.string_toUTF8(Str, 1251)
	end
end

local function trim(s)
	if s == nil then return end
	return (s:gsub("^%s*(.-)%s*$", "%1"))
end

function GetPMState()
	local error_text, pm = base.pcall(base.require, 'pm')
	local PM_detected = false
	if base.package.loaded.pm ~= nil then PM_detected = true end
	return PM_detected
end

function LoadPage(params)
	if (params == nil) then return end
	if params.url == nil then return end
	if (params.size == nil) then params.size = { w = 800, h = 600} end
	base.m_simpleTV.User.Browser.Script = params.script --Скрипт, выполняемый при загрузке страницы
	if params.wait == nil then params.wait = 1000 end
	local scr = 'document.location.href = "' .. params.url .. '";'
	base.debug_in_file(scr, Path .. '\\js\\main.js', true)
	local WindowId = 'Window_Browser'
	Object = base.m_simpleTV.Dialog.FindWindowById(WindowId)
	if Object ~= nil then base.m_simpleTV.Dialog.Close(Object) end
	Object = base.m_simpleTV.Dialog.Show('LoadPage', Path .. '\\Main.html', 'lib\\Browser\\Main.lua', params.size.w, params.size.h, params.flags)
	base.m_simpleTV.Dialog.SetWindowId(Object, WindowId)
	base.m_simpleTV.User.Browser.Url = params.url
	base.m_simpleTV.Common.Wait(params.wait)
	local content = base.m_simpleTV.User.Browser.Content
	if content ~= nil then content = trim(content) end
	return content
end

function ClosePage()
	base.m_simpleTV.Dialog.Close(Object)
end

function Debug(text, file, clear)
	if text == nil then text = '' end
	if file == nil then file = Path .. '\\browser.log' end
	if clear == nil then clear = false end
	base.debug_in_file(text, file, clear)
end