if m_simpleTV.Control.ChangeAdress ~= 'No' then return end
local inAdr = m_simpleTV.Control.CurrentAdress
if inAdr == nil then return end
if not string.match(inAdr, 'kinozal%.tv') then return end

--set your login and password here
local res, login, password, head = xpcall(
	function()
		require('pm')
		-- получаем логин, пароль, заголовок браузера
		return pm.GetPassword('kinozal')
	end, err
)
if login == '' or password == '' or login == nil or password == nil then
	m_simpleTV.OSD.ShowMessage("kinozal.tv - Login and Password is required", 255, 10)
	return
end

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

---------------------------------------------------------------------------------------------------------------------------
local retAdr
local session = m_simpleTV.WinInet.New("Opera/9.80 (Windows NT 6.1; U; ru) Presto/2.9.168 Version/11.52")
if session == nil then return end
--INTERNET_OPTION_CONNECT_TIMEOUT
m_simpleTV.WinInet.SetOptionInt(session, 2, 3000, 0)
--INTERNET_OPTION_RECEIVE_TIMEOUT
m_simpleTV.WinInet.SetOptionInt(session, 6, 5000, 0)
--http://kinozal.tv/details.php?id=1217472
--http://kinozal.tv/download.php/1217472/[kinozal.tv]id1217472.torrent

local host = 'http://kinozal.tv/takelogin.php'
local body = 'username=' .. login .. '&password=' .. password
local header = 
	'Host: kinozal.tv\n' ..
	'Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,bg;q=0.2,fr;q=0.2\n' ..
	'Referer: http://kinozal.tv/\n' ..
	'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\n' ..
	'Content-Type: application/x-www-form-urlencoded'
local rc, answer = m_simpleTV.WinInet.Post(session, host, nil, header, body)
if rc ~= 200 then
	m_simpleTV.WinInet.Close(session)
	m_simpleTV.OSD.ShowMessage("Connection error - " .. rc, 255, 10)
	return
end
--debug_in_file(answer, nil, true)
--[[
local cookie = m_simpleTV.WinInet.GetCookies(session, host, '')
local uid =  findpattern(cookie, 'uid=(.-);', 1, 4, 1)
]]
--debug_in_file(cookie, nil, true)
local retAdr = inAdr

if string.match(retAdr, 'kinozal%.tv/details%.php%?id=') then
	retAdr = string.gsub(retAdr, '/details%.php', '/download%.php')
end
local id = findpattern(retAdr, '\?id=(.+)', 1, 4, 0)
local tmpName = ''
if id ~= nil then tmpName = m_simpleTV.Common.DownloadFileInTmp(retAdr, id .. '.tmp', false) end

m_simpleTV.WinInet.Close(session)

local f = io.open(tmpName , "r")
if not f then return end
f:seek("set", 0)
local line = f:read("*l")
io.close(f)
if string.match(line, '<\!DOCTYPE HTML>') then
	m_simpleTV.OSD.ShowMessage_UTF8(RuStr("Вы возможно превысили лимит скачивания."), 255, 10)
	m_simpleTV.Control.CurrentAdress = 'error'
	return
end

debug_in_file(tmpName .. '\n', nil, true)
m_simpleTV.Control.ChangeAdress = 'Yes'
m_simpleTV.Control.CurrentAdress = 'torrent://' .. tmpName