var g_musics;
var g_plans;
  //导出方案
function on_export()
{
    var plan_name = document.getElementById("plan_select").value;
    var jplan = get_plan_data();
    var data = JSON.stringify(jplan)
    var urlObject = window.URL || window.webkitURL || window;
    var export_blob = new Blob([data]);
    var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
    save_link.href = urlObject.createObjectURL(export_blob);
    save_link.download = plan_name;
    //fakeClick(save_link);
    var ev = document.createEvent("MouseEvents");
    ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, 
                        false, false, false, false, 0, null);
    save_link.dispatchEvent(ev);
}

function on_import()
{
    var file_input = document.createElement("input");
    file_input.type="file";
    //del.onclick = function d(){
    //    alert("dddddddddd");
    //};
    file_input.onchange = function (){
      var file = file_input.files[0];
      var reader = new FileReader();
      reader.readAsText(file);
      reader.onload = function () {
        var jplan = JSON.parse(this.result);
        init_table(jplan.timers);
        //alert(this.result)
      }
    }
    var ev = document.createEvent("MouseEvents");
    ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, 
                        false, false, false, false, 0, null);
    file_input.dispatchEvent(ev);
}
  //启动方案
  function on_active_plan_click()
  {
    var plan_name = document.getElementById("plan_select").value;
    var query_str = "cmd=active&plan_name=" + plan_name;
    ring_set("plan",query_str,function(json){if(json.result ==0){alert("启用方案成功");location.reload();}});
  }
  //删除方案
  function on_del_plan_click()
  {
    var plan_name = document.getElementById("plan_select").value;
    var query_str = "cmd=delete&plan_name=" + plan_name;
    ring_set("plan",query_str,function(json){if(json.result ==0){alert("删除方案成功");location.reload();}});
  }
  //新建方案
  function on_new_plan_click()
  {
    var plan_name = prompt("请输入新方案名称", "新打铃方案");
    var query_str = "cmd=new&"+"plan_name=" + plan_name;
    ring_set("plan",query_str,function(json){if(json.result ==0){alert("新建方案成功");location.reload();}});
  }
  //重命名方案
  function on_rename_plan_click()
  {
    var new_name = prompt("请输入新方案名称", "新打铃方案");
    var plan_name = document.getElementById("plan_select").value;
    var query_str = "cmd=rename&"+"plan_name=" + plan_name+"&new_name="+new_name;
    ring_set("plan",query_str,function(json){if(json.result ==0){alert("重命名方案成功");location.reload();}});
  }
  //删除一行,需要保存
  function on_del_timer_click(ele)
  {
    ele.parentNode.parentNode.remove();
  }
  function on_plan_select_change(ele)
  {
    var query_str = "plan_name="+ele.value;
    var index = ele.selectedIndex;
    document.getElementById("tb_timer").innerHTML="";
    init_table(g_plans[index].timers);
    return ;
    
  }
  function get_plan_data()
  {
    var gen_json = {};
    //gen_json.plan_name=plan_name;
    var j_timers = [];
    var tbody = document.getElementById("tb_timer");
    var trs = tbody.children;
    for(var i = 0; i < trs.length ; i++) {  
      var j_timer = {};    
      var tr = trs[i]; 
      var tds=tr.children;
      j_timer.desc    =tds[0].firstElementChild.value;
      j_timer.time    =tds[1].firstElementChild.value;
      j_timer.category=tds[2].firstElementChild.value;
      j_timer.filename=tds[3].firstElementChild.value;
      j_timers[i] = j_timer;
      //alert(desc.value + time[0].value + filename.value);  
    } 
    j_timers.sort((a,b)=>{
      if(a.time>b.time)
        return 1;
      else
        return -1;
    });
    gen_json.timers=j_timers;  
    return gen_json;   
  }
  function on_save_plan_click()
  {
    var ele_plan_name = document.getElementById("plan_select");
    var plan_name = ele_plan_name.value;
    var gen_json = {};
    //gen_json.plan_name=plan_name;
    var j_timers = [];
    var tbody = document.getElementById("tb_timer");
    var trs = tbody.children;
    for(var i = 0; i < trs.length ; i++) {  
      var j_timer = {};    
      var tr = trs[i]; 
      var tds=tr.children;
      j_timer.desc    =tds[0].firstElementChild.value;
      j_timer.time    =tds[1].firstElementChild.value;
      j_timer.category=tds[2].firstElementChild.value;
      j_timer.filename=tds[3].firstElementChild.value;
      j_timers[i] = j_timer;
      //alert(desc.value + time[0].value + filename.value);  
    } 
    j_timers.sort((a,b)=>{
      if(a.time>b.time)
        return 1;
      else
        return -1;
    });
    gen_json.timers=j_timers; 

    var query_str ="cmd=save&plan_name=" + plan_name;
    ring_json_set("plan",query_str,gen_json,function (json){if(json.result == 0) alert("保存方案成功");});
    return;

  };
  function on_add_timer_click()
  {
    table_add_one("新定时","13:30","","",g_musics);
  }
  function on_category_change(ele)
  {
    var tds=ele.parentNode.parentNode.children;
    var index = tds[2].firstElementChild.selectedIndex;
    var file_select = tds[3].firstElementChild;
    file_select.innerHTML="";

    var files = g_musics[index].files;

    for(var i=0;i<files.length;i++){
      var op = document.createElement("option");
      op.innerHTML = files[i];
      op.setAttribute("value",files[i]);
      file_select.appendChild(op);    
    }
  }

  //向表格中添加一行,用于初始化和添加定时
  function table_add_one(desc,time,category,file,musics)
  {
    var tbodyobj = document.getElementById("tb_timer"); 
    var tr = document.createElement("tr"); 
    var td_desc = document.createElement("td"); 
    var input_desc = document.createElement("input"); 
    input_desc.setAttribute("type", "text");
    input_desc.setAttribute("class", "td_text");
    input_desc.setAttribute("value",desc); 
    td_desc.appendChild(input_desc);

    var td_time = document.createElement("td");
    var input_time = document.createElement("input");
    input_time.setAttribute("type", "time");
    input_time.setAttribute("class", "input_time");
    input_time.setAttribute("value", time);
    td_time.appendChild(input_time);

    var td_path = document.createElement("td");
    var input_path = document.createElement("select");
    input_path.setAttribute("class", "td_cat");
    input_path.setAttribute("onchange", "on_category_change(this)");
    var category_index=0;
    for(var i=0;i<musics.length;i++){
      var op = document.createElement("option");
      op.innerHTML = musics[i].category_name;
      op.setAttribute("value",musics[i].category_name);
      input_path.appendChild(op); 
      if(category == musics[i].category_name) 
        category_index = i;    
    }
    td_path.appendChild(input_path);
    input_path.selectedIndex = category_index; 

    var td_file = document.createElement("td");
    var input_file = document.createElement("select");
    input_file.setAttribute("id", "music");
    input_file.setAttribute("class", "td_ring");
    var select_index=0;
    for(var i=0;i<musics[category_index].files.length;i++){
      var op = document.createElement("option");
      op.innerHTML = musics[category_index].files[i];
      op.setAttribute("value",musics[category_index].files[i]);
      input_file.appendChild(op); 
      if(file == musics[category_index].files[i]) 
        select_index = i;    
    }
    //input3.options[index].selected = true; //保持选中状态
    td_file.appendChild(input_file);
    input_file.selectedIndex = select_index; 

    var td4 = document.createElement("td"); 
    var a_del = document.createElement("button");
    a_del.setAttribute("href","javascript:;") ;
    a_del.setAttribute("src","/image/delete.svg") ;
    a_del.setAttribute("onclick", "on_del_timer_click(this)"); 
    a_del.innerHTML='<i class="icon-bin"></i>';
    td4.appendChild(a_del);

    tr.appendChild(td_desc);
    tr.appendChild(td_time); 
    tr.appendChild(td_path); 
    tr.appendChild(td_file); 
    tr.appendChild(td4);  
    tbodyobj.appendChild(tr); 
    
  }
  function init_table(jtimers){
    if(jtimers == null)
      return;

    for(var i = 0;i<jtimers.length;i++){
      var desc = jtimers[i].desc;
      var time = jtimers[i].time;
      var file = jtimers[i].filename;
      var category = jtimers[i].category;
      table_add_one(desc,time,category,file,g_musics);
    }

  }//end of init_table
  function init_plan_select(json){
    //初始化方案选择
    var plan_select = document.getElementById("plan_select");
    plan_select.innerHTML="";
    var index = 0;
    for(var i=0;i<json.plans.length;i++){
      var op = document.createElement("option");
      op.innerHTML = json.plans[i].plan_name;
      op.setAttribute("value",json.plans[i].plan_name);
      plan_select.appendChild(op);
      if(json.plans[i].active == 1) {
        index = i;  
        op.innerHTML = op.innerHTML +"--（启用）";    
      }
     
    }
    
    plan_select.selectedIndex = index;
    return index;
  }

  function on_recove_plans(json)
  {
      json.musics.sort((a,b)=>{
        if(a.category_name>b.category_name)
          return 1;
        else
          return -1;
      });   
      for(var i=0;i<json.musics.length;i++){
        json.musics[i].files.sort((a,b)=>{
          if(a>b)
            return 1;
          else
            return -1;
        });
      }        
      g_musics = json.musics;
      g_plans = json.plans;
      var index = init_plan_select(json);
      document.getElementById("tb_timer").innerHTML="";
      init_table(json.plans[index].timers);
  }



  function main_init() {
    ring_get("plans","a=1",on_recove_plans);
  }
  //window.onbeforeunload = function() { 
  //  return "确认离开当前页面吗？如未保存,数据将会丢失";
  //}