--script for moevideo.net (14/04/2013)
--get adress
require('json')

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, 'moevideo%.net' ) then return end

m_simpleTV.Control.ChangeAdress='Yes'
m_simpleTV.Control.CurrentAdress = ''

 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)

-----------------------------------------------
 local rc,answer=m_simpleTV.WinInet.Get(session,inAdr)

 if rc~=200 then
	   m_simpleTV.WinInet.Close(session)
	   m_simpleTV.OSD.ShowMessage("Connection error - " .. rc ,255,10)
	   return
 end
answer = m_simpleTV.Common.string_fromUTF8(answer)
local header =  findpattern( answer,'<title>(.-)</title>',1,7,8)

if header==nil then header=inAdr end

if m_simpleTV.Control.CurrentTitle ~= nil then m_simpleTV.Control.CurrentTitle=header end
--debug_in_file(answer .. '\n')

local body,host,adr
adr = findpattern(inAdr,'/video/(.+)',1,7,0)
if adr == nil then return end

host = 'http://api.moevideo.net/'
body = 'r=%5B%22tVL0gjqo5%22%2C%5B%22preview%2Fflv%5Fimage%22%2C%7B%22uid%22%3A%22' .. adr .. '%22%7D%5D%2C%5B%22preview%2Fflv%5Flink%22%2C%7B%22uid%22%3A%22' .. adr .. '%22%7D%5D%5D'

header = 
'Host: api.moevideo.net\n' ..
'Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1\n' ..
'Accept-Language: ru-RU,ru;q=0.9,en;q=0.8\n' ..
'Referer: http://moevideo.net/swf/letplayer.swf\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 .. '\n')

local t = json.decode(answer)

if t == nil or t.data[2].link == nil then
   m_simpleTV.OSD.ShowMessage("Error - video is not available for playback"  ,255,10)
   return
end

retAdr = t.data[2].link 

m_simpleTV.WinInet.Close(session)
m_simpleTV.Control.CurrentAdress = retAdr