var TreeFile = "js/new_tree_script.txt";
var onclicked;
var items=13;
var TmpStr_0, TmpStr_1, LastIndex;
var maxDepth=0;
var imgdown="style/new_tree_icon/btn_item_p.png";
var imgright="style/new_tree_icon/arrow_right2.png";
var opened;
var sgWin;


function modifyTree(scriptText)
{
  //get support check
  var ivs = SendCGICMD("/cgi-bin/view/param?action=list&Group=Properties.IVS");
  var system_ivs_support = GetQueryVariableEx2("root.Properties.IVS.IVSSupport", ivs);
  GetDeviceInfo('IVS.License',"view");
  var tamperingmatch = GetQueryVariable('IVS.License.PEA');
  var tripwirematch = GetQueryVariable('IVS.License.PEA');
  var perimetermatch = GetQueryVariable('IVS.License.PEA');
  var peoplecountmatch = GetQueryVariable('IVS.License.CPC');
  var crowddensitymatch = GetQueryVariable('IVS.License.CDD');

  if(LED == "no")
  {
    scriptText = scriptText.replace("|-L_LED,item,system_led.htm,mainFrame\n","");
  }
  if(MemoryCard == "no")
  {
    scriptText = scriptText.replace("|-L_LocalStorage,item,playback_local.htm,mainFrame\n","");
  }
  if(DISupport=="no"&&DOSupport=="no") 
  {
    scriptText = scriptText.replace("|-L_DigitalIO,item,system_DiDo.htm,mainFrame\n","");
  }

  if(AudioSupport == "no")
  {
    scriptText = scriptText.replace("|-L_Audio,item,basic_audio_set.htm,mainFrame\n",""); //Basic
    scriptText = scriptText.replace("|-L_Audio,item,basic_audio_set.htm,mainFrame\n",""); //Live View
    scriptText = scriptText.replace("|-L_AudioDetection,item,event_audio.htm,mainFrame\n","");
  }

  if(PTZEnabled == "no" )
  {
    scriptText = scriptText.replace("|-L_PTZSetting,item,liveview_ptz_area.htm,mainFrame\n","");
  }
    
  if(OpenVPN=="no")
  {
    scriptText = scriptText.replace("|-L_CamDrive,item,network_vpn.htm,mainFrame\n","");
  }
  if(MemoryCard == "no")
  {
    scriptText = scriptText.replace("|-L_EdgeRecord,item,recording_list.htm,mainFrame\n","");
  }

  if(AudioDetection=="no")
  {
    scriptText = scriptText.replace("|-L_AudioDetection,item,event_audio.htm,mainFrame\n","");
  }  
//  if(TempTag=="no")
//  {
    scriptText = scriptText.replace("|-L_PoE,item,system_PoE.htm,mainFrame\n","");
//  }
  if(system_ivs_support == "no" || system_ivs_support == "" || IVSSupport == "no")
  {
    scriptText = scriptText.replace("-L_IVS,folder,ivs_setting.htm,mainFrame\n","");
    scriptText = scriptText.replace("|-L_License,item,ivs_setting.htm,mainFrame\n","");
    scriptText = scriptText.replace("|-L_TamperingDetection,item,ivs_tampering.htm,mainFrame\n","");
    scriptText = scriptText.replace("|-L_Tripwire_Detection,item,ivs_tripwire.htm,mainFrame\n","");
    scriptText = scriptText.replace("|-L_Perimeter_Detection,item,ivs_perimeter.htm,mainFrame\n","");
    scriptText = scriptText.replace("|-L_People_Counting,item,ivs_peoplecount.htm,mainFrame\n","");
    scriptText = scriptText.replace("|-L_People_Density,item,ivs_density.htm,mainFrame\n","");
  }
  else
  {
    if(TamperingSupport == "no" || tamperingmatch == "NotMatch" || tamperingmatch == "None")
    {
      scriptText = scriptText.replace("|-L_TamperingDetection,item,ivs_tampering.htm,mainFrame\n","");
    }
    if(TripwireSupport == "no" || tripwirematch == "NotMatch" || tripwirematch == "None")
    {
      scriptText = scriptText.replace("|-L_Tripwire_Detection,item,ivs_tripwire.htm,mainFrame\n","");
    }
    if(PerimeterSupport == "no" || perimetermatch == "NotMatch" || perimetermatch == "None")
    {
      scriptText = scriptText.replace("|-L_Perimeter_Detection,item,ivs_perimeter.htm,mainFrame\n","");
    }
    if(PeopleCountingSupport == "no" || peoplecountmatch == "NotMatch" || peoplecountmatch == "None")
    {
      scriptText = scriptText.replace("|-L_People_Counting,item,ivs_peoplecount.htm,mainFrame\n","");
    }
    if(PeopleDensitySupport == "no" || crowddensitymatch == "NotMatch" || crowddensitymatch == "None")
    {
      scriptText = scriptText.replace("|-L_People_Density,item,ivs_density.htm,mainFrame\n","");
    }
  }  

  if(Lenstype != "fisheye")
  {
    scriptText = scriptText.replace("|-L_Fisheye_Setting,item,liveview_fisheye_area.htm,mainFrame\n","");
  }
  
  return scriptText;
}
function onMouseTDOver(id,cur) 
{
   cur.className = "mouseover";
   if(document.getElementById('img'+id)!=null)
   {
     var imgsrc = document.getElementById('img'+id).src;
     imgsrc = imgsrc.replace("2.png","1.png");
     document.getElementById('img'+id).src = imgsrc;
   }
}

function onMouseTDOut(id,cur) 
{
  if(id==onclicked) {
    cur.className = "selected";
    if(document.getElementById('item'+id)!=null){
      document.getElementById('item'+id).className = "selectedTD";  
    }
  }
  else {
    cur.className = "item";
    if(document.getElementById('item'+id)!=null){
      document.getElementById('item'+id).className = "";
    }
  }
  if(document.getElementById('img'+id)!=null)
  {
    var imgsrc = document.getElementById('img'+id).src;
    imgsrc = imgsrc.replace("1.png","2.png"); 
    document.getElementById('img'+id).src = imgsrc;
  }
}

function onTDClick(start,end,cur, target,linkpath)
{
  var i;
  var depth, curDepth = TmpStr_0[start].search("-");
  var TmpStr = new Array;

  if(getType(start)=="folder") {
      closeAllItemWithMask(start,end,curDepth);
      if(document.getElementById('img'+start)!=null){
        if(opened[start]) {
          document.getElementById('img'+start).src=imgright.replace("2.png","1.png");
          opened[start]=false;
        } else {
          document.getElementById('img'+start).src=imgdown.replace("2.png","1.png");
          opened[start]=true;
        }
      }
      var j = start+1;
      for(j;j<=end; j++)
      {
          depth = TmpStr_0[j].search("-");
          if(depth>curDepth){
            if((document.getElementById('layer'+j).style.display=='none')&&(depth==curDepth+1)){
              var ie = (typeof window.ActiveXObject != 'undefined');
              if(ie && getOs() != "IE10"){
                document.getElementById('layer'+j).style.display='block'; 
              }else{
                document.getElementById('layer'+j).style.display='table-row';
                document.getElementById('layer'+j).style.cursor='pointer';
              }
            } else {
              document.getElementById('layer'+j).style.display='none';
            }
          }
          if(document.getElementById('img'+j)!=null)
              document.getElementById('img'+j).src=imgright;
          opened[j]=false;
      }
  }
  for(i=0; i<items; i++) 
  {
    if(i == start) {
      if(document.getElementById('item'+i)!=null)
        document.getElementById('item'+i).className = "selectedTD";
    }else {
      if(document.getElementById('layer'+i)!=null)
        document.getElementById('layer'+i).className = "item";
      if(document.getElementById('item'+i)!=null)
        document.getElementById('item'+i).className = "";
    }
  }
  
  if(opened[start]==true)
  {
     //search select item
     for(i=eval(start+1); i<=end; i++)
     {
       if(TmpStr_0[i].indexOf(linkpath) >= 0)
       {
         TmpStr = TmpStr_0[i].replace(/[-| ]/g,"").split(",");
         onTDClick(i,i,EID("item"+i), TmpStr[3],linkpath);
         return;
       }
     }
  }

  linkpath += "?stamp=" + fwDate;

  if(target!=null){
      if(target=='_top')
        document.getElementById("setPage").src = linkpath;
      else if(target=='_self')
        document.getElementById("setPage").src = linkpath;
      else if(target=='_parent'){
        // for ABus
        document.getElementById("setPage").src = linkpath;
      }else if(target=='_blank')
        window.location=linkpath;
      else if(target=='_new') {
        sgWin = window.open(linkpath , "win2");
        this.focus();
      }else{
        // for ABus
        document.getElementById("setPage").src = linkpath;
      }
  }
  onclicked=start;
}
function onDownloadDone(scriptText){
  scriptText = modifyTree(scriptText);
  TmpStr_0 = scriptText.replace(/^[\s]+/g,"").replace(/[\s]+$/g,"").split("\n");
  items = TmpStr_0.length;
  initTree();
}

var ivspagestart;
var ivspageend;
var didopagestart;
var didopageend;
var systemfoldersstart;
var systemfolderend;
function initTree()
{
  var i, grupEnd;
  var TempHTML;
  var depth;
  var maxWidth=150;
  opened = new Array;
  for(i=0; i<items; i++) {
    depth = TmpStr_0[i].search("-");
    opened[i]=false;
    if(depth>maxDepth)
    maxDepth = depth;
  }
  maxDepth++;

  if(DetectMobile())
  {
    maxWidth = 10*maxDepth+133;
  }
  else
  {
    maxWidth = 10*maxDepth+130;
  }
  TempHTML="<table border=\"0\" width=\""+maxWidth+"\" cellpadding=\"0\" cellspacing=\"0\">";
  TempHTML+=BuildTree(0,items);
  TempHTML+=genTableHeader(maxDepth);
  TempHTML+="</table>";
  document.getElementById('TreeTmp').innerHTML = TempHTML;

  if(getCookies("upload") == "yes")
  {
    setCookies("upload", "no");
    onTDClick(ivspagestart,ivspageend,this,'mainFrame','ivs_setting.htm');
  }

  if(getCookies("page") == "dido")
  {
    if(getOs().indexOf("IE") >= 0 && (getOs() != "IE11+"))
    {
      setCookies("page", "none");
    }
    //folder
    onTDClick(systemfoldersstart,systemfolderend,"none",'mainFrame','system_maintenance.htm');
    //page
    onTDClick(didopagestart,didopageend,"none",'mainFrame','system_DiDo.htm');
  }

}
function BuildTree(Tree_S,Tree_E){
      var i, grupEnd;
  var TempHTML="";
  var NodeType, NodeName, NodeLink, NodeTarget;
  var TmpStr = new Array;
  var depth;
  
  for(i=Tree_S; i<Tree_E; i++) {
    TmpStr = TmpStr_0[i].replace(/[-| ]/g,"").split(",");
    NodeName = TmpStr[0];
    NodeType = TmpStr[1];
    NodeLink = TmpStr[2];
    NodeTarget = TmpStr[3];
    depth = TmpStr_0[i].search("-");
    
    if(NodeName == "L_IVS")
    {
      ivspagestart = i; 
      ivspageend = findNextFolder(i,Tree_E);
    }
    else if(NodeName == "L_System")
    {
      systemfoldersstart = i;
      systemfolderend = findNextFolder(i,Tree_E);
    }
    else if(NodeName == "L_DigitalIO")
    {
      didopagestart = i;
      didopageend = i;
    }
    if(NodeType=="folder") 
    {
      grupEnd = findNextFolder(i,Tree_E);
      TempHTML+=genFolder(i,grupEnd,NodeName,NodeLink,NodeTarget,depth,maxDepth); 
    } else if(NodeType=="blockFrame") {
      //For ABus .Because genItem() default style is none. So I need create a new function and set default style is block. 
      TempHTML+=genBlockItem(i,NodeName,NodeLink,NodeTarget,depth,maxDepth); 
    } else {
      TempHTML+=genItem(i,NodeName,NodeLink,NodeTarget,depth,maxDepth); 
    }
  }
  return TempHTML;
}
function findNextFolder(Tree_S,Tree_E)
{
  var NodeType, NodeName, NodeLink, NodeTarget;
  var cntDepth = TmpStr_0[Tree_S].search("-");
  var depth;
  var TmpStr = new Array;
  for(i=Tree_S+1; i<Tree_E; i++) {
    //parse String
    TmpStr_1 = TmpStr_0[i].split(",");
    NodeName = TmpStr_1[0];
    NodeType = TmpStr_1[1];
    NodeLink = TmpStr_1[2];
    NodeTarget = TmpStr_1[3];
    depth = TmpStr_0[i].search("-");
    if(depth<=cntDepth) 
    {
      return (i-1);
    }
  }
  return (Tree_E-1);
}
function genTableHeader(maxDepth)
{
  var j;
  var tmp="<tr>";
  for(j=0;j<maxDepth;j++)
      tmp+="<td width=\"10\">&nbsp;</td>";
  tmp+="<td width=\"180\">&nbsp;</td></tr>";
  return tmp;
}

function genFolder(i,grupEnd,NodeName,NodeLink,NodeTarget,depth,maxDepth)
{
   var style="";
   if (depth>0) style="style=\"display:none\"";
   var rest = maxDepth-depth;
   var j = 15;//for tabindex
   j += i;
   depth++;
   var tmp = "<tr class=\"item\" id=\"layer"+i+"\" "+style+" onClick=\"onTDClick("+i+","+grupEnd+",this,'"+NodeTarget+"','"+NodeLink+"')\" onkeypress=\"onTDClick("+i+","+grupEnd+",this,'"+NodeTarget+"','"+NodeLink+"')\" onMouseOver=\"onMouseTDOver("+i+",this)\" onMouseOut=\"onMouseTDOut("+i+",this)\" style=\"cursor:pointer\" tabIndex="+j+"><td colspan=\""+depth+"\" class=\"item\" align=\"right\" valign=\"middle\"><img id=\"img"+i+"\" src=\""+imgright+"\"></td><td colspan=\""+rest+"\" class=\"item\" style=\"font-size:12px;\"  align=\"left\" valign=\"middle\">"+loadLangString(NodeName,false)+"</td></tr>";
   return tmp;
}
function genItem(i,NodeName,NodeLink,NodeTarget,depth,maxDepth)
{
  var rest = maxDepth-depth;
  var j = 15;//for tabindex
  depth++;
  j +=i;
  var tmp = "<tr class=\"item\" id=\"layer"+i+"\" style=\"display:none\" style=\"cursor:pointer;font-size:12px;\" tabIndex="+j+" onkeypress=\"onTDClick("+i+","+i+",this,'"+NodeTarget+"','"+NodeLink+"')\"><td colspan=\""+depth+"\" class=\"item\" align=\"center\" valign=\"middle\">&nbsp;</td><td id=\"item"+i+"\" class=\"item\" style=\"cursor:pointer;font-size:12px;\" colspan=\""+rest+"\" align=\"left\" valign=\"middle\"  onMouseOver=\"onMouseTDOver("+i+",this)\" onMouseOut=\"onMouseTDOut("+i+",this)\" onClick=\"onTDClick("+i+","+i+",this,'"+NodeTarget+"','"+NodeLink+"')\">"+loadLangString(NodeName,false)+"</td></tr>";
  return tmp;
}

//For ABus .Because genItem() default style is none. So I need create a new function and set default style is block. 
function genBlockItem(i,NodeName,NodeLink,NodeTarget,depth,maxDepth)
{
  var rest = maxDepth-depth;
  var block = 'table-row;cursor:pointer';
  var ie = (typeof window.ActiveXObject != 'undefined');
  depth++;

  if(ie)
  {
    block = 'block';
  }

  var tmp = "<tr class=\"item\" id=\"layer"+i+"\" style=\"display:" + block + "\" onClick=\"onTDClick("+i+","+i+",this,'"+NodeTarget+"','"+NodeLink+"')\" onMouseOver=\"onMouseTDOver("+i+",this)\" onMouseOut=\"onMouseTDOut("+i+",this)\" style=\"cursor:pointer\"><td colspan=\""+depth+"\" class=\"item\" align=\"center\" valign=\"middle\">&nbsp;</td><td id=\"item"+i+"\" style=\"font-size:12px;\" colspan=\""+rest+"\" align=\"left\" valign=\"middle\">"+loadLangString(NodeName,false)+"</td></tr>";
  return tmp;
}

function closeAllItemWithMask(maskFrom, maskTo, curDepth)
{
  var NodeType, NodeName, NodeLink, NodeTarget;
  var TmpStr = new Array;
  var depth;
  for(i=0; i<items; i++) {
      //parse String
    if((i>=maskFrom)&&(i<=maskTo))
       continue;
    TmpStr_1 = TmpStr_0[i].split(",");
        NodeName = TmpStr_1[0];
    NodeType = TmpStr_1[1];
    NodeLink = TmpStr_1[2];
    NodeTarget = TmpStr_1[3];
    depth = TmpStr_0[i].search("-");
    if(depth>curDepth) 
    {
      document.getElementById('layer'+i).style.display='none';
      if(document.getElementById('img'+i)!=null) {
        document.getElementById('img'+i).src=imgright;
        opened[i]=false;
      }
    }else if(depth==curDepth){
      if(document.getElementById('img'+i)!=null){
        document.getElementById('img'+i).src=imgright;
        opened[i]=false;
      }
    }
  }
}
function getType(idx)
{
  var NodeType, NodeName, NodeLink, NodeTarget;
  var TmpStr = new Array;
  TmpStr_1 = TmpStr_0[idx].split(",");
  NodeName = TmpStr_1[0];
  NodeType = TmpStr_1[1];
  NodeLink = TmpStr_1[2];
  NodeTarget = TmpStr_1[3];
  return NodeType;
}