function trim(s)
  return (s:gsub("^%s*(.-)%s*$", "%1"))
end
-------------------------------------------------------
function String2Upper(s)
  for i = 224, 255 do
    s = s:gsub(string.char(i), string.char(i - 32))
  end
  s = s:gsub(string.char(184), string.char(168))
  return s:upper()
end
-------------------------------------------------------
local function GetFilterTable(value)
     local FilterTable = {}
     local i=1
     for w in string.gmatch(value,'"(.-)"') do 
         if w == nil then break end
         w = trim(w)
         local CurrenName,NewName,GroupName,EpgSource = string.match(w,'(.-),(.-),(.-),(.-)$')
         if CurrenName == nil or NewName == nil or GroupName == nil or EpgSource == nil then break end
   --debug_in_file(CurrenName .. ' ,' .. NewName .. ' ,' .. GroupName .. ' ,' .. EpgSource .. '\n')
   
         FilterTable[i] = {}
         FilterTable[i][1] = CurrenName
         FilterTable[i][2] = NewName
         FilterTable[i][3] = GroupName
         FilterTable[i][4] = EpgSource
     
        i=i+1
     end
  return FilterTable
end

-----------------------------------------------------------------
local function FilterChannels(name,filter)

if filter == nil then filter = m_simpleTV.User.ToolsAddon.FilterTable end

if filter == nil then return nil end

local group=''
local epgSource =''

name = m_simpleTV.Common.string_fromUTF8(name)

local upname = String2Upper(name)
upname = m_simpleTV.Common.string_toUTF8(upname)
--debug_in_file(upname .. '\n')

name = m_simpleTV.Common.string_toUTF8(name)

  for k,v in ipairs(filter) do
     if upname == v[1] then name = v[2] group = v[3] epgSource = v[4] end
  end
  return name,group,epgSource
end
-------------------------------------------------------
function FileExists(file)
   local fhandle = io.open(file,"r")
   if fhandle ~= nil then 
      io.close(fhandle) 
         return true 
     else 
        return false 
    end
end
-------------------------------------------------------
function OnNavigateComplete(Object) 

  m_simpleTV.User.ToolsAddon.FilterTable = nil

  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ResetButton','OnClickButtonClear')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonClearProxy','OnClickButtonClearProxy')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ResetAllButton','OnClickButtonClearAll')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonM3U','OnClickButtonM3U')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonRTMP','OnClickButtonRTMP')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonXSPF','OnClickButtonXSPF')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonRDup','OnClickButtonRDup')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonXML','OnClickButtonXML')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonLoadPls','OnClickButtonLoadPls')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonSavePls','OnClickButtonSavePls')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','CloseButton','OnClickCloseButton')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','HelpButton','OnClickHelpButton')

  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ExtFilterRefresh','OnClickExtFilterRefresh')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','GetExtFilterChannels','OnClickGetExtFilterChannels')
--  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','UpdateExtFilterChannels','OnClickUpdateExtFilterChannels')

  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','DefaultSettings','OnClickDefaultSettings')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','SaveSettings','OnClickSaveSettings')
--  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','AppendToFilterFile','OnClickAppendToFilterFile')
--  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','SaveNewFilterFile','OnClickSaveNewFilterFile')

  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','EditFilter','OnClickEditFilter')
--  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','SaveFilterChanges','OnClickSaveFilterChanges')

  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ConvertTVSFilter','OnClickConvertTVSFilter')
--  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','SaveTVSFilter','OnClickSaveTVSFilter')

  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','BackupFilter','OnClickBackupFilter')
--  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','DebugTable','OnClickDebugTable')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonPathToTVSSaveDirectory','OnClickButtonPathToTVSSaveDirectory')
  m_simpleTV.Dialog.AddEventHandler(Object,'OnClick','ButtonClearTVSFilterFilename','OnClickButtonClearTVSFilterFilename')

  m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'Groups', '')

--check tvsource files exists
  local tvs_ch_filter = m_simpleTV.MainScriptDir .. "user\\TVSources\\core\\channel_filter.lua"
  local tvs_gr_filter = m_simpleTV.MainScriptDir .. "user\\TVSources\\core\\channel_group.lua"

  if FileExists(tvs_ch_filter) then
     m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSChannelFilterStatus', '<div style="color:green;">File is found</div>')
    m_simpleTV.Dialog.SetElementValueString(Object,'TVSChannelFilterValue',tvs_ch_filter) 
   else
     m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSChannelFilterStatus', '<div style="color:red;">File not found</div>')
    m_simpleTV.Dialog.SetElementValueString(Object,'TVSChannelFilterValue','') 
  end  

  if FileExists(tvs_gr_filter) then
     m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSGroupFilterStatus', '<div style="color:green;">File is found</div>')
    m_simpleTV.Dialog.SetElementValueString(Object,'TVSGroupFilterValue',tvs_gr_filter) 
   else
     m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSGroupFilterStatus', '<div style="color:red;">File not found</div>')
    m_simpleTV.Dialog.SetElementValueString(Object,'TVSGroupFilterValue','') 
  end  

  m_simpleTV.Dialog.SetElementText(Object, 'Mess2', '')
----------------------------
--Settings
  local ini = io.open(m_simpleTV.MainScriptDir .. "user/Tools/tools.ini")
  if ini == nil then return end
  value = ini:read("*all")
  ini:close()
--debug_in_file(value .. '\n')  
  local PathToFilterFile = string.match(value,'PathToFilterFile=(.-);')
  local PathToGroupFile = string.match(value,'PathToGroupFile=(.-);')

  local FilterFile = string.match(value,'EnableFilter=(.-);')

   if PathToFilterFile ~= '' and PathToFilterFile ~= nil then 
     local FilePath = m_simpleTV.Common.string_fromUTF8(PathToFilterFile)
     local fhandle = io.open(FilePath, 'r')
     if fhandle == nil then return end
     value = fhandle:read("*all")
     fhandle:close()
--debug_in_file(value .. '\n')          
       --  if FilterFile == '1' then
            value = GetFilterTable(value)
            if value ~= nil then 
	       m_simpleTV.User.ToolsAddon.FilterTable  = value 
              else
               m_simpleTV.User.ToolsAddon.FilterTable  = nil
            end
--debug FilterTable
--[[
              for k, v in ipairs(m_simpleTV.User.ToolsAddon.FilterTable) do 
               debug_in_file(v[1] .. '\n')
              end
]]
       --  end
   end

   if PathToGroupFile ~= '' and PathToGroupFile ~= nil then 
     local FilePath = m_simpleTV.Common.string_fromUTF8(PathToGroupFile)
     local groups = io.open(FilePath, 'r')
     for line in groups:lines() do
      m_simpleTV.Dialog.AddComboValue_UTF8(Object,'Groups',line,-1)  
     end
     groups:close()
    m_simpleTV.Dialog.SelectComboIndex(Object,'Groups',0)

   end

  if m_simpleTV.User.ToolsAddon.FilterFileValue == FilterFile then
      m_simpleTV.Dialog.SetCheckBoxValue(Object,'FilterFile',FilterFile)
   elseif m_simpleTV.User.ToolsAddon.FilterFileValue ~= nil then
      m_simpleTV.Dialog.SetCheckBoxValue(Object,'FilterFile',m_simpleTV.User.ToolsAddon.FilterFileValue)
   else
      m_simpleTV.Dialog.SetCheckBoxValue(Object,'FilterFile',FilterFile)
  end


  m_simpleTV.Dialog.SetElementText_UTF8(Object, 'PathToFilterFile', PathToFilterFile)
  m_simpleTV.Dialog.SetElementText_UTF8(Object, 'PathToGroupFile', PathToGroupFile)
  
--Get ExtFilterList
  local sqlstr = 'Select extfilter.id, extfilter.name from extfilter where extfilter.typemedia=0' 
  local dTable_ExtFilter = m_simpleTV.Database.GetTable(sqlstr)

  if dTable_ExtFilter == nil or dTable_ExtFilter[1]==nil or dTable_ExtFilter[1].id==nil then 
      m_simpleTV.OSD.ShowMessage("ExtFilterList not found " ,255,3)
      m_simpleTV.Dialog.SetElementText(Object, 'Mess', 'ExtFilterList not found')
    return 
  end


if m_simpleTV.User.ToolsAddon.ExtFilterName ~= nil then
   m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'ExtFilterList', '')
end

--debug_in_file(m_simpleTV.User.ToolsAddon.ExtFilterName)

     local ExtFilterId = 0
     local droplist=''
     local count=0
     for i=1,#dTable_ExtFilter,1 do
         
         local ExtFilterName =  dTable_ExtFilter[i].name
         if m_simpleTV.User.ToolsAddon.ExtFilterName == ExtFilterName then ExtFilterId = i end
         m_simpleTV.Dialog.AddComboValue_UTF8(Object,'ExtFilterList',ExtFilterName,-1)
       -- droplist = droplist .. '           <option value="' .. count .. '">' .. ExtFilterName .. '</option>\n'
       -- count=count+1
     end
     --m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'ExtFilterList', droplist)


   if m_simpleTV.User.ToolsAddon.ExtFilterName == nil then
       m_simpleTV.Dialog.SelectComboIndex(Object,'ExtFilterList',0)
     else
       m_simpleTV.Dialog.SelectComboIndex(Object,'ExtFilterList',ExtFilterId-1)
   end

end
-----------------------------------------------------------------

---Convert TVS filters
---------------------------------------------------------
function OnClickButtonPathToTVSSaveDirectory(Object)

 local path =  m_simpleTV.Common.FolderPicker('Select directory')
 if path~=nil then 
     path = path .. '\\'
    m_simpleTV.Dialog.SetElementValueString(Object,'PathToTVSSaveDirectory',path) 
 end

end
---------------------------------------------------------
function OnClickButtonClearTVSFilterFilename(Object)
   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'SetTVSFilterFilename', '')
end
-----------------------------------------------------------------
function OnClickSaveTVSFilter(Object,TVSTable)

--   local TVSTable = m_simpleTV.Dialog.GetElementHtml_UTF8(Object,'TVSTable')
   if TVSTable == nil or TVSTable == '' then return end
   --debug_in_file(TVSTable  .. '\n\n')

   TVSTable = m_simpleTV.Common.string_fromUTF8(TVSTable)
   TVSTable = string.gsub(TVSTable,'&nbsp;','' )

   local out = ''
   for w in string.gmatch(TVSTable,'<tr class="row">(.-)</tr>') do
  
      local CurrentName = string.match(w,'col="oldname">(.-)<')
      local NewName = string.match(w,'col="newname">(.-)<')
      local GroupName = string.match(w,'col="groupname">(.-)<')
      local Source = string.match(w,'col="sourcename">(.-)<')

    if CurrentName ~= nil and NewName ~= nil and GroupName ~= nil and Source ~= nil then

      out = out .. '"' .. String2Upper(CurrentName)  .. ',' .. trim(NewName) .. ',' .. trim(GroupName) .. ',' .. trim(Source) ..'"\n'
  
    end
 end

   out = m_simpleTV.Common.string_toUTF8('--TVS Filter utf-8 on ' .. os.date("%d.%m.%Y %X") .. '\n\n' .. out)
--debug_in_file(out)

 local path = m_simpleTV.Dialog.GetElementValueString(Object,'PathToTVSSaveDirectory')
 local filename = m_simpleTV.Dialog.GetElementValueString(Object,'SetTVSFilterFilename')

 if path == 'Choose directory to save file...' or path == '' or filename == 'Set the file name...' or filename == '' then return end
 path = path .. filename .. '.txt'

 local fhandle = io.open (path , "w+")
 if fhandle==nil then return end
 fhandle:write(out)
 fhandle:close()

  if FileExists(path) then
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess2', 'File saved successfully')
     m_simpleTV.Common.Wait(2000) 
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess2', '')
   else
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess3', 'Error - File cannot be saved')
     m_simpleTV.Common.Wait(2000) 
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess3', '')
  end
end
-----------------------------------------------------------------
function OnClickConvertTVSFilter(Object)

  m_simpleTV.User.ToolsAddon.ExtFilterName = m_simpleTV.Dialog.GetComboValue_UTF8(Object,'ExtFilterList')

  local tvs_ch_filter = m_simpleTV.Dialog.GetElementValueString(Object,'TVSChannelFilterValue')
  local tvs_gr_filter = m_simpleTV.Dialog.GetElementValueString(Object,'TVSGroupFilterValue')

  if tvs_ch_filter == '' or tvs_gr_filter == '' then return end

  local value1 = m_simpleTV.Dialog.GetElementHtml_UTF8(Object, 'TVSChannelFilterStatus')
  local value2 = m_simpleTV.Dialog.GetElementHtml_UTF8(Object, 'TVSGroupFilterStatus')

  if string.match(value1,'File is found') and string.match(value2,'File is found') then
--debug_in_file(tvs_ch_filter .. '\n' .. tvs_gr_filter .. '\n')
  m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSTable', '<span style="color:#47D1FF;font-size:12px;">The data is converted. Please wait...</span>')
  m_simpleTV.Common.Wait(1000)

   local ch_filter = dofile (tvs_ch_filter)
   local gr_filter = dofile (tvs_gr_filter)

local function GetGroup(value,filter)

 if filter == nil then filter = gr_filter end

 local group=''
  for k,v in pairs(filter) do
    if value == v[1] then group = v[2] end 
  end

   return group  
end

 local source = 'TVSource'
 local out=''
 local i=1
 for k,v in pairs(ch_filter) do

   local oldname = v[1]
   local newname = v[2]
   if oldname == nil or newname == nil then return end

   local group = GetGroup(newname)
   if group == '' then group = '!No Group' end

--debug_in_file(oldname .. ',' .. newname ..',' .. group .. '\n')


out = out .. 
'        <tr class="row">\n' ..
'            <td>\n' ..
'                <input name="TVScheckbox" type="checkbox" id="TVSCheck' .. i .. '"></td>\n' .. 
'            <td>\n' .. 
'                <label for="TVSCheck' .. i .. '" col="oldname">' .. oldname .. '</label>\n' ..
'            </td>\n' ..
'            <td>\n' .. 
'                <div class="editable" contenteditable="true" col="newname">' .. newname .. '</div>\n' ..
'            </td>\n' ..
'            <td>\n' ..
'                <div id="TVSgrpname' .. i .. '" class="editable" contenteditable="true" col="groupname">' .. group .. '</div>\n' .. 
'            </td>\n' ..
'            <td col="sourcename">' .. source .. '</td>\n' ..
'        </tr>\n' 
    i=i+1
  end

out = 
'<div id="tvstable">\n' .. 
'<h3>Filter: ' .. source .. ', <span id="tvscount" style="color:#47D1FF;font-size:12px;"></span></h3>\n' ..
'<table id="TVSsort" class="sort">\n' ..
'    <thead>\n' .. 
'        <tr>\n' ..
'            <th><input name="TVScheckbox" id="TVSCheckAll" type="checkbox" onclick="TVSCheckAll(this)"></th>\n' ..
'            <th>Current Name</th>\n' ..
'            <th>New Name</th>\n' ..
'            <th>Group</th>\n'  ..
'            <th>Source</th>\n' ..
'        </tr>\n' ..
'    </thead>\n' .. 
'    <tbody>\n' .. out .. 
'    </tbody>\n' ..
'</table>\n' ..
'</div>\n' ..
'<br><center><a class="totop" href="#" onclick="JumpTop();return false;">JUMP TO TOP</a></center>'

local head =
'<!DOCTYPE html>\n' .. 
'<head>\n' .. 
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' .. 
'<meta http-equiv="X-UA-Compatible" content="IE=10">\n' .. 
'<link rel="stylesheet" href="css/tool.css" />\n' .. 
'<script type="text/javascript" src="misc/jquery.min.js"></script>\n' .. 
'<script type="text/javascript" src="misc/jquery.checkboxes-1.0.6.min.js"></script>\n' .. 
'<script type="text/javascript" src="misc/jquery.ordertable.min.js"></script>\n' .. 
'<style>\n' ..
'body {background-color:#FFFFFF;}\n' ..
'</style>\n' ..
'</head>\n' .. 
'<body>\n' ..
"<script>$(function() {$('#TVSsort').checkboxes('range', true);   $('#TVSsort').orderTable({excludeColumns:[0]});  $('[contenteditable=true]').bind('paste',function(t){var a='',i=$(this);return t.clipboardData?a=t.clipboardData.getData('text/plain'):window.clipboardData?a=window.clipboardData.getData('Text'):t.originalEvent.clipboardData&&(a=$('<div></div>').text(t.originalEvent.clipboardData.getData('text'))),document.queryCommandSupported('insertText')?(document.execCommand('insertHTML',!1,$(a).html()),!1):(i.find('*').each(function(){$(this).addClass('within')}),void setTimeout(function(){i.find('*').each(function(){$(this).not('.within').contents().unwrap()})},1))});  var count = 'Records: ' + $('#TVSsort tr').not('thead tr').length; $('#tvscount').html(count);});</script>\n\n"

local footer = 
'<script>function TVSCheckAll(e){checkboxes=document.getElementsByName("TVScheckbox");for(var c=0,n=checkboxes.length;n>c;c++)checkboxes[c].checked=e.checked} function JumpTop() { document.body.scrollTop = document.documentElement.scrollTop = 0;};</script>\n' ..
'</body>\n' .. 
'</html>'

out = head .. out .. footer


  local fhandle = io.open (m_simpleTV.MainScriptDir .. "user/Tools/EditTVS.html" , "w+")
  if fhandle==nil then return end
  fhandle:write(out)
  fhandle:close()

  m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSTable', '<iframe id="frametvs" src="EditTVS.html" width="750" height="320" frameborder="0" onload="frametvsonload()"><p>Your browser does not support iframes.</p></iframe>')

 end

end
------------------------------------------------------------------------

-------Rename Channels
----------------------------------------------------------------------
function OnClickSaveSettings(Object)

--save settings

   local ini = m_simpleTV.MainScriptDir .. "user/Tools/tools.ini"
   os.remove(ini)

    ini = io.open(m_simpleTV.MainScriptDir .. "user/Tools/tools.ini",'a+')
    if ini == nil then return end
    local PathToFilterFile = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'PathToFilterFile')
    local PathToGroupFile = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'PathToGroupFile')
    local FilterFile = m_simpleTV.Dialog.GetCheckBoxValue(Object,'FilterFile')
    
    local str = 'PathToFilterFile=' .. PathToFilterFile ..';\n' .. 'PathToGroupFile=' .. PathToGroupFile  ..';\n' .. 'EnableFilter=' .. FilterFile .. ';\n'
    ini:write(str)
    ini:close()

end
-----------------------------------------------------------------
function OnClickBackupFilter(Object)

--backup filter
  m_simpleTV.Dialog.SetElementText(Object, 'Mess', '')

 local PathToFilterFile = m_simpleTV.Dialog.GetElementValueString(Object,'PathToFilterFile')
 if PathToFilterFile == nil then return end

 local fhandle = io.open(PathToFilterFile)
 if fhandle == nil then return end
 local filter = fhandle:read("*all")
 fhandle:close()

 local BackupFilePath = string.gsub(PathToFilterFile,'.txt','')

 local t = {}
 t.day,t.month,t.year,t.hour,t.min,t.sec = string.match(os.date("%d.%m.%Y %X"),"(%d*).(%d*).(%d*) (%d*):(%d*):(%d*)")
  local date = t.year .. t.month .. t.day.. '_' .. t.hour .. t.min .. t.sec

  if FileExists(PathToFilterFile) then
   os.rename(PathToFilterFile, BackupFilePath .. "_" .. date ..".bak")
  end

 fhandle = io.open (PathToFilterFile , "w+")
 if fhandle==nil then return end
 fhandle:write(filter)
 fhandle:close()

  m_simpleTV.Dialog.SetElementHtml(Object, 'Mess', '<span style="color:#47D1FF;font-size:11px;">Backup completed.</span>')
  m_simpleTV.Common.Wait(3000) 
  m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')

end
-----------------------------------------------------------------
function OnClickExtFilterRefresh(Object)

--Refresh ExtFilterList
  m_simpleTV.Dialog.SetElementText_UTF8(Object, 'ExtFilterList', '')
  m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')
  local sqlstr = 'Select extfilter.id, extfilter.name from extfilter where extfilter.typemedia=0' 
  local dTable_ExtFilter = m_simpleTV.Database.GetTable(sqlstr)

  if dTable_ExtFilter == nil or dTable_ExtFilter[1]==nil or dTable_ExtFilter[1].id==nil then 
      m_simpleTV.OSD.ShowMessage("ExtFilterList not found " ,255,3)
      m_simpleTV.Dialog.SetElementText(Object, 'Mess', 'ExtFilterList not found')
    return 
  end
  local count=0
  for i=1,#dTable_ExtFilter,1 do
     
      local ExtFilterName = dTable_ExtFilter[i].name
      m_simpleTV.Dialog.SelectComboIndex(Object,'ExtFilterList',count)
      local value = m_simpleTV.Dialog.GetComboValue_UTF8(Object,'ExtFilterList')
--debug_in_file(ExtFilterName .. '  ' .. value .. '\n')
      if value ~= ExtFilterName then
          m_simpleTV.Dialog.AddComboValue_UTF8(Object,'ExtFilterList',ExtFilterName,-1)
      end
     count=count+1
  end
  m_simpleTV.Dialog.SelectComboIndex(Object,'ExtFilterList',0)

end
-----------------------------------------------------------------
function OnClickGetExtFilterChannels(Object)

  m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')
  m_simpleTV.Dialog.SetElementText(Object, 'ChannelsTable', '')    

  m_simpleTV.User.ToolsAddon.ExtFilterName = m_simpleTV.Dialog.GetComboValue_UTF8(Object,'ExtFilterList')

  local ExtFilterName  = m_simpleTV.Dialog.GetComboValue_UTF8(Object,'ExtFilterList')
  if ExtFilterName == nil or ExtFilterName == '' then 
      m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', 'ExtFilter not found')
    return 
  end

--debug_in_file(m_simpleTV.User.ToolsAddon.ExtFilterName .. ' afterGet\n')

  
  local PathToFilterFile = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'PathToFilterFile')
  local PathToGroupFile = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'PathToGroupFile')

  if (PathToFilterFile == '') and (PathToGroupFile == '' ) then
      m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', 'Filter and Group files not found')
    return 
  end

  if PathToFilterFile == '' then
      m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', 'Filter file not found')
    return 
  end

  if PathToGroupFile == '' then
      m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', 'Group file not found')
    return 
  end

  local sqlstr

  sqlstr = 'Select extfilter.id from extfilter where extfilter.name="' .. ExtFilterName .. '"'
  local dTable_ExtFilter = m_simpleTV.Database.GetTable(sqlstr)
  if dTable_ExtFilter == nil or dTable_ExtFilter[1]==nil then return end

  local ExtFilterId = dTable_ExtFilter[1].id

  sqlstr = 'Select main.id, main.name, main.adress, main.program, main.group from main where main.extfilter=' .. ExtFilterId
  local dTable_Main = m_simpleTV.Database.GetTable(sqlstr)
  if dTable_Main == nil or dTable_Main[1] == nil then return end

  sqlstr = 'Select progchannel.id, progchannel.namechannel, progchannel.source from progchannel '
  local dTable_ProgChannel = m_simpleTV.Database.GetTable(sqlstr)
  if dTable_ProgChannel == nil or dTable_ProgChannel[1] == nil then return end

  sqlstr = 'Select Query_Group.id, Query_Group.groupname from Query_Group'
  local dTable_Query_Group = m_simpleTV.Database.GetTable(sqlstr)
  if dTable_Query_Group == nil or dTable_Query_Group[1] == nil then 

--add new tmp group to database
    local  New_Id = tonumber(0x10000000)
          m_simpleTV.Database.ExecuteSql('INSERT INTO Main (id,name,numchanel,extfilter) VALUES (' .. New_Id .. ',"tmpgroup",' .. New_Id .. ',0);',true) 
   end

  local function CheckAndRemoveGroup(id)
     for i=1,#dTable_Query_Group,1 do 
        if id == dTable_Query_Group[i].id then return false end
     end
     return true
  end

  local function GetName(name,dTable)
        local source
          for i,v in ipairs(dTable) do 
              if name == v.id then name = v.namechannel or v.groupname source = v.source end
          end
         return name, source
    end

  m_simpleTV.User.ToolsAddon.FilterFileValue = m_simpleTV.Dialog.GetCheckBoxValue(Object,'FilterFile')
  local FilterFile = m_simpleTV.User.ToolsAddon.FilterFileValue
--debug_in_file(m_simpleTV.User.ToolsAddon.FilterTable[1][1] .. '\n')

  local out=''
  local i = 1

for k,w in pairs(dTable_Main) do 

   local id = w.id
   local oldname = w.name
   local address = w.adress

  if CheckAndRemoveGroup(id)  then
   
      local group=GetName(w.group,dTable_Query_Group)
      if w.group == 0 then group = '!No Group' end
      local epgId = w.program 
      if epgId == nil then epgId = '' end
   
      local newname,source=GetName(epgId,dTable_ProgChannel)
      if source == nil then source = '!No Source' end


--debug_in_file(k .. ' ' .. id .. ' ' .. oldname .. ' ' .. newname .. ' ' .. group .. ' ' .. address .. ' ' .. epgId .. ' ' .. source .. '\n')

--use filter 

     if FilterFile == 1 then

      if m_simpleTV.User.ToolsAddon.FilterTable ~= nil then
           newname,group,source = FilterChannels(oldname)
           if source == '' and group == '' then 
               newname,source=GetName(epgId,dTable_ProgChannel)
               if source == nil then source = '!No Source' end
                 --source = 'No Source'
                 group = '!No Group' 
           end
           else
          group = '!No Group'
       end
 
   end

out = out .. 
'      <tr class="row">\n' ..
'        <td class="hide" col="channelId">' .. id .. '</td>\n' ..
'        <td>\n' ..
'          <input name="checkbox" id="Check' .. i .. '" type="checkbox">\n' ..
'        </td>\n' ..
'        <td>\n' ..
'          <label id="oldname' .. i .. '" for="Check' .. i .. '" col="oldname">' .. oldname .. '</label>\n' ..          
'        </td>\n' ..
'        <td>\n' ..
'          <div class="editable" id="newname' .. i .. '" contenteditable="true" col="newname">' .. newname .. '</div>\n' ..
'        </td>\n' ..
'        <td>\n' ..
'          <div class="editable" id="grpname' .. i .. '" contenteditable="true" col="groupname">' .. group .. '</div>\n' ..
'        </td>\n' ..
'        <td class="hide" col="address">' .. address .. '</td>\n' ..
'        <td col="sourcename">' .. source .. '</td>\n' ..
'      </tr>\n' 

      i=i+1
    end
end

out = 
'<div id="channelstable">\n' .. 
'<h3>ExtFilter: ' .. ExtFilterName .. ', <span id="countchannels" style="color:#47D1FF;font-size:12px;"></span></h3>\n' ..
'  <table class="sort" id="sort">\n' ..
'    <thead>\n' ..
'      <tr>\n' ..
'        <th class="hide">Channel Id</th>\n' ..
'        <th width="22"><input name="checkbox" id="CheckAll" type="checkbox" onclick="CheckAll(this)"></th>\n' ..
'        <th>Current Name</th>\n' ..
'        <th>New Name</th>\n' ..
'        <th>Group</th>\n' ..
'        <th class="hide">Channel Address</th>\n' ..
'        <th>Source</th>\n' ..
'      </tr>\n' ..
'    </thead>\n' ..
'    <tbody>\n' .. out ..
'    </tbody>\n' ..  
'  </table>\n' ..
'</div>\n' ..
'<br><center><a class="totop" onclick="JumpTop();return false;" href="#">JUMP TO TOP</a></center>'
  --debug_in_file(out)

local head =
'<!DOCTYPE html>\n' .. 
'<head>\n' .. 
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' .. 
'<meta http-equiv="X-UA-Compatible" content="IE=10">\n' .. 
'<link rel="stylesheet" href="css/tool.css" />\n' .. 
'<script type="text/javascript" src="misc/jquery.min.js"></script>\n' .. 
'<script type="text/javascript" src="misc/jquery.checkboxes-1.0.6.min.js"></script>\n' .. 
'<script type="text/javascript" src="misc/jquery.ordertable.min.js"></script>\n' .. 
'<style>\n' ..
'body {background-color:#FFFFFF;}\n' ..
'</style>\n' ..
'</head>\n' .. 
'<body>\n' ..
"<script>$(function() {$('#sort').checkboxes('range', true);   $('#sort').orderTable({excludeColumns:[0,1]});   $('[contenteditable=true]').bind('paste',function(t){var a='',i=$(this);return t.clipboardData?a=t.clipboardData.getData('text/plain'):window.clipboardData?a=window.clipboardData.getData('Text'):t.originalEvent.clipboardData&&(a=$('<div></div>').text(t.originalEvent.clipboardData.getData('text'))),document.queryCommandSupported('insertText')?(document.execCommand('insertHTML',!1,$(a).html()),!1):(i.find('*').each(function(){$(this).addClass('within')}),void setTimeout(function(){i.find('*').each(function(){$(this).not('.within').contents().unwrap()})},1))});  var count = 'Channels: ' + $('#sort tr').not('thead tr').length; $('#countchannels').html(count);});</script>\n\n"

local footer = 
'<script>function CheckAll(e){checkboxes=document.getElementsByName("checkbox");for(var c=0,n=checkboxes.length;n>c;c++)checkboxes[c].checked=e.checked} function JumpTop() { document.body.scrollTop = document.documentElement.scrollTop = 0;};</script>\n' ..
'</body>\n' .. 
'</html>'

out = head .. out .. footer

  local fhandle = io.open (m_simpleTV.MainScriptDir .. "user/Tools/EditChannels.html" , "w+")
  if fhandle==nil then return end
  fhandle:write(out)
  fhandle:close()

  m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'ChannelsTable', '<iframe id="framechannels" src="EditChannels.html" width="750" height="240" frameborder="0" onload="framechannelsonload()"><p>Your browser does not support iframes.</p></iframe>')

--delete tmp group from database
  m_simpleTV.Database.ExecuteSql('DELETE FROM Query_Group WHERE GroupName="tmpgroup";',true) 

end
-----------------------------------------------------------------------------------

function OnClickUpdateExtFilterChannels(Object,channels)

   if channels == nil or string.match(channels,'class="hide"') == nil then return end

  m_simpleTV.Dialog.SetElementText(Object, 'Mess', '')
  m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'Mess', '<span style="color:#47D1FF;font-size:11px;">The channels is updated. Please wait...</span>')
     m_simpleTV.Common.Wait(1000) 

  local function GetGroupTable()
     local sqlstr = 'Select Query_Group.id, Query_Group.groupname from Query_Group'
     local dTable_Query_Group = m_simpleTV.Database.GetTable(sqlstr)
     if dTable_Query_Group == nil or dTable_Query_Group[1] == nil then return nil end
      return dTable_Query_Group   
  end
  
  local function GroupExists(name,t)
    t = GetGroupTable() 
    if t == nil then return false end
     for k,w in pairs(t) do  
       if name == w.groupname then return true end
     end
       return false
  end

  local function GetGroupIdbyGroupName(name)
     local id 
     local t = GetGroupTable() 
     if t == nil then return nil end

     for k,w in pairs(t) do  
        if name == w.groupname then id = w.id end
     end
       return id
  end

  local function GetEpgIdbyChannelName(name,dTable)
        local id = ''
        local n = findpattern(name,'^(.-)%*',1,0,1)
        if n == nil then n = name end
        name = n
        name = m_simpleTV.Common.string_fromUTF8(name)
        name = trim(name)
        name = String2Upper(name)
        local namechannel 
          for i,v in ipairs(dTable) do 
	    namechannel = m_simpleTV.Common.string_fromUTF8(v.namechannel)
            namechannel = String2Upper(namechannel)
              if name == namechannel then id = v.id end
          end
         return id
    end

 --  local channels = m_simpleTV.Dialog.GetElementHtml_UTF8(Object,'ChannelsTable')

   channels = m_simpleTV.Common.string_fromUTF8(channels)
--debug_in_file(channels  .. '\n\n')

--   local ExtFilterName = string.match(channels,'ExtFilter: (.-),')
   local ExtFilterName = findpattern(channels,'ExtFilter: (.-),',1,11,1)
   if ExtFilterName == nil then return end

   local sqlstr = 'Select extfilter.id from extfilter where extfilter.name="' .. ExtFilterName .. '"'
   local dTable_ExtFilter = m_simpleTV.Database.GetTable(sqlstr)
   if dTable_ExtFilter == nil or dTable_ExtFilter[1] == nil then 
      m_simpleTV.Dialog.SetElementText(Object, 'Mess', 'ExtFilter not found in database. Update aborted.') 
      OnClickExtFilterRefresh(Object)  
      return 
   end
   local ExtFilterId = dTable_ExtFilter[1].id

  sqlstr = 'Select main.id, main.name, main.adress, main.program, main.group from main where main.extfilter=' .. ExtFilterId
  local dTable_Main = m_simpleTV.Database.GetTable(sqlstr)
  if dTable_Main == nil or dTable_Main[1] == nil then 
     m_simpleTV.Dialog.SetElementText(Object, 'Mess', 'Channels not found in database. Update aborted.')  
     m_simpleTV.Common.Wait(3000) 
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')  
      return 
   end

  sqlstr = 'Select progchannel.id, progchannel.namechannel, progchannel.source from progchannel '
  local dTable_ProgChannel = m_simpleTV.Database.GetTable(sqlstr)
  if dTable_ProgChannel == nil or dTable_ProgChannel[1] == nil then return end

  channels = string.gsub(channels,'&nbsp;','' )

 for w in string.gmatch(channels,'<tr class="row">(.-)</tr>') do

  local ChannelId = string.match(w,'col="channelId">(.-)<')
  local ChannelName = string.match(w,'col="newname">(.-)<')
  local GroupName = string.match(w,'col="groupname">(.-)<')
  local Source = string.match(w,'col="sourcename">(.-)<')
  local ChannelAddress = string.match(w,'col="address">(.-)<')

    if ChannelId ~= nil and ChannelName ~= nil and GroupName ~= nil and Source ~= nil then

       if trim(ChannelName) == '' then 
          m_simpleTV.Dialog.SetElementText(Object, 'Mess', 'Detected an empty channel names in New Name column. Update aborted.')   
        m_simpleTV.Common.Wait(3000) 
        m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')   
         return 
       end

    if trim(GroupName) == '' then GroupName = '!No Group' end

    ChannelName = trim(ChannelName) 
    GroupName = trim(GroupName) 

    GroupName = m_simpleTV.Common.string_toUTF8(GroupName)
    ChannelName = m_simpleTV.Common.string_toUTF8(ChannelName)
    ChannelAddress = m_simpleTV.Common.string_toUTF8(ChannelAddress)

--debug_in_file(ChannelId .. ' ' .. ChannelName .. ' ' .. GroupName .. ' ' .. ChannelAddress .. '\n')

  if not GroupExists(GroupName) then
       local New_Id 
       local dTable_Query_Group = GetGroupTable()
       
       if dTable_Query_Group ~= nil and dTable_Query_Group[1] ~= nil then
          local sqlstr = 'SELECT (Max(Query_Group.Id)+1) AS [New_Id] FROM Query_Group;'
          local dTable = m_simpleTV.Database.GetTable(sqlstr)
          New_Id = dTable[1].New_Id
         else
          New_Id = tonumber(0x10000000)
       end
   
--add new group to database
      m_simpleTV.Database.ExecuteSql('INSERT INTO Main (id,name,numchanel,extfilter) VALUES (' .. New_Id .. ',"' .. GroupName .. '",' .. New_Id .. ',' .. ExtFilterId .. ');',true) 
  
    end
  
    local GroupId = GetGroupIdbyGroupName(GroupName)
    if GroupId == nil then return end

    local EpgId = GetEpgIdbyChannelName(ChannelName,dTable_ProgChannel)

--update channel  
    m_simpleTV.Database.ExecuteSql('UPDATE Main SET Main.Name =  "' .. ChannelName .. '", Main.program =  "' .. EpgId .. '", Main.[Group] = ' .. GroupId .. ' WHERE (Main.Id=' .. ChannelId .. ');',true) 
  end
 end

  sqlstr = 'Select main.id, main.name, main.group from main where main.extfilter=' .. ExtFilterId
  local dTable_Main = m_simpleTV.Database.GetTable(sqlstr)
  if dTable_Main == nil or dTable_Main[1] == nil then return end

  local t = GetGroupTable() 

  local function CheckNoEmptyGroup(id)
     for i=1,#dTable_Main,1 do 
        if id == dTable_Main[i].group then return true end
     end
     return false
  end

  for k,w in pairs(t) do  
     local id = w.id
     if not CheckNoEmptyGroup(id) then
--debug_in_file(w.groupname ..'\n')
--remove group with no channels from extfilter 
        m_simpleTV.Database.ExecuteSql('UPDATE Main SET Main.extfilter = 0 WHERE (Main.Id=' .. id .. ');',true)
     end
  end


  m_simpleTV.Interface.MessageBox('Channels updating completed.','Tools add-on - Update Channels',0,Object)
  m_simpleTV.Dialog.SetElementText(Object, 'Mess', '')
end
-------------------------------------------------------------------------------
function OnClickAppendToFilterFile(Object,channels)
--debug_in_file(channels)
   if channels == nil or string.match(channels,'class="hide"') == nil then return end

  local num = m_simpleTV.Interface.MessageBox('Empty cells and !No Group will be ignored.','Tools add-on - Add data to filter file',1,Object)
--debug_in_file(num)
  if num == 2 then return end

   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')

  -- local channels = m_simpleTV.Dialog.GetElementHtml_UTF8(Object,'ChannelsTable')

   if string.match(channels,'id="filter"') then
      m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', 'To save data click on Save Changes button.')
      m_simpleTV.Common.Wait(3000) 
      m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')
     return 
   end

 channels = m_simpleTV.Common.string_fromUTF8(channels)
 channels = string.gsub(channels,'&nbsp;','' )

 local out = ''
 for w in string.gmatch(channels,'<tr class="row">(.-)</tr>') do

  local CurrentName = string.match(w,'col="oldname">(.-)<')
  local NewName = string.match(w,'col="newname">(.-)<')
  local GroupName = string.match(w,'col="groupname">(.-)<')
  local Source = string.match(w,'col="sourcename">(.-)<')

  if CurrentName ~= nil and NewName ~= nil and GroupName ~= nil and Source ~= nil then

       if trim(NewName) ~= '' and trim(GroupName) ~= '!No Group' and trim(GroupName) ~= '' then
          out = out .. '"' .. String2Upper(CurrentName)  .. ',' .. trim(NewName) .. ',' .. trim(GroupName) .. ',' .. Source ..'"\n'
       end
    end
  end
   out = m_simpleTV.Common.string_toUTF8(out)
--debug_in_file(out)


--  local FilterFile = m_simpleTV.MainScriptDir .. "user\\Tools\\default\\filter.txt"
  local FilterFile = m_simpleTV.Dialog.GetElementValueString(Object,'PathToFilterFile')
  local fhandle = io.open(FilterFile,"a+")
  if fhandle == nil then 
      m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', 'Sorry bro, I cannot add data to nowhere.')
      m_simpleTV.Common.Wait(3000) 
      m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')
    return 
  end
  fhandle:write(out)
  fhandle:close()

  fhandle = io.open(FilterFile,"r")
  if fhandle == nil then return end
  channels = fhandle:read("*all")
  fhandle:close()

--debug_in_file(channels.. '\n')

  local dup={}
  for w in string.gmatch(channels,'"(.-)"') do
     if w == nil then break end
     dup[#dup+1] = w
  end

local function RemoveDuplicates(t)
  local hash = {} 
  local res = {} 
  for _,v in ipairs(t) do 
     if (not hash[v]) then 
        res[#res+1] = v 
        hash[v] = true 
     end
  end
  return  res
end

local res = RemoveDuplicates(dup)
local str = 
'--filter list utf-8 on ' .. os.date("%d.%m.%Y %X") .. '\n' ..
'--current channel name allways in uppercase, new name, group name, epg source name\n\n'

  str = m_simpleTV.Common.string_toUTF8(str)

  fhandle = io.open(FilterFile,"w+")
  if fhandle == nil then return end
  fhandle:write(str)

  table.sort(res)
  for i,v in ipairs(res) do 
       v = '"' .. v .. '"\n'
       fhandle:write(v)
    -- debug_in_file(v)
  end
  fhandle:close()

  fhandle = io.open(FilterFile,"r")
  if fhandle == nil then return end
  channels = fhandle:read("*all")
  fhandle:close()

  m_simpleTV.User.ToolsAddon.FilterTable = nil
  m_simpleTV.User.ToolsAddon.FilterTable = GetFilterTable(channels)
--debug_in_file(m_simpleTV.User.ToolsAddon.FilterTable[1][1] .. '\n')

  m_simpleTV.Interface.MessageBox('Data has been successfully added to filter file.','Tools add-on - Add data to filter file',0,Object)

end
-------------------------------------------------------------------------------
function OnClickSaveNewFilterFile(Object,channels)


   if channels == nil or string.match(channels,'class="hide"') == nil then return end

   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')

--local channels = m_simpleTV.Dialog.GetElementHtml_UTF8(Object,'ChannelsTable')

if channels ~= nil then
 channels = string.gsub(channels,'&nbsp;','' )

 for w in string.gmatch(channels,'<tr class="row">(.-)</tr>') do

  local CurrentName = string.match(w,'col="oldname">(.-)<')
  local NewName = string.match(w,'col="newname">(.-)<')
  local GroupName = string.match(w,'col="groupname">(.-)<')
  local Source = string.match(w,'col="sourcename">(.-)<')

    if CurrentName ~= nil and NewName ~= nil and GroupName ~= nil and Source ~= nil then

    if trim(GroupName) == '!No Group' and (trim(NewName) == '' or trim(GroupName) == '' or trim(Source) == '') then
         m_simpleTV.Dialog.SetElementText(Object, 'Mess', "Detected an empty cells and !No Group in Group column. Aborted.")
       m_simpleTV.Common.Wait(3000) 
       m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')
       return 
   end
   if trim(NewName) == '' or trim(GroupName) == '' or trim(Source) == '' then
         m_simpleTV.Dialog.SetElementText(Object, 'Mess', 'Detected an empty cells. Aborted.')      
       m_simpleTV.Common.Wait(3000) 
       m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')
       return 
   end
    if trim(GroupName) == '!No Group' then
         m_simpleTV.Dialog.SetElementText(Object, 'Mess', "Detected !No Group in Group column. Aborted.") 
       m_simpleTV.Common.Wait(3000) 
       m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Mess', '')
       return 
   end
 end
end

local ObjectSaveFilter = m_simpleTV.Dialog.Show('Save as new filter file',m_simpleTV.MainScriptDir .. 'user\\Tools\\SaveFilter.html','user\\Tools\\SaveFilter.lua',350,250,1+32,Object)  
 end
end
----------------------------------------------------------------------
function OnClickEditFilter(Object)

  m_simpleTV.User.ToolsAddon.ExtFilterName = m_simpleTV.Dialog.GetComboValue_UTF8(Object,'ExtFilterList')
 
  m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'FilterTable', '')

  filter = m_simpleTV.User.ToolsAddon.FilterTable
  if filter == nil then return end

  local out = ''
  for i=1,#filter do

out = out .. 
'      <tr class="row">\n' ..
'        <td class="hide" col="channelId">' .. i .. '</td>\n' ..
'        <td>\n' ..
'          <input name="checkbox" id="Check' .. i .. '" type="checkbox">\n' ..
'        </td>\n' ..
'        <td>\n' ..
'          <div id="oldname' .. i .. '" class="editable" contenteditable="true" col="oldname">' .. filter[i][1] .. '</div>\n' ..          
'        </td>\n' ..
'        <td>\n' ..
'          <div class="editable" id="newname' .. i .. '" contenteditable="true" col="newname">' .. filter[i][2] .. '</div>\n' ..
'        </td>\n' ..
'        <td>\n' ..
'          <div class="editable" id="grpname' .. i .. '" contenteditable="true" col="groupname">' .. filter[i][3] .. '</div>\n' ..
'        </td>\n' ..
'        <td>\n' .. 
'          <div class="editable" contenteditable="true" col="sourcename">' .. filter[i][4] .. '</div>\n' ..
'        </td>\n' ..
'      </tr>\n' 
  end
out = 
'<div id="filtertable">\n' ..
'<table>\n' ..
'  <tr>\n' ..
'    <td width="200"><h3>Filter <span id="filtercount" style="color:#47D1FF;font-size:12px;"></span></h3></td>\n' ..
'    <td width="80">Search in table</td>\n' ..
'    <td><input type="text" style="width: 200px;" id="search"/></td>\n' ..
'  </tr>\n' ..
'</table>\n' ..
--'<h3>Filter <span id="filtercount" style="color:#47D1FF;font-size:12px;"></span></h3>\n' ..
'  <table class="sort" id="filter">\n' ..
'    <thead>\n' ..
'      <tr>\n' ..
'        <th class="hide">#</th>\n' ..
'        <th width="22"><input name="checkbox" id="CheckAll" type="checkbox" onclick="CheckAll(this)"></th>\n' ..
'        <th>Current Name</th>\n' ..
'        <th>New Name</th>\n' ..
'        <th>Group</th>\n' ..
'        <th>Source</th>\n' ..
'      </tr>\n' ..
'    </thead>\n' ..
'    <tbody>\n' .. out ..
'  </table>\n' ..
'</div>' ..
'<br><center><a class="totop" onclick="JumpTop();return false;" href="#">JUMP TO TOP</a></center>'

local head =
'<!DOCTYPE html>\n' .. 
'<head>\n' .. 
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n' .. 
'<meta http-equiv="X-UA-Compatible" content="IE=10">\n' .. 
'<link rel="stylesheet" href="css/tool.css" />\n' .. 
'<script type="text/javascript" src="misc/jquery.min.js"></script>\n' .. 
'<script type="text/javascript" src="misc/jquery.checkboxes-1.0.6.min.js"></script>\n' .. 
'<script type="text/javascript" src="misc/jquery.ordertable.min.js"></script>\n' .. 
'<style>\n' ..
'body {background-color:#FFFFFF;}\n' ..
'</style>\n' ..
'</head>\n' .. 
'<body>\n' ..
"<script>$(function() {$('#filter').checkboxes('range', true);   $('#filter').orderTable({excludeColumns:[0,1]});   $('[contenteditable=true]').bind('paste',function(t){var a='',i=$(this);return t.clipboardData?a=t.clipboardData.getData('text/plain'):window.clipboardData?a=window.clipboardData.getData('Text'):t.originalEvent.clipboardData&&(a=$('<div></div>').text(t.originalEvent.clipboardData.getData('text'))),document.queryCommandSupported('insertText')?(document.execCommand('insertHTML',!1,$(a).html()),!1):(i.find('*').each(function(){$(this).addClass('within')}),void setTimeout(function(){i.find('*').each(function(){$(this).not('.within').contents().unwrap()})},1))});  var count = 'Records: ' + $('#filter tr').not('thead tr').length; $('#filtercount').html(count);});</script>\n\n" ..
'<script>function searchTable(e){var n=$("#filter");n.find("tr").each(function(n,t){var i=$(t).find("td");if(i.length>0){var a=!1;i.each(function(n,t){var i=new RegExp(e,"i");return i.test($(t).text())?(a=!0,!1):void 0}),1==a?$(t).show():$(t).hide()}})}$(function(){$("#search").keyup(function(){searchTable($(this).val())})});</script>\n\n'

local footer = 
'<script>function CheckAll(e){checkboxes=document.getElementsByName("checkbox");for(var c=0,n=checkboxes.length;n>c;c++)checkboxes[c].checked=e.checked} function JumpTop() { document.body.scrollTop = document.documentElement.scrollTop = 0;};</script>\n' ..
'</body>\n' .. 
'</html>'

out = head .. out .. footer

  local fhandle = io.open (m_simpleTV.MainScriptDir .. "user/Tools/EditFllter.html" , "w+")
  if fhandle==nil then return end
  fhandle:write(out)
  fhandle:close()

  m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'FilterTable', '<iframe id="framefilter" src="EditFllter.html" width="750" height="350" frameborder="0" onload="framefilteronload()"><p>Your browser does not support iframes.</p></iframe>')

end
-------------------------------------------------------------------------------
function OnClickSaveFilterChanges(Object,filter)
--debug_in_file(filter  .. '\n\n')
 -- local filter = m_simpleTV.Dialog.GetElementHtml_UTF8(Object,'ChannelsTable')
  if filter == nil or not string.match(filter,'id="filter"') then return end

   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'MessEditFilter', '')

 filter = string.gsub(filter,'&nbsp;','' )

 local out = ''
 for w in string.gmatch(filter,'<tr class="row">(.-)</tr>') do

  local CurrentName = string.match(w,'col="oldname">(.-)<')
  local NewName = string.match(w,'col="newname">(.-)<')
  local GroupName = string.match(w,'col="groupname">(.-)<')
  local Source = string.match(w,'col="sourcename">(.-)<')

    if CurrentName ~= nil and NewName ~= nil and GroupName ~= nil and Source ~= nil then

       if trim(GroupName) == '!No Group' and (trim(CurrentName) or trim(NewName) == '' or trim(GroupName) == '' or trim(Source) == '') then
            m_simpleTV.Dialog.SetElementText(Object, 'MessEditFilter', "Detected  an empty cells and !No Group in Group column. Aborted.")
          m_simpleTV.Common.Wait(3000) 
          m_simpleTV.Dialog.SetElementText_UTF8(Object, 'MessEditFilter', '')
          return 
      end
      if trim(CurrentName) == '' or trim(NewName) == '' or trim(GroupName) == '' or trim(Source) == '' then
            m_simpleTV.Dialog.SetElementText(Object, 'MessEditFilter', 'Detected an empty cells. Aborted.')      
          m_simpleTV.Common.Wait(3000) 
          m_simpleTV.Dialog.SetElementText_UTF8(Object, 'MessEditFilter', '')
          return 
      end
       if trim(GroupName) == '!No Group' then
            m_simpleTV.Dialog.SetElementText(Object, 'MessEditFilter', "Detected !No Group in Group column. Aborted.") 
          m_simpleTV.Common.Wait(3000) 
          m_simpleTV.Dialog.SetElementText_UTF8(Object, 'MessEditFilter', '')
          return 
      end

          CurrentName = String2Upper(CurrentName)
          out = out .. '"' .. trim(CurrentName)  .. ',' .. trim(NewName) .. ',' .. trim(GroupName) .. ',' .. trim(Source) ..'"\n'
     
     end
end

local str = 
'--filter list utf-8  on ' .. os.date("%d.%m.%Y %X") .. '\n' .. 
'--current channel name allways in uppercase, new name, group name, epg source name\n\n'

  str = m_simpleTV.Common.string_toUTF8(str)

  local PathToFilterFile = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'PathToFilterFile')

  local fhandle = io.open (PathToFilterFile , "w+")
  if fhandle==nil then return end
  fhandle:write(str .. out)
  fhandle:close()

 if FileExists(PathToFilterFile) then
     m_simpleTV.User.ToolsAddon.FilterTable = nil
     m_simpleTV.User.ToolsAddon.FilterTable = GetFilterTable(out)
     m_simpleTV.Interface.MessageBox('Filter saved successfully.','Tools add-on - Save Filter Changes',0,Object)
    else
     m_simpleTV.Interface.MessageBox('Error - Filter cannot be saved.','Tools add-on - Save Filter Changes',0,Object)
 end

end
-------------------------------------------------------------------------------
function OnClickDebugTable(Object)

--local out = m_simpleTV.Dialog.GetElementHtml_UTF8(Object,'ChannelsTable')
--local out = m_simpleTV.Dialog.GetElementHtml_UTF8(Object,'FilterTable')
--local out = m_simpleTV.Dialog.GetElementHtml_UTF8(Object,'TVSTable')
--debug_in_file(out  .. '\n\n')

end
-------------------------------------------------------------------------------

function JSCallBack1(Object,param_utf8)
   local out =  param_utf8
--debug_in_file(out  .. '\n')
end

-------------------------------------------------------------------------------
function OnClickDefaultSettings(Object)

local value
--Set default settings

  m_simpleTV.User.ToolsAddon.FilterTable = nil

  local ini = io.open(m_simpleTV.MainScriptDir .. "user/Tools/tools.ini",'w+')
  if ini == nil then return end

  local DefFilterPath =  m_simpleTV.MainScriptDir .. "user\\Tools\\default\\filter.txt"
  local DefGrp = m_simpleTV.MainScriptDir .. "user\\Tools\\default\\groups.txt"

  local str = 'PathToFilterFile=' .. DefFilterPath ..';\n' .. 'PathToGroupFile=' .. DefGrp  ..';\n' .. 'EnableFilter=1;\n'
  ini:write(str)
  ini:close()

  m_simpleTV.Dialog.SetElementText(Object, 'Mess', '')
  m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Groups', '')

 local t = {}
 t.day,t.month,t.year,t.hour,t.min,t.sec = string.match(os.date("%d.%m.%Y %X"),"(%d*).(%d*).(%d*) (%d*):(%d*):(%d*)")
  local date = t.year .. t.month .. t.day.. '_' .. t.hour .. t.min .. t.sec

  if FileExists(DefFilterPath) then
   os.rename(DefFilterPath, m_simpleTV.MainScriptDir .. "user\\Tools\\default\\filter_" .. date ..".bak")
  end

  local fhandle = io.open(m_simpleTV.MainScriptDir .. "user/Tools/default/filter.default")
  if fhandle == nil then return end
  local filter_default = fhandle:read("*all")
  fhandle:close()

  local DefFilter =  io.open(DefFilterPath,"w+")
  if DefFilter == nil then return end
  DefFilter:write(filter_default)
  DefFilter:close()

   local FilePath = m_simpleTV.Common.string_fromUTF8(DefFilterPath)
   local fhandle = io.open(FilePath, 'r')

   FilePath = m_simpleTV.Common.string_fromUTF8(DefGrp)
   local groups = io.open(FilePath, 'r')

    if fhandle == nil and groups == nil then m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'Mess', 'Filter and Group  files not found') return end

   if fhandle == nil then 
     m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'Mess', 'Filter file not found') 
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'PathToGroupFile', DefGrp)
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'PathToFilterFile', '')

     for line in groups:lines() do
      m_simpleTV.Dialog.AddComboValue_UTF8(Object,'Groups',line,-1)  
     end
     groups:close()
     m_simpleTV.Dialog.SelectComboIndex(Object,'Groups',0)
       return 
   end

  if groups == nil then 
     m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'Mess', 'Group file not found') 
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'PathToFilterFile', DefFilter)
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'PathToGroupFile', '')
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'Groups', '')
     m_simpleTV.Dialog.SetCheckBoxValue(Object,'FilterFile',1)

     value = fhandle:read("*all")
     fhandle:close()
     m_simpleTV.User.ToolsAddon.FilterTable = GetFilterTable(value)
      return 
  end

     value = fhandle:read("*all")
     fhandle:close()
     m_simpleTV.User.ToolsAddon.FilterTable = GetFilterTable(value)

     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'PathToFilterFile', DefFilterPath)
     m_simpleTV.Dialog.SetCheckBoxValue(Object,'FilterFile',1)
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'PathToGroupFile', DefGrp)

     for line in groups:lines() do
      m_simpleTV.Dialog.AddComboValue_UTF8(Object,'Groups',line,-1)  
     end
     groups:close()
    m_simpleTV.Dialog.SelectComboIndex(Object,'Groups',0)

   OnClickExtFilterRefresh(Object)

end
----------------------------------------------------------------------
function JSCallBack2(Object,param1,param2)

local value
 if  param1 == 'ReadFile1' then
   if param2 ~=nil then
     local FilePath = m_simpleTV.Common.string_fromUTF8(param2)
     local fhandle = io.open(FilePath, 'r')
     value = fhandle:read("*all")
     fhandle:close()
   end
    m_simpleTV.Dialog.SetElementText_UTF8(Object, 'inText', value) 

  elseif param1 == 'ReadFile2' then
   
    m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'Mess', '')
    m_simpleTV.User.ToolsAddon.FilterTable = nil
    m_simpleTV.Dialog.SetCheckBoxValue(Object,'FilterFile',1)

   if param2 ~=nil then

     local FilePath = m_simpleTV.Common.string_fromUTF8(param2)
     local fhandle = io.open(FilePath, 'r')
     value = fhandle:read("*all")
     fhandle:close()
--debug_in_file(value)
     m_simpleTV.User.ToolsAddon.FilterTable = nil
     m_simpleTV.User.ToolsAddon.FilterTable = GetFilterTable(value)
   end

  elseif param1 == 'ReadFile3' then

    m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'Mess', '')
    m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'Groups', '')

   if param2 ~=nil then
     local FilePath = m_simpleTV.Common.string_fromUTF8(param2)
     local groups = io.open(FilePath, 'r')
     for line in groups:lines() do
      m_simpleTV.Dialog.AddComboValue_UTF8(Object,'Groups',line,-1)  
     end
     groups:close()
    m_simpleTV.Dialog.SelectComboIndex(Object,'Groups',0)
   end

  elseif param1 == 'ReadFile4' then
   if param2 ~=nil then
     local FilePath = m_simpleTV.Common.string_fromUTF8(param2)
     local fhandle = io.open(FilePath, 'r')
     value = fhandle:read("*all")
     fhandle:close()
   end
     if string.match(value,'local ch_filter') then
        m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSChannelFilterStatus', '<div style="color:green;">File is found</div>') 
        m_simpleTV.Dialog.SetElementValueString(Object,'TVSChannelFilterValue',param2) 
       else   
        m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSChannelFilterStatus', '<div style="color:red;">Incorrect file</div>')
        m_simpleTV.Dialog.SetElementValueString(Object,'TVSChannelFilterValue','') 
     end

  elseif param1 == 'ReadFile5' then
   if param2 ~=nil then
     local FilePath = m_simpleTV.Common.string_fromUTF8(param2)
     local fhandle = io.open(FilePath, 'r')
     value = fhandle:read("*all")
     fhandle:close()
   end
     if string.match(value,'local gr_filter') then
        m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSGroupFilterStatus', '<div style="color:green;">File is found</div>') 
        m_simpleTV.Dialog.SetElementValueString(Object,'TVSGroupFilterValue',param2) 
      else 
        m_simpleTV.Dialog.SetElementHtml_UTF8(Object, 'TVSGroupFilterStatus', '<div style="color:red;">Incorrect file</div>')
        m_simpleTV.Dialog.SetElementValueString(Object,'TVSGroupFilterValue','') 
     end
  elseif param1 == 'FilterTable' then
   if param2 ~=nil then
       OnClickSaveFilterChanges(Object,param2)
   end

  elseif param1 == 'ChannelsTableAddFilter' then
   if param2 ~=nil then
       OnClickAppendToFilterFile(Object,param2)
   end

  elseif param1 == 'ChannelsTableNewFilter' then
   if param2 ~=nil then
       m_simpleTV.User.ToolsAddon.NewFilter = param2
       OnClickSaveNewFilterFile(Object,param2)
   end

  elseif param1 == 'ChannelsTableUpdate' then
   if param2 ~=nil then
       OnClickUpdateExtFilterChannels(Object,param2)
   end

  elseif param1 == 'SaveTVSTable' then
   if param2 ~=nil then
       OnClickSaveTVSFilter(Object,param2)
   end


  end
     
end
------------------------------------------------------------------
------------------------------------------------------------------
--Main tools
local err = 'Incorrect data'

function OnClickButtonClear(Object)
  m_simpleTV.Dialog.SetElementText(Object, 'inText', '')
end

function OnClickButtonClearProxy(Object)
  m_simpleTV.Dialog.SetElementText(Object, 'prxy', '')
end

function OnClickButtonClearAll(Object)
  m_simpleTV.Dialog.SetElementText(Object, 'inText', '')
  m_simpleTV.Dialog.SetElementText(Object, 'outText', '')
  m_simpleTV.Dialog.SetElementText(Object, 'prxy', 'http://192.168.0.1:1234')
end

function OnClickHelpButton(Object)
local Object4 =  m_simpleTV.Dialog.FindWindowById( 'tools_window_4' )
if  Object4 ~=nil then  
     m_simpleTV.Dialog.SetForegroundWindow(Object4)
    return
end
local Object4 = m_simpleTV.Dialog.Show('Help',m_simpleTV.MainScriptDir .. 'user\\Tools\\Help.html','user\\Tools\\Help.lua',800,600,1+4+8+16+32+512+1024)
m_simpleTV.Dialog.SetWindowId(Object4,'tools_window_4') 
end
-------------------------------------------------------------------
function OnClickButtonM3U(Object)
 local prxy = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'prxy')
 local value = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'inText')
 if value ~= '' then

	if not string.match(value,'#EXTM3U') and not string.match(value,'#EXTINF') then 
	   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', err)  	 
	    return 
 	end
 
local  tmpName = m_simpleTV.Common.GetTmpName()
if tmpName == nil then return end 

 local tfile = io.open(tmpName,'w+')
 if tfile == nil then 
     os.remove(tmpName)
     return
 end
if string.match(value,'^#EXTM3U') == nil then  
 tfile:write('#EXTM3U\n')
  else
 tfile:write('')
end
 tfile:close() 

value = string.gsub(value,'^#',' #')
for w in string.gmatch(value,'%s+[^\r\n]+') do 
 if w == nil then break end
 w = trim(w)
 tfile = io.open(tmpName,'a+')
 tfile:write(w..'\n')
 tfile:close()
end

tfile = io.open(tmpName, 'r')
value = tfile:read("*all")
tfile:close()
  if prxy ~= '' then
	if string.match (value, 'udp://') then
 	  value = string.gsub(value, '%@', '')
 	  value = string.gsub(value, 'udp://', prxy..'/udp/')
   	  value = trim(value)
	end
      else
     value = trim(value)
  end

 m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', value)  	 
 os.remove(tmpName)  
 end

end
------------------------------------------------------------------
function OnClickButtonRTMP(Object)
 local value = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'inText')
 if value ~= '' then
	value = trim(value)
	if not string.match(value,'^rtmp:') and not string.match(value,'^rtmpe:') and not string.match(value,'^url:') then 
	   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', err)  	 
	    return 
 	end
local  tmpName = m_simpleTV.Common.GetTmpName()
if tmpName == nil then return end 

 local tfile = io.open(tmpName,'w+')
 if tfile == nil then 
     os.remove(tmpName)
     return
 end
 tfile:write('')
 tfile:close()

if string.match(value,'^rtmp') then

 value = string.gsub(value,'rtmp:','rtmp://$OPT:rtmp-raw=rtmp:')
 value = string.gsub(value,'rtmpe:','rtmp://$OPT:rtmp-raw=rtmpe:')
 value = string.gsub(value,'<playpath>',' playpath=')
 value = string.gsub(value,'<swfUrl>','swfUrl=')
 value = string.gsub(value,'<pageUrl>','pageUrl=')
      tfile = io.open(tmpName,'a+')
      tfile:write(value)
      tfile:close()

  elseif string.match(value,'^url:') then

   value = string.gsub(value, '$','\r\n')
   for rtmp,pageUrl,swfUrl,playpath  in string.gmatch(value,'url: (.-)\r\n.-pageUrl: (.-)\r\nswfUrl: (.-)\r\n.-playPath: (.-)\r\n') do 
    if rtmp == nil or pageUrl == nil or swfUrl == nil or playpath == nil then break end
    value = 'rtmp://$OPT:rtmp-raw=' .. rtmp .. ' playpath=' .. playpath .. ' swfUrl=' .. swfUrl .. ' pageUrl=' .. pageUrl
--debug_in_file(value ..'\n\n')
      tfile = io.open(tmpName,'a+')
      tfile:write(value..'\n\n')
      tfile:close()
   end
end
     tfile = io.open(tmpName, 'r')
     value = tfile:read("*all")
     tfile:close()
     value = trim(value)
     m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', value)  
     os.remove(tmpName)	 
 end
end
----------------------------------------------------------------------
function OnClickButtonXSPF(Object)
 local value = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'inText')
 local prxy = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'prxy')
  --   m_simpleTV.Dialog.SetElementText(Object, 'outText', prxy)  

 if value ~= '' then
	value = trim(value)
	if not string.match(value,'<trackList>') then 
	   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', err)  	 
	    return 
 	end
local  tmpName = m_simpleTV.Common.GetTmpName()
if tmpName == nil then return end 

 local tfile = io.open(tmpName,'w+')
 if tfile == nil then 
     os.remove(tmpName)
     return
 end
 tfile:write('#EXTM3U\n')
 tfile:close()

for w in string.gmatch(value,'<track>(.-)</track>') do 
  local url = string.match(w,'<location>(.-)</location>')
  local name = string.match(w,'<title>(.-)</title>')
 if url == nil or name == nil  then break end
 local tout = '#EXTINF:-1,' .. name .. '\n' .. url .. '\n'
 tfile = io.open(tmpName,'a+')
 tfile:write(tout)
 tfile:close()
end
     tfile = io.open(tmpName, 'r')
     value = tfile:read("*all")
     tfile:close()
  if prxy ~= '' then
	if string.match (value, 'udp://') then
 	  value = string.gsub(value, '%@', '')
 	  value = string.gsub(value, 'udp://', prxy..'/udp/')
   	  value = trim(value)
	end
      else
     value = trim(value)
  end
    m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', value)  
     os.remove(tmpName)
 end

end
----------------------------------------------------------------------
function OnClickButtonRDup(Object)

 local value = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'inText')

 if value ~= '' then

	if not string.match(value,'#EXTM3U') and not string.match(value,'#EXTINF') then 
	   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', err)  	 
	    return 
 	end

local  tmpName = m_simpleTV.Common.GetTmpName()
if tmpName == nil then return end 

 local tfile = io.open(tmpName,'w+')
 if tfile == nil then 
     os.remove(tmpName)
     return
 end

local t={}
local hash={}
value = string.gsub(value,'^#',' #')
for w in string.gmatch(value,'%s+[^\r\n]+') do 
 if w == nil then break end
 w = trim(w)
 table.insert(t,w..'\n')
end

for _,v in ipairs(t) do
   if not hash[v] then
       hash[v] = true
 tfile = io.open(tmpName,'a+')
 tfile:write(v)
 tfile:close()
--debug_in_file(v)
   end
end
     tfile = io.open(tmpName, 'r')
     value = tfile:read("*all")
     tfile:close()
    value = trim(value)
    m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', value)  

 end
end
----------------------------------------------------------------------
function OnClickButtonXML(Object)
 local value = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'inText')

 if value ~= '' then
	value = trim(value)
	if not string.match(value,'<channel>') and not string.match(value,'<item>') and not string.match(value,'<subitem>')  then 
	   m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', err)  	 
	    return 
 	end
local  tmpName = m_simpleTV.Common.GetTmpName()
if tmpName == nil then return end 

 local tfile = io.open(tmpName,'w+')
 if tfile == nil then 
     os.remove(tmpName)
     return
 end
 tfile:write('#EXTM3U\n')
 tfile:close()
if string.match(value,'<item>') or string.match(value,'<subitem>') ~=nil then
value = string.gsub(value,'<subitem>','<item>')
value = string.gsub(value,'</subitem>','</item>')

for w in string.gmatch(value,'<item>(.-)</item>') do 
 w = string.gsub(w,'<%!%[CDATA%[','')
 w = string.gsub(w,'%]%]>','')
  local url = string.match(w,'<link>(.-)</link>')
  local name = string.match(w,'<title>(.-)</title>')
   url = string.gsub(url,'rtmp:','rtmp://$OPT:rtmp-raw=rtmp:')
   url = string.gsub(url,'rtmpe:','rtmp://$OPT:rtmp-raw=rtmpe:')
 if name == nil or url == nil then break end
 local tout = '#EXTINF:-1,' .. trim(name) .. '\n' .. trim(url) .. '\n'
 tfile = io.open(tmpName,'a+')
 tfile:write(tout)
 tfile:close()
 end

else

for w in string.gmatch(value,'<channel>(.-)</channel>') do 
 w = string.gsub(w,'<%!%[CDATA%[','')
 w = string.gsub(w,'%]%]>','')
  local url = string.match(w,'<stream_url>(.-)</stream_url>')
  local name = string.match(w,'<title>(.-)</title>')
 if url == nil then url = string.match(w,'<playlist_url>(.-)</playlist_url>') end
 if name == nil or url == nil then break end
 local tout = '#EXTINF:-1,' .. trim(name) .. '\n' .. trim(url) .. '\n'
 tfile = io.open(tmpName,'a+')
 tfile:write(tout)
 tfile:close()
 end
end
     tfile = io.open(tmpName, 'r')
     value = tfile:read("*all")
     tfile:close()
     value = trim(value)
  
    m_simpleTV.Dialog.SetElementText_UTF8(Object, 'outText', value)  
     os.remove(tmpName)
 end
end
----------------------------------------------------------------------
function OnClickButtonLoadPls(Object)
local value = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'outText')
if value ~= '' then
local Object2 = m_simpleTV.Dialog.Show('Load playlist',m_simpleTV.MainScriptDir .. 'user\\Tools\\LoadPls.html','user\\Tools\\LoadPls.lua',350,250,1+8+32,Object)  
 end
end
----------------------------------------------------------------------
function OnClickButtonSavePls(Object)
local value = m_simpleTV.Dialog.GetElementValueString_UTF8(Object,'outText')
if value ~= '' then
local Object3 = m_simpleTV.Dialog.Show('Save playlist',m_simpleTV.MainScriptDir .. 'user\\Tools\\SavePls.html','user\\Tools\\SavePls.lua',350,250,1+32,Object)  
 end
end
----------------------------------------------------------------------
function OnClickCloseButton(Object)

  m_simpleTV.User.ToolsAddon.ExtFilterName = nil
  m_simpleTV.User.ToolsAddon.FilterFileValue = nil
  m_simpleTV.Dialog.Close(Object)
end

----------------------------------------------------------------------

function OnOk(Object) 
 end
