/*
* dialog.js
* http://tasuke.dna.affrc.go.jp/
*
* Copyright (c) 2013 National Institute of Agrobiological Sciences   
*
* This software is released under the MIT License.
*
* http://opensource.org/licenses/mit-license.php
*/

//////////////////////////////////////////////////////////////////////////////////////
//  dialog "_dialog_primer3"
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_p3(str){
  $("#dialog_p3").dialog({
    autoOpen: true,
    modal: true,
    width: 750,
    maxHeight: 800,
    draggable: true,
    resizable: true
  });
  //for exporting sequence 
  var strarray = str.split("|");
  var accession = strarray[0];
  var target=parseInt(strarray[1]);
  var targetEnd=parseInt(strarray[2]);
  var variant=strarray[3];
  var q=localStorage.getItem("_QUAL");
  var dp=localStorage.getItem("_DP");
  var s = target-500;
  var e = target+500;
  if (s < 1){s=1;}
  $("prm_p3_list").val(accession);
  $("input[name=prm_p3_var]").val(variant);
  $("input[name=prm_p3_qual]").val(q);
  $("input[name=prm_p3_dp]").val(dp);
  $("#prm_p3_flk").val(500);
  $("input[name=prm_p3_s]").val(s);
  $("input[name=prm_p3_e]").val(e);

  // Set chromosome
  var o=new Object(JSON.parse(localStorage.getItem("_Chrs")));
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  var name=localStorage.getItem("_Name");
  var nameS=localStorage.getItem("_NameSub");
  var chr = document.getElementById("_Chr");
  var ld="";
  for (var i=0;i<o.length;i++)ld=ld+"<option value='"+o[i].id+"'>"+en.chromosome_name+o[i].id+"</option>";
  
  //Form & param
  $("#prm_p3_name").val(name);
  $("#prm_p3_nameS").val(nameS);
  $("#prm_p3_ref").val(en.reference_name);
  $('#dialog_p3').tabs();
  $('select[name=prm_p3_chr]').find('option').remove().end().append(ld);
  $("select[name=prm_p3_chr]").val(Objects.Chr);
  $("input[name=prm_p3_tgt]").val(target);
  $("input[name=prm_p3_tgt_e]").val(targetEnd);
  
  //dynamic contents
  var sl = document.getElementById("flk_len");
  var len = 500;
  var flk5=len;
  var flk3=len;
  if((s-len) < 0){flk5=s-(s-len);}
  if((e+len) > parseInt(_last_Chr("1b",chr))){flk3=e-(e+len);}
  sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+parseInt(flk5)+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+parseInt(flk3)+"&nbsp;bp";
  _dialog_p3_len();
  _dialog_rp3_len();
  var res = document.getElementById("p3_query_res");
  res.innerHTML="";
  if($("#p3Setting").is(":hidden") != true){
    $("#p3Setting").hide();
  }
  if($("#p3HistArea").is(":hidden") != true){
    $("#p3HistArea").hide();
  }
  _sessionStart();
}

//////////////////////////////////////////////////////////////////////////////////////
// For run Primer3
//////////////////////////////////////////////////////////////////////////////////////
function _slideP3Setting(){
  if ($("#p3Setting").is(":hidden")) {
    $("#p3Setting").slideDown("fast");
  } else {
    $("#p3Setting").slideUp();
  }
}

function _slideP3History(){
  if ($("#p3HistArea").is(":hidden")) {
    $("#p3HistArea").slideDown("fast");
  } else {
    $("#p3HistArea").slideUp();
  }
}

//////////////////////////////////////////////////////////////////////////////////////
//  Validate sequence length for primer template  
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_p3_len(){
  var sub = document.getElementById("p3_submit");
  var flk = document.getElementById("prm_p3_flk");
  var sl = document.getElementById("flk_len");
  var tgt = document.getElementById("prm_p3_tgt");
  var tgte = document.getElementById("prm_p3_tgt_e");
  var dp = document.getElementById("prm_p3_dp");
  var q = document.getElementById("prm_p3_qual");
  var chr = document.getElementById("prm_p3_chr");
  var avd = document.getElementById("prm_p3_avd");
  var avdv = parseInt(avd.value);
  var vdp = parseInt(dp.value);
  var vq = parseInt(q.value);
  var flkv = parseInt(flk.value);
  var tgtv = parseInt(tgt.value);
  var tgtev = parseInt(tgte.value);
  var string="";
  var passed=0;
  
  if(tgt.checkValidity() && tgte.checkValidity() && tgtv!=0 && tgtev!=0 && tgtev >= tgtv && tgtev <= parseInt(_last_Chr("1b",chr.value))){
    if((tgtv-flkv) < 0){flk5=tgtv-1;}
    if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev-1;}
    if((tgtev-tgtv) <= 2000){
      sub.innerHTML =  "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" >Export</button>";
      passed=1;
    }else{
      string="<font color=\"#FF0000\">Target is too long!<br>Maximum size is 2,000 bp.</font>";
      sl.innerHTML = string;
      sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" disabled  >Export</button>";
      passed=0;
    }
  }else{
    string="<font color=\"#FF0000\">Invalid value. Please input target position!</font>";
    sl.innerHTML = string;
    sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" disabled  >Export</button>";
    passed=0;
  }
  
  var flk5=flkv;
  var flk3=flkv;
  if(passed == 1){
    if(flk.checkValidity() && flkv!=0){
      sub.innerHTML =  "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" >Export</button>";
      if (flkv > 2000){
        $("#prm_p3_flk").val(2000);
        flkv = parseInt(flk.value);
        flk5=flkv;
        flk3=flkv;
        if((tgtv-flkv) < 0){flk5=tgtv-1;}
        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
        sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
        passed=2;
      } else if (flkv <= 0){
        string="<font color=\"#FF0000\">Invalid value.</font>";
        sl.innerHTML = string;
        sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" disabled  >Export</button>";
        passed=0;
      } else{
        if((tgtv-flkv) < 0){flk5=tgtv-1;}
        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
        sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
        passed=2;
      }
    }else{
      string="<font color=\"#FF0000\">Please input flanking region length!</font>";
      sl.innerHTML = string;
      sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" disabled onClick=\"_genPrimer3Query();\" >Export</button>";
      passed=0;
    }
  } 
  if(passed == 2){
    if(avd.checkValidity() && dp.checkValidity() && q.checkValidity() && vdp>=0 && vq>=0 && avdv>=0 && flkv >= avdv){
      sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" >Export</button>";
    } else{
      string="<font color=\"#FF0000\">Invalid value.</font>";
      sl.innerHTML = string;
      sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" disabled onClick=\"_genPrimer3Query();\" >Export</button>";
    }
  }
  $("#prm_p3_s").val(tgtv-flk5);
  $("#prm_p3_e").val(parseInt(tgtev)+parseInt(flk3));
}

//////////////////////////////////////////////////////////////////////////////////////
//  Validate sequence length for primer template  
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_rp3_len(){
  var sub = document.getElementById("rp3_submit");
  var flk = document.getElementById("prm_rp3_flk");
  var sl = document.getElementById("flk_len_r");
  var tgt = document.getElementById("prm_rp3_tgt");
  var tgte = document.getElementById("prm_rp3_tgt_e");
  var chr = document.getElementById("prm_rp3_chr");
  var avd = document.getElementById("prm_rp3_avd");
  var dp = document.getElementById("prm_rp3_dp");
  var q = document.getElementById("prm_rp3_qual");
  var avdv = parseInt(avd.value);
  var vdp = parseInt(dp.value);
  var vq = parseInt(q.value);
  var prdmi = document.getElementById("prm_rp3_prdmi");
  var prdmx = document.getElementById("prm_rp3_prdmx");
  var sizeopt = document.getElementById("prm_rp3_sizopt");
  var sizmax = document.getElementById("prm_rp3_sizmax");
  var sizmin = document.getElementById("prm_rp3_sizmin");
  var tmopt = document.getElementById("prm_rp3_tmopt");
  var tmmx = document.getElementById("prm_rp3_tmmx");
  var tmmi = document.getElementById("prm_rp3_tmmi");
  var tmdif = document.getElementById("prm_rp3_tmdif");
  var lowmsk = document.getElementById("prm_rp3_lowmsk");
  var flkv = parseInt(flk.value);
  var tgtv = parseInt(tgt.value);
  var tgtev = parseInt(tgte.value);
  var string="";
  var passed=0;
  
  if(tgt.checkValidity() && tgte.checkValidity() && tgtv!=0 && tgtev!=0 && tgtev >= tgtv && tgtev <= parseInt(_last_Chr("1b",chr.value))){
        if((tgtv-flkv) < 0){flk5=tgtv-1;}
        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev-1;}
    if((tgtev-tgtv) <= 2000){
      sub.innerHTML =  "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" >Run</button>";
      passed=1;
    }else{
      string="<font color=\"#FF0000\">Target is too long!<br>Maximum size is 2,000 bp.</font>";
      sl.innerHTML = string;
      sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
      passed=0;
    }
  }else{
    string="<font color=\"#FF0000\">Invalid value. Please input target position!</font>";
    sl.innerHTML = string;
    sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
    passed=0;
  }
  
  var flk5=flkv;
  var flk3=flkv;
  if(passed == 1){
    if(flk.checkValidity() && flkv!=0){
      sub.innerHTML =  "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" >Run</button>";
      if (flkv > 2000){
        $("#prm_p3_flk").val(2000);
        flkv = parseInt(flk.value);
        flk5=flkv;
        flk3=flkv;
        if((tgtv-flkv) < 0){flk5=tgtv-1;}
        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
        sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
        passed=2;
      } else if (flkv <= 0){
        string="<font color=\"#FF0000\">Invalid value.</font>";
        sl.innerHTML = string;
        sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
        passed=0;
      } else{
        if((tgtv-flkv) < 0){flk5=tgtv-1;}
        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
        sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
        passed=2;
      }
    }else{
      string="<font color=\"#FF0000\">Please input flanking region length!</font>";
      sl.innerHTML = string;
      sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
      passed=0;
    }
  }
  if(passed == 2){
    if(avd.checkValidity() && dp.checkValidity() && q.checkValidity() && prdmi.checkValidity() && prdmx.checkValidity() && sizeopt.checkValidity() 
     && sizmax.checkValidity() && sizmin.checkValidity() && tmopt.checkValidity() && tmmx.checkValidity() && tmmi.checkValidity()  && tmdif.checkValidity()  
     && lowmsk.checkValidity() && vdp>=0 && vq>=0 && avdv>=0 && flkv >= avdv){
      sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" >Run</button>";
    } else{
      string="<font color=\"#FF0000\">Invalid value.</font>";
      sl.innerHTML = string;
      sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
    }
  }
  $("#prm_rp3_s").val(tgtv-flk5);
  $("#prm_rp3_e").val(parseInt(tgtev)+parseInt(flk3));
}

//////////////////////////////////////////////////////////////////////////////////////
//  dialog "_changeRef"
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_changeRef(i){
  $("#prm_chref").val(i);
  $("#dialog_chref").dialog({
    autoOpen: true,
    modal: true,
    width: 470,
    draggable: true,
    resizable: true
  });	
  var cr = document.getElementById("chref_ac");
  var o=new Object(JSON.parse(localStorage.getItem('_Lists')));
  var label = localStorage.getItem("_Name");
  if(Objects.Onebase=="off"){
    if ( localStorage.getItem("_Ref") != o[i].db ) {
      if(label == "id"){
        cr.innerHTML = "Change&nbsp;the&nbsp;reference&nbsp;sequence&nbsp;to&nbsp;<font color=\"red\">"+_escapeHTML(o[i].id)+"<\/font>.";
      } else{
        cr.innerHTML = "Change&nbsp;the&nbsp;reference&nbsp;sequence&nbsp;to&nbsp;<font color=\"red\">"+_escapeHTML(o[i].name)+"<\/font>.";
      }
    } else {
      cr.innerHTML = "Reset&nbsp;reference&nbsp;sequence.";
    }
  }else{
    cr.innerHTML = "This&nbsp;function&nbsp;is&nbsp;disabled&nbsp;when&nbsp;the&nbsp;frequency&nbsp;mode&nbsp;is&nbsp;turned&nbsp;off.";
  }
}

//////////////////////////////////////////////////////////////////////////////////////
// Close dialog:changing reference
//////////////////////////////////////////////////////////////////////////////////////
function _dlg_chref_cancel() {
  $("#dialog_chref").dialog('close');
}
 
//////////////////////////////////////////////////////////////////////////////////////
// Downloading FASTA
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_fa(){
  $("#dialog_fa").dialog({
    autoOpen: true,
    modal: true,
    width: 650,
    draggable: true,
    resizable: true
  });
  var s=parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
  var blk=localStorage.getItem("_Block");
  var e=s+(blk*_cvtZoom(Objects.Zoom))-1;
  if((e-s) >= 19999){e=s+19999;} 
  $("#prm_fa_s").val(s);
  $("#prm_fa_e").val(e);
  
  // Set parameters
  var o=new Object(JSON.parse(localStorage.getItem("_Chrs")));
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  var ld="";
  var q=localStorage.getItem("_QUAL");
  var dp=localStorage.getItem("_DP");
  var name=localStorage.getItem("_Name");
  var nameS=localStorage.getItem("_NameSub");
  var sl = document.getElementById("seq_len");
  var len = e-s+1;
  
  for (var i=0;i<o.length;i++)ld=ld+"<option value='"+o[i].id+"'>"+en.chromosome_name+o[i].id+"</option>";
  $('#prm_fa_chr').find('option').remove().end().append(ld);
  $("#prm_fa_chr").val(Objects.Chr);
  $("#prm_fa_qual").val(q);
  $("#prm_fa_dp").val(dp);
  $("#prm_fa_list").val(_getList("db"));
  $("#prm_fa_name").val(name);
  $("#prm_fa_nameS").val(nameS);
  $("#prm_fa_ref").val(en.reference_name);
  if (len > 20000){
    len = 20000;
  }else if (len < 0){
    len = 0;
  }
  sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+parseInt(len)+"&nbsp;bp";
}

//////////////////////////////////////////////////////////////////////////////////////
// Close dialog:fasta
//////////////////////////////////////////////////////////////////////////////////////
function _dlg_fa_cancel() {
  $("#dialog_fa").dialog('close');
}

///////////////////////////////////////////////////////////////////////////////////
// for exporting param 
///////////////////////////////////////////////////////////////////////////////////
function _param_display(){
  var dp = document.getElementById("prm_fa_dp");
  var q = document.getElementById("prm_fa_qual");
  var w = document.getElementById("prm_fa_width");
  var vw = w.value;
  var vdp = dp.value;
  var vq = q.value;
  var sub = document.getElementById("fa_submit");

  if(dp.checkValidity() && q.checkValidity() && w.checkValidity() && vdp!=0 && vq!=0){
    sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" >";
  } else{
    sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" disabled=\"true\">";
  }
}

 //////////////////////////////////////////////////////////////////////////////////////
//  sequence length
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_fa_len(){
  var s = document.getElementById("prm_fa_s");
  var e = document.getElementById("prm_fa_e");
  var len = e.value-s.value+1;
  var sub = document.getElementById("fa_submit");
  var sl = document.getElementById("seq_len");
  var sv =s.value;
  var ev =e.value;
  
  if(s.checkValidity() && e.checkValidity() && sv!=0 && ev!=0){
    sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" >";
    if (len > 20000){
      len = 20000;
      e.value=(parseInt(sv)+19999);
      sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+len+"&nbsp;bp";
    } else if (len <= 0){
      //len = 0;
      len="<font color=\"#FF0000\">Please check start-postion and end-postion.</font>";
      sl.innerHTML = len;
      sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" disabled=\"true\">";
    } else{
      sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+len+"&nbsp;bp";
    }
  }else{
    len="<font color=\"#FF0000\">Please input postion!</font>";
    sl.innerHTML = len;
    sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" disabled=\"true\">";
  }
}

//////////////////////////////////////////////////////////////////////////////////////
// Downloading CSV
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_csv(){
  $("#dialog_csv").dialog({
    autoOpen: true,
    modal: true,
    width: 500,
    draggable: true,
    resizable: true
  });
  var s=parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
  var e=s+1999;
  $("#prm_csv_s").val(s);
  $("#prm_csv_e").val(e);
  
  // Set parameters
  var o=new Object(JSON.parse(localStorage.getItem("_Chrs")));
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  var ld="";
  for (var i=0;i<o.length;i++)ld=ld+"<option value='"+o[i].id+"'>"+en.chromosome_name+o[i].id+"</option>";
  $('#prm_csv_chr').find('option').remove().end().append(ld);
  $("#prm_csv_chr").val(Objects.Chr);
  var q=localStorage.getItem("_QUAL");
  $("#prm_csv_qual").val(q);
  var dp=localStorage.getItem("_DP");
  $("#prm_csv_dp").val(dp);
  $("#prm_csv_list").val(_getList("db"));
}

//////////////////////////////////////////////////////////////////////////////////////
// Close dialog:csv
//////////////////////////////////////////////////////////////////////////////////////
function _dlg_csv_cancel() {
  $("#dialog_csv").dialog('close');
}

//////////////////////////////////////////////////////////////////////////////////////
// Managing of accession lists
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_list(){
  $("#dialog_list").dialog({
    autoOpen: true,
    modal: true,
    width: 800,
    draggable: true,
    resizable: true
  });
  _dlg_make_list();
}

function _dlg_make_list(){
  var l=new Object(JSON.parse(localStorage.getItem('_Lists')));
  var d=new Object(JSON.parse(localStorage.getItem('_ListsDeleted')));
  var ls="";
  var ld="";
  var ss="";
  
  $('#prm_tw').val(localStorage.getItem('_TitleW'));
  $('#prm_switch_name').val(localStorage.getItem('_Name'));
  $('#prm_switch_sub').val(localStorage.getItem('_NameSub'));
  for (var i=0;i<l.length;i++){
    if ( Objects.Name == "id" ) {
      ss=l[i].id
    } else {
      ss=l[i].name
    }
    var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), l[i].variety.replace(/^\s+|\s+$/g, ""), l[i].grp.replace(/^\s+|\s+$/g, ""), l[i].origin.replace(/^\s+|\s+$/g, ""), l[i].type.replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;");
    ls=ls+"<option value='"+l[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+l[i].variety.replace(/^\s+|\s+$/g, "")+"|"+l[i].grp.replace(/^\s+|\s+$/g, "")+"|"+l[i].origin.replace(/^\s+|\s+$/g, "")+"|"+l[i].type.replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>";
  }
  for (var i=0;i<d.length;i++){
    if ( Objects.Name == "id" ) {
      ld=ld+"<option value='"+d[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+d[i].variety.replace(/^\s+|\s+$/g, "")+"|"+d[i].grp.replace(/^\s+|\s+$/g, "")+"|"+d[i].origin.replace(/^\s+|\s+$/g, "")+"|"+d[i].type.replace(/^\s+|\s+$/g, "")+"'>"+d[i].id+"</option>";
    } else {
      ld=ld+"<option value='"+d[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+d[i].variety.replace(/^\s+|\s+$/g, "")+"|"+d[i].grp.replace(/^\s+|\s+$/g, "")+"|"+d[i].origin.replace(/^\s+|\s+$/g, "")+"|"+d[i].type.replace(/^\s+|\s+$/g, "")+"'>"+d[i].name+"</option>";
    }
  }
  $('#lstBox1').find('option').remove().end().append(ls);
  $('#lstBox2').find('option').remove().end().append(ld);
  
  //button for sorting
  var butSort = "<button class=\"asc\" style=\"width:115px;\" id=\"bSort\"  onClick=\"_sort_accession_list(1,'asc')\" >ID/Name</button>\
  <button class=\"asc\" id=\"bSort2\" style=\"width:115px;\" onClick=\"_sort_accession_list(2,'asc')\">Variety</button>\
  <button class=\"asc\" id=\"bSort3\" style=\"width:115px;\" onClick=\"_sort_accession_list(3,'asc')\">Sub Variety</button>\
  <button class=\"asc\" id=\"bSort4\" style=\"width:115px;\" onClick=\"_sort_accession_list(4,'asc')\">Type</button>";
  $('#run_sorting').html(butSort);
  $('button.asc').button({
    icons: {
      secondary: 'ui-icon-triangle-1-n'
    }
  });
  $('button.desc').button({
    icons: {
      secondary: 'ui-icon-triangle-1-s'
    }
  });
}

//////////////////////////////////////////////////////////////////////////////////////
// Set accession sorting event
//////////////////////////////////////////////////////////////////////////////////////
$(document).ready(function() {
  $('#prm_list_init').click(function(e) {
    localStorage.setItem("_Lists",localStorage.getItem("_Lists-origin"));
    localStorage.setItem("_ListsDeleted","[]");
    _showLoading();
    localStorage.removeItem("_ListsTgt");
    _execCanvas();
    _dlg_make_list();
  });

  $('#prm_list_submit').click(function(e) {
    _reset_accession_lists();
    _showLoading();
    localStorage.removeItem("_ListsTgt");
    _execCanvas();
    _dlg_make_list();
  });

  $('#btnRight').click(function(e) {
    var va=new Array();
    var selectedOpts = $('#lstBox1 option:selected');
    var o=new Object(JSON.parse(localStorage.getItem('_Lists-origin')));
    var ld="";
    if (selectedOpts.length == 0) {
        alert("Nothing to move.");
        e.preventDefault();
    }
    $('#lstBox2').append($(selectedOpts).clone());
    $(selectedOpts).remove();
    e.preventDefault();
    $("#lstBox2 option").each(function () {
      var valAry = $(this).val().split("|");
      va.push(valAry[0]);
    }, null);
    for (var j=0;j<va.length;j++){
      for (var i=0;i<o.length;i++){
        if ( va[j] == o[i].id ) {
          if ( Objects.Name == "id" ) {
            ld=ld+"<option value='"+o[i].id+"|"+o[i].id.replace(/^\s+|\s+$/g, "")+"|"+o[i].variety.replace(/^\s+|\s+$/g, "")+"|"+o[i].grp.replace(/^\s+|\s+$/g, "")+"|"+o[i].origin.replace(/^\s+|\s+$/g, "")+"|"+o[i].type.replace(/^\s+|\s+$/g, "")+"'>"+o[i].id+"</option>";
          } else {
            ld=ld+"<option value='"+o[i].id+"|"+o[i].id.replace(/^\s+|\s+$/g, "")+"|"+o[i].variety.replace(/^\s+|\s+$/g, "")+"|"+o[i].grp.replace(/^\s+|\s+$/g, "")+"|"+o[i].origin.replace(/^\s+|\s+$/g, "")+"|"+o[i].type.replace(/^\s+|\s+$/g, "")+"'>"+o[i].name+"</option>";
          }
        }
      }
    }
    $('#lstBox2').find('option').remove().end().append(ld);
  });

  $('#btnLeft').click(function(e) {
    var va=new Array();
    var o=new Object(JSON.parse(localStorage.getItem('_Lists-origin')));
    var ls="";
    var ss="";
    var selectedOpts = $('#lstBox2 option:selected');
    
    if (selectedOpts.length == 0) {
      alert("Nothing to move.");
      e.preventDefault();
    }
    $('#lstBox1').append($(selectedOpts).clone());
    $(selectedOpts).remove();
    e.preventDefault();
    $("#lstBox1 option").each(function () {
      var valAry = $(this).val().split("|");
      va.push(valAry[0]);
    }, null);
    for (var j=0;j<va.length;j++){
      for (var i=0;i<o.length;i++){
        if ( va[j] == o[i].id ) {
          if ( Objects.Name == "id" ) {
            ss=o[i].id
          } else {
            ss=o[i].name
          }
          var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), o[i].variety.replace(/^\s+|\s+$/g, ""), o[i].grp.replace(/^\s+|\s+$/g, ""), o[i].origin.replace(/^\s+|\s+$/g, ""), o[i].type.replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;")
          ls=ls+"<option value='"+o[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+o[i].variety.replace(/^\s+|\s+$/g, "")+"|"+o[i].grp.replace(/^\s+|\s+$/g, "")+"|"+o[i].origin.replace(/^\s+|\s+$/g, "")+"|"+o[i].type.replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>"
        }
      }
    }
    $('#lstBox1').find('option').remove().end().append(ls);
  });

  $.fn.reverse = [].reverse;
  $("#bUp,#bDown").click(function() {
    var $opt = $("#lstBox1 option:selected");
    if (!$opt.length) return;
    var bGoUp = (this.id == "bUp");
    if (!bGoUp) $opt.reverse();
    $opt.each(function(i) {
      var $src = $(this);
      var $dst = $src[bGoUp ? "prev" : "next"]();
      if ($dst.length && $dst[0].selected) return;
      $dst[bGoUp ? "before" : "after"]($src);
    });
  });
});

function _sort_accession_list(type,order){
var ls ="";
var keyAry = new Array();
var valAry = new Array();
var prtAry = new Array();
var labels = ["ID/Name","Variety", "Sub Variety", "Type"];
var orderForNext;
var maxtype=4;
var butSort ="";

//type: 1=id or name, 2=variety, 3=subvariety, 4=origin
//order: 1=asec, 2=desc

var elm = document.getElementById("lstBox1");
type=parseInt(type);
if(type < 1 || type > 4){
  type=1;
}

for (var i=0;i<elm.options.length;i++) {
  var eachtext = elm.options[i].value;
  var textAry = eachtext.split("|");
  keyAry.push(textAry[type]);
  valAry.push(eachtext);
}

var uniqueArray = keyAry.filter(
  function( value, index, self ){return self.indexOf( value ) == index;}
);

if(order=="asc"){
  uniqueArray.sort();
  orderForNext="desc";
}else{
  uniqueArray.reverse();
  orderForNext="asc";
}

for(var x=0; x<uniqueArray.length; x++){
  var str = uniqueArray[x];
  for(var i=0; i<elm.options.length; i++){
    var tmpAry = valAry[i].split("|");
    if(tmpAry[type] == str){
      prtAry.push(valAry[i]);
    }
  }
}
for(var i=0; i<prtAry.length; i++){
  var str = prtAry[i].split("|");
  var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", str[1], str[2], str[3], str[4], str[5]).replace(/\s/g,"&nbsp;");
  ls=ls+"<option value='"+str[0]+"|"+str[1]+"|"+str[2]+"|"+str[3]+"|"+str[4]+"|"+str[5]+"'>"+st+"</option>";
}
$('#lstBox1').find('option').remove().end().append(ls);

for(var i=0; i<maxtype; i++){
  if(type==parseInt(i+1)){
    butSort=butSort+"<button class=\""+orderForNext+"\" id=\"bSort\" style=\"width:115px; color: blue;\" onClick=\"_sort_accession_list("+parseInt(i+1)+",'"+orderForNext+"')\" >"+labels[i]+"</button> ";
  }else{
    butSort=butSort+"<button class=\"asc\" id=\"bSort\" style=\"width:115px;\" onClick=\"_sort_accession_list("+parseInt(i+1)+",'asc')\" >"+labels[i]+"</button> ";
  }
}

$('#run_sorting').html(butSort);
$('button.asc').button({
  icons: {
    secondary: 'ui-icon-triangle-1-n'
  }
});
$('button.desc').button({
  icons: {
    secondary: 'ui-icon-triangle-1-s'
  }
});

}

//////////////////////////////////////////////////////////////////////////////////////
// Reset accession list
//////////////////////////////////////////////////////////////////////////////////////
function _reset_accession_lists() {
  var o=new Object(JSON.parse(localStorage.getItem('_Lists-origin')));
  var value1=new Array();
  $("#lstBox1 option").each(function () {
    var valAry = $(this).val().split("|");
    value1.push(valAry[0]);
  }, null);
  
  var strDel="[";
  for (var i=0;i<value1.length;i++) {
    for (var j=0;j<o.length;j++){
      if ( value1[i] == o[j].id ){
        strDel=strDel+"{";
        strDel=strDel+"\"id\":\""+o[j].id+"\",";
        strDel=strDel+"\"db\":\""+o[j].db+"\",";
        strDel=strDel+"\"name\":\""+o[j].name+"\",";
        strDel=strDel+"\"variety\":\""+o[j].variety+"\",";
        strDel=strDel+"\"grp\":\""+o[j].grp+"\",";
        strDel=strDel+"\"origin\":\""+o[j].origin+"\",";
        strDel=strDel+"\"origin_2\":\""+o[j].origin_2+"\",";
        strDel=strDel+"\"type\":\""+o[j].type+"\"";
        strDel=strDel+"}";
      }
    }
    if ( i < value1.length-1 ) {
      strDel=strDel+",";
    }
  }
  strDel=strDel+"]";
  localStorage.setItem("_Lists",(strDel));

  var value=new Array();
  $("#lstBox2 option").each(function () {
    var valAry = $(this).val().split("|");
    value.push(valAry[0]);
  }, null);
  var strDel="[";
  for (var i=0;i<value.length;i++) {
    for (var j=0;j<o.length;j++){
      if ( value[i] == o[j].id ){
        strDel=strDel+"{";
        strDel=strDel+"\"id\":\""+o[j].id+"\",";
        strDel=strDel+"\"db\":\""+o[j].db+"\",";
        strDel=strDel+"\"name\":\""+o[j].name+"\",";
        strDel=strDel+"\"variety\":\""+o[j].variety+"\",";
        strDel=strDel+"\"grp\":\""+o[j].grp+"\",";
        strDel=strDel+"\"origin\":\""+o[j].origin+"\",";
        strDel=strDel+"\"origin_2\":\""+o[j].origin_2+"\",";
        strDel=strDel+"\"type\":\""+o[j].type+"\"";
        strDel=strDel+"}";
      }
    }
    if ( i < value.length-1 ) {
      strDel=strDel+",";
    }
  }
  strDel=strDel+"]";
  localStorage.setItem("_ListsDeleted",(strDel));
}

//////////////////////////////////////////////////////////////////////////////////////
// Search keyword & jump position
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_go(){
  $("#dialog_go").dialog({
    autoOpen: true,
    modal: false,
    width: 800,
    ONdraggable: true,
    resizable: true
  });

  // Set chromosome
  var o=new Object(JSON.parse(localStorage.getItem("_Chrs")));
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  var cs="";
  for (var i=0;i<o.length;i++) cs=cs+"<option value='"+o[i].id+"'>"+en.chromosome_name+o[i].id+"</option>";
  $('#prm_position_chr').find('option').remove().end().append(cs);
  $('#prm_position_chr').val(Objects.Chr);
  $('#prm_position_zoom').val(localStorage.getItem('_Zoom'));
  _setComboHistory()  // Set history combobox
}

////////////////////////////// Set options in combobox
function _setComboHistory() {
  var h=JSON.parse(localStorage.getItem("_History"));
  var en=JSON.parse(localStorage.getItem("_Env"));
  var hs="<option value=''> - </option>";
  for (i=1;i<h.length;i++) {
    t=h[i].split(",");
    if(t[0]=="search") hs=hs+"<option value='"+i+"'>"+t[1]+"</option>";
    else if(t[0]=="position") {
      var spt3;
      var t2t3;
      if (t[3].match(/k/i)) {
        spt3=t[3].split("k");
        t2t3=(t[2]-1)*spt3[0]*1000+1;
      } else{
        spt3=t[3].split("b");
        t2t3=(t[2]-1)*spt3[0]+1;
      }
      hs=hs+"<option value='"+i+"'>"+en.chromosome_name+t[1]+" : "+t2t3+"&nbsp;&nbsp;&nbsp;("+t[3]+")</option>";
    }
  }
  $('#prm_history_cmd').find('option').remove().end().append(hs);
}

///////////////////////////// Convert length of chromosome as zoom
function _setHistory(str){
  var a=JSON.parse(localStorage.getItem("_History"));
  if(a.length>20) a.pop();
  a.unshift(str);
  localStorage.setItem("_History",JSON.stringify(a));
  _setComboHistory();
}

// Execute history command
function _historyCmd() {
  var history=parseInt($('#prm_history_cmd').val());
  var h=JSON.parse(localStorage.getItem("_History"));
  var t=h[history].split(",");
  if(t[0]=="search") {
    _execSearch(t[1]);
  }
  if(t[0]=="position") {
    _setHistory(h[history]);
    localStorage.setItem('_Chr', t[1]);
    localStorage.setItem('_Pos', t[2]);
    localStorage.setItem("_Zoom", t[3]);
    var spt3;
    var t2t3;
    if (t[3].match(/k/i)) {
      spt3=t[3].split("k");
      t2t3=(t[2]-1)*spt3[0]*1000+1;
    } else{
      spt3=t[3].split("b");
      t2t3=(t[2]-1)*spt3[0]+1;
    }
    _showLoading();
    _messageOnScreen("Loading position "+t2t3);
    _execCanvas();
  }
}

function _jumpPOS(e){
  var spzoom;
  var pzoom;
  c=$('#prm_position_chr').val();
  z=$('#prm_position_zoom').val();
  i=$('#prm_position').val();
  
  if(!isNaN(i)&&i!=""){
    p=_checkPos_Chr(i,z,c);
    localStorage.setItem('_Pos', p);
    localStorage.setItem('_Chr', c);
    localStorage.setItem("_Zoom", z);
    _showLoading();
    if (z.match(/k/i)) {
      spzoom=z.split("k");
      pzoom=(p-1)*spzoom[0]*1000+1;
    }else{
      spzoom=z.split("b");
      pzoom=(p-1)*spzoom[0]+1;
    }
    _messageOnScreen("Loading position "+pzoom+" ["+z+"]");
    _execCanvas();
    _setHistory("position,"+c+","+p+","+z);
  } else {
    _messageOnScreen("Input numeric code ["+i+"]");
  }
  $("#dialog_position").dialog('close');
}

function _searchID(e){
  str=$('#prm_keyword_res').val();
  if(!str){return;}
  if(str.length>3) {
    _execSearch(str);
    $('#prm_keyword_res').blur();
    $("#dialog_keyword").dialog('close');
    $("#dialog_go").dialog('close');
  } 
}

function _preSearchID(e){
  if(e.keyCode == 13 || ! e.keyCode){
    str=$('#prm_keyword').val();
    mode=$('#prm_opt').val();
    if(str.length>3) {
      $('#prm_keyword_res').find('OPTGROUP').remove().end();
      $('#prm_keyword_res').find('option').remove().end().append("<option value=\'\'>Searching...</option>");
      _preExecSearch(str,mode);
      $('#prm_keyword').blur();
      $('#prm_opt').blur();
    } else {
      _drawCanvas();
      _messageOnScreen("The keyword must has over 4 strings.");
    }
    $("#dialog_keyword").dialog('close');
  }
}

//////////////////////////////////////////////////////////////////////////////////////
// Track manager
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_track(){
  $("#dialog_track").dialog({
    autoOpen: true,
    modal: false,
    width: 620,
    draggable: true,
    resizable: true
  });
  $('#dialog_track').empty();
  $('#dialog_track').append(_html_track());
}

function _html_track(){
  var t=new Object(JSON.parse(localStorage.getItem('_Tracks')));
  if ( !t.length ) {
    $('#dialog_track').append("<br><br><font color='red'>Track is empty.</font>");
  } else {
    var str="<table width='100%'><tr height='40'><th width='31%' align='left'>Track name</th><th width='23%' align='left'>View</th><th width='13%' align='left'>Row</th><th width='13%' align='left'>Order</th><th width='20%' align='left'>Color <input type='submit' name='_track_c_' value='Apply' onClick='_changeColorTrack(this)' style='width: 50px;'></td></th></tr>";
    for (var i=0;i<t.length;i++){
      str=str+"<tr><td><label>"+(i+1)+". "+t[i].track+"</label></td>";
      str=str+"<td><select name='_track_v_"+i+"' onChange='_changeViewTrack(this)'>";
      if ( t[i].p == 1 ) { 
        str=str+"<option value='on' selected>ON</option>";
        str=str+"<option value='off'>OFF</option>";
      } else {
        str=str+"<option value='on'>ON</option>";
        str=str+"<option value='off' selected>OFF</option>";
      }
      str=str+"</select></td>";
      str=str+"<td><select name='_track_d_"+i+"' onChange='_changeDepthTrack(this)'>";
      if ( t[i].h == 1 ) {
        str=str+"<option value='1' selected>1</option>";
        str=str+"<option value='4'>4</option>";
      } else {
        str=str+"<option value='1'>1</option>";
        str=str+"<option value='4' selected>4</option>";
      }
      str=str+"</select></td>";
      str=str+"<td><select name='_track_s_"+i+"' onChange='_changeSortTrack(this)'>";
      for (var j=0; j<t.length; j++ ) {
        if ( i == j ) {
          str=str+"<option value='"+j+"' selected>"+(j+1)+"</option>";
        } else {
          str=str+"<option value='"+j+"'>"+(j+1)+"</option>";
        }
      }
      str=str+"</select></td>";
      str=str+"<td><input type='text' name='_track_c_"+i+"' value='"+t[i].c+"' style='width: 70px;'>";
    }
    str=str+"</table>";
    str=str+"<br>";
  }
  return str;
}

function _changeColorTrack(Obj) {
  var t=new Object(JSON.parse(localStorage.getItem('_Tracks')));
  var str="[";
  for ( var i=0; i<t.length; i++ ) {
    str=str+"{";
    str=str+"\"track\":\""+t[i].track+"\",";
    str=str+"\"p\":\""+t[i].p+"\",";
    str=str+"\"h\":\""+t[i].h+"\",";
    str=str+"\"c\":\""+$("input[name='_track_c_"+i+"']").val()+"\",";
    str=str+"\"s\":\""+i+"\"}";
    if ( i < t.length-1 ) {
      str=str+",";
    }
  }
  str=str+"]";
  localStorage.setItem("_Tracks",str);
  _drawCanvas();
}

function _changeViewTrack(Obj) {
  var n=Obj.name.split("_");
  var v=Obj.options[Obj.selectedIndex].value;
  var t=new Object(JSON.parse(localStorage.getItem('_Tracks')));
  var cmp = "1";
  if ( v == "off" ) {cmp = "0";}
  var str="[";
  
  for ( var i=0; i<t.length; i++ ) {
    str=str+"{";
    str=str+"\"track\":\""+t[i].track+"\",";
    if ( t[i].s == n[3] ){
      str=str+"\"p\":\""+cmp+"\",";
    } else {
      str=str+"\"p\":\""+t[i].p+"\",";
    }
    str=str+"\"h\":\""+t[i].h+"\",";
    str=str+"\"c\":\""+t[i].c+"\",";
    str=str+"\"s\":\""+i+"\"}";
    if ( i < t.length-1 ) {
      str=str+",";
    }
  }
  str=str+"]";
  localStorage.setItem("_Tracks",str);
  _drawCanvas();
}

function _changeDepthTrack(Obj) {
  var n=Obj.name.split("_");
  var v=parseInt(Obj.options[Obj.selectedIndex].value);
  var t=new Object(JSON.parse(localStorage.getItem('_Tracks')));
  var str="[";
  
  for ( var i=0; i<t.length; i++ ) {
    str=str+"{";
    str=str+"\"track\":\""+t[i].track+"\",";
    str=str+"\"p\":\""+t[i].p+"\",";
    if ( t[i].s == n[3] ){
        str=str+"\"h\":\""+v+"\",";
    } else {
        str=str+"\"h\":\""+t[i].h+"\",";
    }
    str=str+"\"c\":\""+t[i].c+"\",";
    str=str+"\"s\":\""+i+"\"}";
    if ( i < t.length-1 ) {
      str=str+",";
    }
  }
  str=str+"]";
  localStorage.setItem("_Tracks",str);
  _drawCanvas();
}

function _changeSortTrack(Obj) {
  var n=Obj.name.split("_");
  var v=parseInt(Obj.options[Obj.selectedIndex].value);
  var t=new Object(JSON.parse(localStorage.getItem('_Tracks')));
  var a=new Array();

  for ( var i=0; i<t.length; i++ ) {
    a[i] = i; 
  }
  a[n[3]]=v; 
  a[v]=n[3]; 
  var tmp = localStorage.getItem('_Track_'+n[3]);
  localStorage.setItem("_Track_"+n[3],localStorage.getItem('_Track_'+v));
  localStorage.setItem("_Track_"+v,tmp);
  var str="[";
  for ( var i=0; i<a.length; i++ ) {
    for (var j=0;j<t.length;j++) {
      if ( a[i] == t[j].s ){
        str=str+"{";
        str=str+"\"track\":\""+t[j].track+"\",";
        str=str+"\"p\":\""+t[j].p+"\",";
        str=str+"\"h\":\""+t[j].h+"\",";
        str=str+"\"c\":\""+t[j].c+"\",";
        str=str+"\"s\":\""+i+"\"}";
      }
    }
    if ( i < a.length-1 ) {
      str=str+",";
    }
  }
  str=str+"]";
  localStorage.setItem("_Tracks",str);
  $('#dialog_track').empty();
  $('#dialog_track').append(_html_track());
  _drawCanvas();
}

//////////////////////////////////////////////////////////////////////////////////////
// Help
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_manual(){
  $("#dialog_manual").dialog({
    autoOpen: true,
    modal: false,
    width: 700,
    draggable: true,
    height: 625,
    resizable: true
  });
}

//////////////////////////////////////////////////////////////////////////////////////
// About
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_about(){
  $("#dialog_about").dialog({
    autoOpen: true,
    modal: true,
    width: 400,
    height: 450,
    draggable: true,
    resizable: true
  });
}

//////////////////////////////////////////////////////////////////////////////////////
// Citation
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_citation(){
  $("#dialog_citation").dialog({
    autoOpen: true,
    modal: true,
    width: 650,
    draggable: true,
    resizable: true
  });
}

//////////////////////////////////////////////////////////////////////////////////////
// Reset to browser
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_reset(){
  $("#dialog_reset").dialog({
    autoOpen: true,
    modal: true,
    width: 320,
    draggable: true,
    resizable: true
  });
}

function _dlg_reset_cancel() {
  $("#dialog_reset").dialog('close');
}

function _dlg_reset_confirm() {
  localStorage.clear();
  _initCache();
  location.replace('./');
}

//////////////////////////////////////////////////////////////////////////////////////
// Variants filter
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_filter(){
  $("#dialog_filter").dialog({
    autoOpen: true,
    modal: true,
    width: 350,
    draggable: true,
    resizable: true
  });
  $('#prm_quality').val(localStorage.getItem('_QUAL'));
  $('#prm_depth').val(localStorage.getItem('_DP'));
  $('#prm_dp4').val(localStorage.getItem('_DP4'));
}

/////////////////////////////////////////////// Change variant QUAL
function _changeQUAL(){
  var qual=$('#prm_quality').val();
  localStorage.setItem("_QUAL", qual);
  _showLoading();
  _messageOnScreen("Changing filter: Quality > "+qual);
  _execCanvas();
}

/////////////////////////////////////////////// Change variant DEPTH
function _changeDEPTH(){
  var dp=$('#prm_depth').val();
  localStorage.setItem("_DP", dp);
  _showLoading();
  _messageOnScreen("Changing filter: Depth > "+dp);
  _execCanvas();
}

/////////////////////////////////////////////// Change variant DP4
function _changeDP4(){
  var dp=$('#prm_dp4').val();
  localStorage.setItem("_DP4", dp);
  _showLoading();
  _messageOnScreen("Changing filter: Depth of Alternative allele > "+dp);
  _execCanvas();
}

//////////////////////////////////////////////////////////////////////////////////////
// Options view: block
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_theme(){
  $("#dialog_theme").dialog({
    autoOpen: true,
    modal: true,
    width: 300,
    draggable: true,
    resizable: true
  });
  $('#prm_bgc').val(localStorage.getItem('_Color'));
}

/////////////////////////////////////////////// Change color
function _changeColor(){
  var color=$('#prm_bgc').val();
  localStorage.setItem("_Color", color);
  location.reload();
}

/////////////////////////////////////////////// Change amino acids
function _changeAmino(){
  if (localStorage.getItem("_Amino") == "on"){
    localStorage.setItem("_Amino", "off");
  } else {
    localStorage.setItem("_Amino", "on");
  }
  _drawCanvas();
}

/////////////////////////////////////////////// Change indicator
function _changeIndicator(){
  if (localStorage.getItem("_Indicator") == "on"){
    localStorage.setItem("_Indicator", "off");
    var element = document.getElementById("cvs_ind"); 
    element.style.width = '0px'; 
    element.style.height = '0px'; 
    $('#prm_idc').val("off");
  } else {
    localStorage.setItem("_Indicator", "on");
    var element = document.getElementById("cvs_ind"); 
    element.style.width = '150px'; 
    element.style.height = '135px'; 
    $('#prm_idc').val("on");
  }
  _drawCanvas();
}

/////////////////////////////////////////////// Change title width
function _changeTitleW(){
  var width=$('#prm_tw').val();
  localStorage.setItem("_TitleW", width);
  _drawCanvas();
  _messageOnScreen("Changing width of title: "+width+" pixel");
}

/////////////////////////////////////////////// Change title with ID or Name
function _changeTitleID(){
  localStorage.setItem("_Name",$('#prm_switch_name').val());
  _drawCanvas();
  _dlg_make_list();
}

/////////////////////////////////////////////// Change title with ID or Name
function _changeTitleVariety(){
  localStorage.setItem("_NameSub",$('#prm_switch_sub').val());
  _drawCanvas();
}

//////////////////////////////////////////////////////////////////////////////////////
// Dialog: Cell information
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_infocell(str){
  $("#dialog_infocell").dialog({
    autoOpen: true,
    modal: true,
    width: 900,
    maxHeight: 600,
    draggable: true,
    resizable: true
  });
  $('#dialog_cellinformation').empty();
  $('#dialog_cellinformation').append(str);
}

//////////////////////////////////////////////////////////////////////////////////////
// Dialog: Blocks
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_block(){
  $("#dialog_block").dialog({
    autoOpen: true,
    modal: true,
    width: 300,
    draggable: true,
    resizable: true
  });
  $('#prm_bn').val(localStorage.getItem('_Block'));
  $('#prm_bh').val(localStorage.getItem('_BlockH'));
  $('#prm_bw').val(localStorage.getItem('_BlockW'));
}


/////////////////////////////////////////////// Change column(load block)
function _changeBlock(){
  var col=parseInt($('#prm_bn').val());
  localStorage.setItem('_Block', String(col));
  if(Objects.Pos+col>_last(Objects.Zoom)) localStorage.setItem('_Pos',String(_last(Objects.Zoom)-col+1));
  _showLoading();
  _messageOnScreen("Changing "+Objects.Block+" to "+col+" blocks");
  _execCanvas();
}

/////////////////////////////////////////////// Change block width
function _changeBlockW(){
  var width=$('#prm_bw').val();
  localStorage.setItem("_BlockW", width);
  _messageOnScreen("Changing width of block: "+width+" pixel");
  setTimeout("_drawCanvas()", 500);
}

/////////////////////////////////////////////// Change block height
function _changeBlockH(){
  var height=$('#prm_bh').val();
  localStorage.setItem("_BlockH", height);
  _messageOnScreen("Changing width of height: "+height+" pixel");
  setTimeout("_drawCanvas()", 500);
}

//////////////////////////////////////////////////////////////////////////////////////
// Effect level list
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_list_effect(){
  $("#dialog_list_effect").dialog({
    autoOpen: true,
    modal: false,
    width: 350,
    draggable: true,
    resizable: true
  });
}

/////////////////////////////////////////////// Change color depth for Custom track
function _dialog_colorManager(){
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  var valArrayPct = _genArrayForColManPct();
  var valArray = _genArrayForColMan();
  var KeyRelation = _genKeyRelateColMan(valArray);
  var KeyRelationPct = _genKeyRelateColMan(valArrayPct);
  var zoom= localStorage.getItem("_Zoom");
  $("#cstm_slider_name").text(en.cstm_name);
  var snp_max=(en.snp_100k/100000)*100;
  var indel_max=_getMaxGraINDEL()/_cvtZoom(localStorage.getItem("_Zoom"))*100;
  var depth_max=en.depth_max;
  var cstm_max=en.cstm_max;
  var snp_min=(en.snp_min/100000)*100;
  var indel_min=(en.indel_min/100000)*100;
  if("snp_min_rate" in Objects){snp_min=Objects.snp_min_rate*100;}
  if("indel_min_rate" in Objects){indel_min=Objects.indel_min_rate*100;}
  var depth_min=en.depth_min;
  var cstm_min=en.cstm_min;

  if(_isUndefined(KeyRelation[depth_max])){depth_max=roundBasedOnArray(depth_max,valArray);}
  if(_isUndefined(KeyRelation[depth_min])){depth_min=roundBasedOnArray(depth_min,valArray);}
  if(_isUndefined(KeyRelation[cstm_max])){depth_max=roundBasedOnArray(cstm_max,valArray);}
  if(_isUndefined(KeyRelation[cstm_min])){cstm_min=roundBasedOnArray(cstm_min,valArray);}
  if(_isUndefined(KeyRelationPct[snp_max])){snp_max=roundBasedOnArray(snp_max,valArrayPct);}
  if(_isUndefined(KeyRelationPct[snp_min])){snp_min=roundBasedOnArray(snp_min,valArrayPct);}
  if(_isUndefined(KeyRelationPct[indel_max])){indel_max=roundBasedOnArray(indel_max,valArrayPct);}
  if(_isUndefined(KeyRelationPct[indel_min])){indel_min=roundBasedOnArray(indel_min,valArrayPct);}
  $("#snp_slider_range_view").text("Range: "+(snp_min)+"% - "+(snp_max)+"%");
  $("#indel_slider_range_view").text("Range: "+(indel_min)+"% - "+(indel_max)+"%");
  $("#depth_slider_range_view").text("Range: "+valArray[KeyRelation[depth_min]]+" - "+valArray[KeyRelation[depth_max]]);
  $("#cstm_slider_range_view").text("Range: "+valArray[KeyRelation[cstm_min]]+" - "+valArray[KeyRelation[cstm_max]]);
  $("#manager_snp_max").val(en.snp_max_col);
  $("#manager_snp_min").val(en.snp_min_col);
  $("#manager_indel_max").val(en.indel_max_col);
  $("#manager_indel_min").val(en.indel_min_col);
  $("#manager_depth_max").val(en.depth_max_col);
  $("#manager_depth_min").val(en.depth_min_col);
  $("#manager_cstm_max").val(en.cstm_max_col);
  $("#manager_cstm_min").val(en.cstm_min_col);
  _drawManagerInd();
  
  $("#dialog_color_manager").dialog({
    autoOpen: true,
    modal: true,
    width: 650,
    draggable: true,
    resizable: true
  });
  
  var colorObjects=["#manager_snp_max","#manager_snp_min","#manager_indel_max","#manager_indel_min","#manager_depth_max","#manager_depth_min","#manager_cstm_max","#manager_cstm_min"];
  for(var b=0; b<colorObjects.length; b++){
    $(colorObjects[b]).ColorPicker({
      onSubmit: function(hsb, hex, rgb, el) {
      $(el).val("#"+hex);
      $(el).ColorPickerHide();
      _drawManagerInd(1);
      },
      onBeforeShow: function () {
        $(this).ColorPickerSetColor(this.value);
      }
    }).bind('keyup', function(){
      $(this).ColorPickerSetColor(this.value);
    });
  }
  
  $(function() {
    $( "#snp_slider_range" ).slider({
      range: true,
      min: 0,
      max: valArrayPct.length-1,
      values: [ KeyRelationPct[snp_min], KeyRelationPct[snp_max] ],
      slide: function( event, ui ) {
        if(ui.values[0] >= ui.values[1]){return false;}
        $("#snp_slider_min").val(valArrayPct[ui.values[0]]);
        $("#snp_slider_max").val(valArrayPct[ui.values[1]]);
        $("#snp_slider_range_view").text("Range: "+valArrayPct[ui.values[0]]+"% - "+valArrayPct[ui.values[1]]+"%");
        _changeRangeOfGrad("snp");
      }
    });
    $("#snp_slider_min").val(valArrayPct[$( "#snp_slider_range" ).slider( "values", 0 )]);
    $("#snp_slider_max").val(valArrayPct[$( "#snp_slider_range" ).slider( "values", 1 )]);
  });
  $(function() {
    $( "#indel_slider_range" ).slider({
      range: true,
      min: 0,
      max: valArrayPct.length-1,
      values: [ KeyRelationPct[indel_min], KeyRelationPct[indel_max] ],
      slide: function( event, ui ) {
        if(ui.values[0] >= ui.values[1]){return false;}
        $("#indel_slider_min").val(valArrayPct[ui.values[0]]);
        $("#indel_slider_max").val(valArrayPct[ui.values[1]]);
        $("#indel_slider_range_view").text("Range: "+valArrayPct[ui.values[0]]+"% - "+valArrayPct[ui.values[1]]+"%");
        _changeRangeOfGrad("indel");
      }
    });
    $("#indel_slider_min").val(valArrayPct[$( "#indel_slider_range" ).slider( "values", 0 )]);
    $("#indel_slider_max").val(valArrayPct[$( "#indel_slider_range" ).slider( "values", 1 )]);
  });
  $(function() {
    $( "#depth_slider_range" ).slider({
      range: true,
      min: 0,
      max: valArray.length-1,
      values: [ KeyRelation[depth_min], KeyRelation[depth_max] ],
      slide: function( event, ui ) {
        if(ui.values[0] >= ui.values[1]){return false;}
        $("#depth_slider_min").val(valArray[ui.values[0]]);
        $("#depth_slider_max").val(valArray[ui.values[1]]);
        $("#depth_slider_range_view").text("Range: "+valArray[ui.values[0]]+" - "+valArray[ui.values[1]]);
        _changeRangeOfGrad("depth");
      }
    });
    $("#depth_slider_min").val(valArray[$( "#depth_slider_range" ).slider( "values", 0 )]);
    $("#depth_slider_max").val(valArray[$( "#depth_slider_range" ).slider( "values", 1 )]);
  });
  $(function() {
    $( "#cstm_slider_range" ).slider({
      range: true,
      min: 0,
      max: valArray.length-1,
      values: [ KeyRelation[cstm_min], KeyRelation[cstm_max] ],
      slide: function( event, ui ) {
        if(ui.values[0] >= ui.values[1]){return false;}
        $("#cstm_slider_min").val(valArray[ui.values[0]]);
        $("#cstm_slider_max").val(valArray[ui.values[1]]);
        $("#cstm_slider_range_view").text("Range :"+valArray[ui.values[0]]+" - "+valArray[ui.values[1]]);
        _changeRangeOfGrad("cstm");
      }
    });
    $("#cstm_slider_min").val(valArray[$( "#cstm_slider_range" ).slider( "values", 0 )]);
    $("#cstm_slider_max").val(valArray[$( "#cstm_slider_range" ).slider( "values", 1 )]);
  });
}

function _resetColorEnv(){
  if("snp_min_rate" in Objects){delete Objects.snp_min_rate;}
  if("indel_min_rate" in Objects){delete Objects.indel_min_rate;}
  _execEnv();
  _drawCanvas();
  _dialog_colorManager();
}

function roundBasedOnArray(val,array){
  var ret="";
  for(var a=0; a<array.length; a++){
    if(array[a] > val){
      var left=a-1;
      if(a<1){left=0;}
      var right=a;
      left=Math.abs(val-left);
      right=Math.abs(val-right);
      if(left >= right){
        ret=array[a];
      }else{
        ret=array[a-1];
      }
      break;
    }
  }
  if(val < array[0]){ret=array[0];}
  return ret;
}

function _genArrayForColMan(){
  var valArray=[0,1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,200,250,300,400,500,600,700,800,900,1000,1500,2000,2500,3000,4000,5000];
  return valArray;
}  

function _genArrayForColManPct(){
  var valArray=[0.001,0.002,0.005,0.01,0.02,0.05,0.1,0.2,0.5,1,2,5,10];//percent
  return valArray;
} 

function _genKeyRelateColMan(a){
  var KeyRelation= new Object();
  for(var i=0; i<a.length; i++){
    KeyRelation[a[i]]=i;
  }
  return KeyRelation;
}

