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

var cvs0;
var ctx0;
var cvs1;
var ctx1;
var cvs2;
var ctx2;
var cvs3;
var ctx3;
var cvs4;
var ctx4;
var cvs5;
var ctx5;
var cvs6;
var ctx6;
var cvs7;
var ctx7;
var cvs8;
var ctx8;
var cvs9;
var ctx9;
var cvs10;
var ctx10;
var cvs11;
var ctx11;
var frameCell;
var frameCellwoI;
var frameTitle;
var frameNav;
var frameChr;
var frameTrack;
var frameTrackwR;
var frameSNP;
var frameZoomb;
var ONSEARCH = false;
var RELOAD = false;
var PROGRESSTIMER;
var BUSYDETECTTIMER;
var Objects=new Object();
var timerArray = new Array();

function render() {
  // Checking HTML5
  var canvasSupported = !!window.HTMLCanvasElement;
  if (!canvasSupported) document.location="./bin/error.php?prm_error_mode=HTML5";
  cvs0=document.getElementById("cvs_track_list");
  ctx0=cvs0.getContext("2d");
  cvs1=document.getElementById("cvs_tracks");
  ctx1=cvs1.getContext("2d");
  cvs2=document.getElementById("cvs_nav");
  ctx2=cvs2.getContext("2d");
  cvs3=document.getElementById("cvs_list");
  ctx3=cvs3.getContext("2d");
  cvs4=document.getElementById("cvs_view");
  ctx4=cvs4.getContext("2d");
  cvs5=document.getElementById("cvs_snpt");
  ctx5=cvs5.getContext("2d");
  cvs6=document.getElementById("cvs_snpg");
  ctx6=cvs6.getContext("2d");
  cvs7=document.getElementById("cvs_ind");
  ctx7=cvs7.getContext("2d");
  cvs8=document.getElementById("cvs_ind_blk");
  ctx8=cvs8.getContext("2d");
  cvs9=document.getElementById("cvs_zbar");
  ctx9=cvs9.getContext("2d");
  cvs10=document.getElementById("cvs_cellinf");
  ctx10=cvs10.getContext("2d");
  cvs11=document.getElementById("cvs_refname");
  ctx11=cvs11.getContext("2d");

  // Clear localStorage when url is sub directory on same domain
  var crntUrl = location.href.split("?");
  if ( localStorage.getItem('_Url') != crntUrl[0].replace("index.html","") && _isEmpty(localStorage.getItem("_Ext_accessions"))) localStorage.clear();
  RELOAD = true;
  _showLoadingDialog();
  _showLoading();
  _initCache();
  _externalParser();
  _execCanvas();
  RELOAD = false;
  // When first time
  if ( localStorage.getItem('_Count') == "1" ) {localStorage.setItem('_Count',"2");}
  $("#tasuke").css("background-color",_setColor().bgcolor);
}

///////////////////////////////////////////////////////////
// Initialize localStorage
///////////////////////////////////////////////////////////
function _initCache() {
  if(_isEmpty(localStorage.getItem("_Url"))){
    var crntUrl = location.href.split("?");
    localStorage.setItem("_Url",crntUrl[0].replace("index.html",""));
  }
  if(_isEmpty(localStorage.getItem("_Ref"))){
    localStorage.setItem("_Ref","Reference");
  }
  if(_isEmpty(localStorage.getItem("_Zoom"))){
    localStorage.setItem("_Zoom","1k");
  }
  if(_isEmpty(localStorage.getItem("_Pos"))){
    localStorage.setItem("_Pos","1");
  }
  if(_isEmpty(localStorage.getItem("_Mode"))){
    localStorage.setItem("_Mode","s");
  }
  if(_isEmpty(localStorage.getItem("_Eff"))){
    localStorage.setItem("_Eff","off");
  }
  if(_isEmpty(localStorage.getItem("_Snpblock"))){
    localStorage.setItem("_Snpblock","off");
  }
  if(_isEmpty(localStorage.getItem("_QUAL"))){
    localStorage.setItem("_QUAL","20");
  }
  if(_isEmpty(localStorage.getItem("_DP"))){
    localStorage.setItem("_DP","2");
  }
  if(_isEmpty(localStorage.getItem("_DP4"))){
    localStorage.setItem("_DP4","2");
  }
  if(_isEmpty(localStorage.getItem("_Name"))){
    localStorage.setItem("_Name","id");
  }
  if(_isEmpty(localStorage.getItem("_NameSub"))){
    localStorage.setItem("_NameSub","subvariety");
  }
  /*if(_isEmpty(localStorage.getItem("_TitleW"))){
    localStorage.setItem("_TitleW","160");
  }*/
  if(_isEmpty(localStorage.getItem("_BlockW"))){
    localStorage.setItem("_BlockW","10");
  }
  if(_isEmpty(localStorage.getItem("_BlockH"))){
    localStorage.setItem("_BlockH","12");
  }
  if(_isEmpty(localStorage.getItem("_Block"))){
    localStorage.setItem("_Block","100");
  }
  if(_isEmpty(localStorage.getItem("_Indicator"))){
    localStorage.setItem("_Indicator","on");
  }
  if(_isEmpty(localStorage.getItem("_Amino"))){
    localStorage.setItem("_Amino","on");
  }
  if(_isEmpty(localStorage.getItem("_DirRef"))){
    localStorage.setItem("_DirRef","+");
  }
  if(_isEmpty(localStorage.getItem("_Null"))){
    localStorage.setItem("_Null","true");
  }
  if(_isEmpty(localStorage.getItem("_Keyword"))){
    localStorage.setItem("_Keyword","");
  }
  if(_isEmpty(localStorage.getItem("_History"))){
    localStorage.setItem("_History","[]");
  }
  if(_isEmpty(localStorage.getItem("_Color"))){
    localStorage.setItem("_Color","0");
  }
  if(_isEmpty(localStorage.getItem("_Count"))){
    localStorage.setItem("_Count","1");
  }
  if(_isEmpty(localStorage.getItem("_ListsDeleted"))){
    localStorage.setItem("_ListsDeleted","[]");
  }
  if(_isEmpty(localStorage.getItem("_Env"))){
    _execEnv();
  }
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  if(_isEmpty(localStorage.getItem("_Update"))){
    var str = _checkUpdate();
    localStorage.setItem("_Update", str);
  }else{
    var str = _checkUpdate();
    if(localStorage.getItem("_Update")!=str){
      _dlg_reset_confirm();
    }
  }
  if(_isEmpty(localStorage.getItem("_Lists"))){
    _execLists();
  }
  if(_isEmpty(localStorage.getItem("_CrtCondition"))){
    localStorage.setItem("_CrtCondition", "0|||");
  }
  if(_isEmpty(localStorage.getItem("_Chr"))){
    _execChr();
    localStorage.setItem("_Chr",_getChr().id);
  }
  if(_isEmpty(localStorage.getItem("_Onebase"))){
    localStorage.setItem("_Onebase", "off");
  }
  if(_isEmpty(localStorage.getItem("_CSTM"))){
    if(en.cstm_track=="enabled"){
      localStorage.setItem("_CSTM", "off");
    }else{
      localStorage.setItem("_CSTM", "disabled");
    }
  }
  if(_isEmpty(localStorage.getItem("_TrackID"))){
    localStorage.setItem("_TrackID","off");
  }
  if(_isEmpty(localStorage.getItem("_ColorCode")) || _isEmpty(localStorage.getItem("_GrpCol"))){
    localStorage.setItem("_ColorCode","off");
    _setTitleColor();
  }
  if(!_isEmpty(en.color_acc_group)){
    if(en.color_acc_group=="enabled"){
      localStorage.setItem("_ColorCode", "on");
    }else{
      localStorage.setItem("_ColorCode", "off");
    }
  }
  if(_isEmpty(localStorage.getItem("_TitleW"))){
    if(_isEmpty(en.accession_cvs_width)){
      localStorage.setItem("_TitleW", parseInt(160));
    }else{
      localStorage.setItem("_TitleW", parseInt(en.accession_cvs_width));
    }
  }
  if(_isEmpty(localStorage.getItem("_Conditions"))){
    localStorage.setItem("_Conditions", "[{\"\id\":\"\"}]");
  }
}

///////////////////////////////////////////// Cheking empty
function _isEmpty(value){
  return (value == null || value.length == 0);
}

///////////////////////////////////////////////////////////
// Ajax: get environment settings
///////////////////////////////////////////////////////////
function _checkUpdate() {
var date="";
  $.ajax({
    url: "./bin/"+_backendSelector("dbupdate.php"),
    cache: false,
    async: false,
    success: function(data) {
      date=data;
    }
  });
  date = tasuke_version()+":"+date;
return date;
}

///////////////////////////////////////////////////////////
// Ajax: get environment settings
///////////////////////////////////////////////////////////
function _execEnv() {
  $.ajax({
    url: "./bin/env.php",
    cache: false,
    async: false,
    success: function(data) {
      localStorage.setItem("_Env", data);
    }
  });
}

///////////////////////////////////////////////////////////
// Ajax: get chromosome
///////////////////////////////////////////////////////////
function _execChr() {
  $.ajax({
    url: "./bin/"+_backendSelector("chr.php"),
    cache: false,
    async: false,
    success: function(data) {
      localStorage.setItem("_Chrs", data);
    }
  });
}

///////////////////////////////////////////////////////////
// Ajax: get snpblock
///////////////////////////////////////////////////////////
function _execSnpblock(keyword) {
  $.ajax({
    url: "./bin/snpblock.php",
    cache: false,
    async: false,
    data: {
      "prm_accession": keyword
    },
    success: function(data) {
      localStorage.setItem("_Snpblock", data.replace(/^[ 　\t\r\n]+|[ 　\t\r\n]+$/g, ""));
    }
  });
}

///////////////////////////////////////////////////////////
// Ajax: get list of accessions & tracks
///////////////////////////////////////////////////////////
function _execLists() {
  var accessions = "";
  if(!_isEmpty(localStorage.getItem("_Ext_accessions"))){
    accessions = localStorage.getItem("_Ext_accessions");
    localStorage.removeItem("_Ext_accessions");
  }
  $.ajax({
    url: "./bin/"+_backendSelector("list.php"),
    cache: false,
    type: "POST",
    async: false,
    data: {
      "prm_ext_acc":accessions
    },
    success: function(data) {
      var a=data.split("|");
      localStorage.setItem("_Lists", a[0]);
      localStorage.setItem("_Lists-origin", a[0]);
      localStorage.setItem("_Tracks", a[1]);
      localStorage.setItem("_Conditions", a[2]);
    }
  });
}

///////////////////////////////////////////////////////////
// Ajax: Load information of cell
///////////////////////////////////////////////////////////
function _execInfoCell(x,y) {
  _windowGffClose();
  var o=new Object(JSON.parse(localStorage.getItem('_Lists')));
  var ct=-2;
  for(var i in o){ct++;}
  if(y >(Objects.BlockH*ct)){
    y=Objects.BlockH*ct;
  }else if(y < 0){
    y=0;
  }
  var id=o[parseInt(y/Objects.BlockH)].db;
  var b=Math.abs(parseInt((x/Objects.BlockW)));
  if(b > Objects.Block-1){//when over cvs_view
    b = Objects.Block-2;
  }
  var p=Objects.Pos+b;

  if ( _cvtZoom(Objects.Zoom) > 4000 ) { // When over 1k
    _drawInfoCell(id,b,y,"[]");
  } else {
    $.ajax({
      url: "./bin/"+_backendSelector("info.php"),
      type: "GET",
      cache: false,
      data: {
        "prm_Zoom":Objects.Zoom,
        "prm_Chr":Objects.Chr,
        "prm_Mode":Objects.Mode,
        "prm_Pos":p,
        "prm_QUAL":localStorage.getItem("_QUAL"),
        "prm_DP":localStorage.getItem("_DP"),
        "prm_DP4":localStorage.getItem("_DP4"),
        "prm_Acc":id
      },
      success: function(datas) {
        _drawInfoCell(id,b,y,datas);
      }
    });
  }
}

///////////////////////////////////////////////////////////
// Ajax: Search ID
//       1K zoom will setted
///////////////////////////////////////////////////////////
function _execSearch(keyword) {
  var target=keyword.split("|");
  var cnt=0;
  for(var i in target){cnt++;}
  if(cnt>4){
    var len = target[2]-target[1];
    var blks = parseInt((len*1.1)/Objects.Block);
    var optBlks="";
    var locString="the target";
    var leftPos=1;
    var b=0;
    var c=0;
    var modLeftPos=0;
    if(blks < 1){blks=1;}
    var scale = Math.floor(Math.log(blks)/Math.log(10))+1;
    if(scale==3 && blks > 900){scale=4;}
    if (scale > 1){//processing for Block-size and postion
      b = (blks/Math.pow(10,(scale-1)));
      c = parseInt(b)*Math.pow(10,(scale-1));
      if(scale < 4){
        if(len*1.1 > c*Objects.Block){c = parseInt(b+1)*Math.pow(10,(scale-1));}
        leftPos=parseInt(target[1]/c)-(parseInt((Objects.Block-parseInt(len/c)-2)/2));
        optBlks=c+"b";
      }else{
        if(len*1.1 > c*1000*Objects.Block){c = parseInt(b+1)*Math.pow(10,(scale-1));}
        leftPos=parseInt(target[1]/c)-(parseInt((Objects.Block-parseInt(len/c))/2));
        optBlks=c/1000+"k";
      }
    }else{
      b = (blks/Math.pow(10,(scale-1)));
      c = parseInt(b)*Math.pow(10,(scale-1));
      if(len*1.1 > c*Objects.Block){c = parseInt(b+1)*Math.pow(10,(scale-1));}
      leftPos=parseInt(target[1]/c)-(parseInt((Objects.Block-parseInt(len/c)-2)/2));
      optBlks=c+"b";
    }
    if(scale < 4){
      p=_checkPos_Chr(leftPos*c,optBlks,target[3]);
    }else{
      p=_checkPos_Chr(parseInt(leftPos*c),optBlks,target[3]);
    }
    localStorage.setItem("_Keyword", target[0]);
    localStorage.setItem("_Chr", target[3]);
    localStorage.setItem("_Zoom", optBlks);
    localStorage.setItem("_Pos", p);
    _changeChromosomeSearch(target[0]);
  }
}

///////////////////////////////////////////////////////////
// Ajax: Search ID
//       for  candidates
///////////////////////////////////////////////////////////
function _preExecSearch(keyword,mode) {
  $.ajax({
    url: "./bin/"+_backendSelector("search.php"),
    type: "GET",
    cache: false,
    data: {
      "prm_chr":localStorage.getItem("_Chr"),
      "prm_zoom":localStorage.getItem("_Zoom"),
      "prm_keyword":keyword
    },
    success: function(datas) {
    var spdatas = datas.split("~");
    var cnt=-1;
    var ls="<OPTGROUP label=\"&lt;ID&gt;&nbsp;&nbsp;&nbsp;&lt;Chromosome&gt;&nbsp;&nbsp;&nbsp;&lt;Start&#045;End&gt;&nbsp;&nbsp;&nbsp;&lt;Note&gt;\"></OPTGROUP>";
    var tc=0;
    var num="";
    var submit="";
    for(var i in spdatas){cnt++;}
    for(var t=0; t < cnt; t++){
      var a=spdatas[tc].split("|");
      var id = _delLFCR(a[0]);
      var st = _delLFCR(a[1]);
      var ed = _delLFCR(a[2]);
      var c = _delLFCR(a[4]);
      var note ="";
      var raw_note="";
      if(a[5]){
        note = _delLFCR(a[5]);
        raw_note=note;
        var all=id+""+st+""+ed+""+c+""+note;
        if (all.length > 70){
          note=note.substring(0, (70-(all.length-note.length)));
          note=note+"...";
        }
      }
      if(a[1]>0){
        if(t==0){
          ls = ls+"<option value='"+id+"|"+st+"|"+ed+"|"+c+"' selected title='"+raw_note+"'>"+id+"&#009;"+c+"&#009;"+st+"&#045;"+ed+"&#009;"+note+"</option>";
          submit="<input type=\"submit\" id=\"prm_keyword_res\" value=\"GO\" onClick=\"_searchID(event)\"/>";
          num="Search&nbsp;results&nbsp;:&nbsp;"+a[3];
        }else{
          ls = ls+"<option value='"+id+"|"+st+"|"+ed+"|"+c+"' title='"+raw_note+"'>"+id+"&#009;"+c+"&#009;"+st+"&#045;"+ed+"&#009;"+note+"</option>";
          submit="<input type=\"submit\" id=\"prm_keyword_res\" value=\"GO\" onClick=\"_searchID(event)\"/>";
          num="Search&nbsp;results&nbsp;:&nbsp;"+a[3];
        }
        if(a[3] >= 1000){
          num="&nbsp;<font color='red'>Too&nbsp;many&nbsp;results&nbsp;were&nbsp;found.&nbsp;(Displayed&nbsp;only&nbsp;1&nbsp;to&nbsp;1000&nbsp;of&nbsp;"+a[3]+"&nbsp;results)<br>&nbsp;Try&nbsp;it&nbsp;again&nbsp;with&nbsp;other&nbsp;keywords.</font>";
        }
      } else {
        if(st=="false1"){ 
          ls = "<option value='NF' disabled>&nbsp;Note&nbsp;is&nbsp;not&nbsp;installed&nbsp;in&nbsp;TASUKE.&nbsp;&nbsp;</option>";
          submit = "<input type=\"submit\" id=\"prm_keyword_res\" value=\"GO\" disabled />";
          num="&nbsp;";
          break;
      }else{
          ls = "<option value='NF' disabled>&nbsp;Not&nbsp;found&nbsp;</option>";
          submit = "<input type=\"submit\" id=\"prm_keyword_res\" value=\"GO\" disabled />";
          num="&nbsp;";
          break;
        }
      }
      tc++;
    }
    var cr = document.getElementById("prm_keyword_res_str");
    cr.innerHTML=num;
    $('#prm_keyword_res').find('option').remove().end().append(ls);
    $('#prm_keyword_res_sb').find('input').remove().end().append(submit);
    }
  });
}

//// replace LF and CR for Search
function _delLFCR(string){
  string = string.replace( /\r\n/g , "\n" );	
  string = string.replace( /^(\n+)|(\n+)$/g , "" );
  return string
}

///////////////////////////////////////////////////////////
// Ajax: Get track&depth&variant and drawing
///////////////////////////////////////////////////////////
function _execCanvas(p,b,s) {
  var thread=4;
  var acLen = new Array();
  var acPos = new Array();
  var isScroll=false;
  var countaAc = 0;
  var mod = 0;
  var invisDatas="";
  acLen[0]=0;
  acPos[0]=1;

  if(SCRTIMER && FROMSCROLL){
    isScroll=true;
    clearTimeout(SCRTIMER);
  }
  FROMSCROLL=false;
  
  // Depth&Variants
  if (_isEmpty(p)) {
      p=localStorage.getItem("_Pos"); 
      b=localStorage.getItem("_Block"); 
  }
  baseobj=new Object(_getList("db"));

  var trc = new Object(JSON.parse(localStorage.getItem("_Tracks")));
  var blksH = localStorage.getItem("_BlockH");
  var cvsTrackH = (57+((4*blksH)*trc.length));
  if(cvsTrackH <= 57){cvsTrackH=78;}
  
  if((localStorage.getItem("_ListsTgt") || localStorage.getItem("_ListsTgt")=="") && parseInt(baseobj.length/thread) != 0){
    var visList= new Array();
     _getVisibleArea();
    visList=localStorage.getItem("_ListsTgt").split(","); 
    var visListNum=visList.length;
    if(RELOAD){
      var height = $(window).outerHeight(true)-document.body.clientHeight-cvsTrackH-123;
      visListNum = parseInt(height/parseInt(localStorage.getItem("_BlockH")));
      if(visListNum > baseobj.length){visListNum = baseobj.length;}
    }
    countaAc=parseInt(visListNum/thread);
    mod = (visListNum)%thread;
    acPos[0]=VIEWSTART;
  }else{
    var height = $(window).outerHeight(true)-document.body.clientHeight-cvsTrackH-123;
    var len = parseInt(height/parseInt(localStorage.getItem("_BlockH")));
    if(len > baseobj.length){len = baseobj.length;}
    var array= new Array();
    countaAc=parseInt(len/thread);
    mod = (len)%thread;
    array = _NgetList("db",len+1,(baseobj.length-(len)));
    invisDatas=";";
    var en=new Object(JSON.parse(localStorage.getItem("_Env")));
    if(en.cstm_track=="enabled"){
      for(var i=0; i<array.length; i++){
        invisDatas += array[i]+"|["+times("{\"dp\":\"x\",\"rdp\":\"x\"},",b).slice(0,-1)+"];";
      }
    }else{
      for(var i=0; i<array.length; i++){
        invisDatas += array[i]+"|["+times("{\"dp\":\"x\"},",b).slice(0,-1)+"];";
      }
    }
  }
  if(countaAc==0){thread=1;}
  for (var i = 1; i <= thread; i++) {
    acLen[i]=countaAc;
    if(i <= (mod)){
      acLen[i]++;
    }
    acPos[i]=acPos[i-1]+acLen[i-1];
  }

  //var invisDatas="";
  var upperArray=new Array();
  var lowerArray=new Array();
  upperArray = _NgetList("db",1,acPos[0]-1);
  lowerArray = _NgetList("db",(acPos[0]+visListNum),(baseobj.length-(acPos[0]+visListNum-1)));

  if(upperArray.length!=0 || lowerArray.length!=0){invisDatas = ";";}
  for(var i=0; i<upperArray.length; i++){
    var num=0;
    if(_getCompressedData(upperArray[i]).indexOf("{\"dp\":\"x\"}") == -1 && isScroll){
      //pass
    }else{
      invisDatas += upperArray[i]+"|["+times("{\"dp\":\"x\",\"rdp\":\"x\"},",b).slice(0,-1)+"];";
    }
  }
  if(lowerArray.length==0){invisDatas=invisDatas.slice(0,-1);}
  for(var i=0; i<lowerArray.length; i++){
    var num=0;
    if(_getCompressedData(lowerArray[i]).indexOf("{\"dp\":\"x\"}")  == -1 && isScroll){
    }else{
      invisDatas += lowerArray[i]+"|["+times("{\"dp\":\"x\",\"rdp\":\"x\"},",b).slice(0,-1)+"];";
    }
  }
  if(lowerArray.length!=0){invisDatas=invisDatas.slice(0,-1);}
  isScroll=false;
  if(thread != 1){
    var jqXHRList = [];
    _drawProgress(100,1);
    jqXHRList.push($.ajax({
      url: "./bin/"+_backendSelector("track.php"),
      type: "GET",
      cache: false,
      data: {
        "prm_Zoom":localStorage.getItem("_Zoom"),
        "prm_Chr":localStorage.getItem("_Chr"),
        "prm_Pos":localStorage.getItem("_Pos"),
        "prm_Block":localStorage.getItem("_Block"),
        "prm_Tracks":new Object(_getTrack("list"))
        }
    }
    ));
    for (var i = 1; i <= thread; i++) {
      jqXHRList.push($.ajax({ 
        url: "./bin/"+_backendSelector("data.php"),
        type: "POST",
        cache: false,
        data: {
        "prm_Ref":localStorage.getItem("_Ref"),
        "prm_width":localStorage.getItem("_BlockW"),
        "prm_Zoom":localStorage.getItem("_Zoom"),
        "prm_Chr":localStorage.getItem("_Chr"),
        "prm_Pos":p,
        "prm_QUAL":localStorage.getItem("_QUAL"),
        "prm_DP":localStorage.getItem("_DP"),
        "prm_DP4":localStorage.getItem("_DP4"),
        "prm_Block":b,
        "prm_Lists":new Object(_NgetList("db",acPos[i],acLen[i]))
        }
      }
      ));
    }
    $.when.apply($, jqXHRList).done(function () {
      var datas = [];
      var statuses = [];
      var jqXHRResultList = [];
      var trdatas = [];
      var trstatuses = [];
      var trjqXHRResultList = [];
      var trresult = arguments[0];
      trdatas.push(trresult[0]);
      trstatuses.push(trresult[1]);
      trjqXHRResultList.push(trresult[3]);
      var n=trdatas[0].split("|");
      var dvdata="";
      
      for (var i=0; i<_getTrack("list").length;i++){
	n[i] = n[i].replace(/---/g,"\|");
        localStorage.setItem("_Track_"+i, n[i]);
      }
      if ( localStorage.getItem("_Zoom") == '1b' ) {
        localStorage.setItem("_FASTA", n[n.length-1]);
      }
      for (var i = 1; i < thread+1; i++) {
        var result = arguments[i];
        datas.push(result[0]);
        statuses.push(result[1]);
        jqXHRResultList.push(result[3]);
      }
      for (var i = 0; i < arguments.length-1; i++) {
        if(i==0){
          dvdata=datas[i];
        }else{
          dvdata=dvdata+";"+datas[i];
        }
      }
      dvdata += invisDatas;
      for(var x=0; x<timerArray.length; x++){	clearInterval(timerArray.shift());} // animation
      var d=dvdata.replace(/^\s+|\s+$/g, "");
      if (_isEmpty(s)) {
        _setData(d);
      } else {
        _setData_p(d,s,b);
      }
      _drawCanvas();
      DATAPFLAG=false;
      localStorage.setItem("_ListsTgt","");
      clearTimeout(PROGRESSTIMER);
      setTimeout("_drawProgress('100')",100);
      setTimeout(_closeLoadingDialog,500);
    });
  }else{
    _drawProgress(100,1);
    $.ajax({
      url: "./bin/"+_backendSelector("track.php"),
      type: "GET",
      cache: false,
      async: false,
      data: {
        "prm_Zoom":localStorage.getItem("_Zoom"),
        "prm_Chr":localStorage.getItem("_Chr"),
        "prm_Pos":localStorage.getItem("_Pos"),
        "prm_Block":localStorage.getItem("_Block"),
        "prm_Tracks":new Object(_getTrack("list"))
      },
      success: function(datas) {
        var n=datas.split("|");
        for (i=0; i<_getTrack("list").length;i++){
          localStorage.setItem("_Track_"+i, n[i]);
        }
        if ( localStorage.getItem("_Zoom") == '1b' ) {
          localStorage.setItem("_FASTA", n[n.length-1]);
        }
      }
    });
    $.ajax({
      url: "./bin/"+_backendSelector("data.php"),
      type: "POST",
      cache: false,
      data: {
        "prm_Ref":localStorage.getItem("_Ref"),
        "prm_width":localStorage.getItem("_BlockW"),
        "prm_Zoom":localStorage.getItem("_Zoom"),
        "prm_Chr":localStorage.getItem("_Chr"),
        "prm_Pos":p,
        "prm_QUAL":localStorage.getItem("_QUAL"),
        "prm_DP":localStorage.getItem("_DP"),
        "prm_DP4":localStorage.getItem("_DP4"),
        "prm_Block":b,
        "prm_Lists":new Object(_getList("db"))
      },
      success: function(datas) {
        var d=datas.replace(/^\s+|\s+$/g, "");
        if (_isEmpty(s)) {
          _setData(d);
        } else {
          _setData_p(d,s,b);
        }
        for(var x=0; x<timerArray.length; x++){	clearInterval(timerArray.shift());} // animation
        _drawCanvas();
        DATAPFLAG=false;
        localStorage.setItem("_ListsTgt","");
        clearTimeout(PROGRESSTIMER);
        setTimeout("_drawProgress('100')",100);
        setTimeout(_closeLoadingDialog,500);
      }
    });
  }
  clearTimeout(BUSYDETECTTIMER);
}

function _NgetList(str,num,count) {
  var a=new Array();
  var o=new Object(JSON.parse(localStorage.getItem("_Lists")));
  var acCount=0;
  var start=parseInt(num-1);
  var end=parseInt(num-1+count);
  for(var i=start;i<end;i++){
    if(!_isUndefined(o[i])){
      if(str=="id"){
        a[acCount]=o[i].id;
      }else if(str=="db"){
        a[acCount]=o[i].db;
      }else if(str=="name"){
        a[acCount]=o[i].name;
      }else if(str=="grp"){
        a[acCount]=o[i].grp;
      }else if(str=="variety"){
        a[acCount]=o[i].variety;
      }else if(str=="origin"){
        a[acCount]=o[i].origin;
      }else if(str=="type"){
        a[acCount]=o[i].type;
      }
      acCount++;
    }else{
      //console.log(i+" is undefined");
    }
  }
  return a;
}

function _sessionStart(){
  var runP3Res = document.getElementById("run_p3_res");
  var runP3Hist = document.getElementById("run_p3_hist");
  $.ajax({
    url: "./bin/session.php",
    type: "POST",
    cache: false,
    data: {
    "init":"load",
    "string":"1"
    },
    success: function(data) {
      array=data.split("---SPLIT---");
      if(array[3]=="true"){
        runP3Hist.innerHTML=array[2];
        runP3Res.innerHTML="";
      }else if(array[3]=="false"){
        var resTblStr = "<hr><table class=\"fontCourierNew\" style=\"margin-left:150px;\" cellspacing=\"0\"  width=\"60%\"><tr><td>";
        var resTblEnd = "</td></tr></table>";
        runP3Res.innerHTML=resTblStr+"<img src=\"./images/loader.gif\" alt=\"Running...\" style=\"\" />Running Primer3, you can close this dialog."+resTblEnd;
      }else{
        runP3Res.innerHTML="";
      }
    }
  });
}

///////////////////////////////////////////////////////////
// Exporting/importing Accession list
///////////////////////////////////////////////////////////
function _downloadAccList(){
  var l = new Object(JSON.parse(localStorage.getItem('_Lists')));
  var str = "";
  var Time = new Date();
  var timePrint = Time.getFullYear()+"_"+(Time.getMonth()+1)+"_"+Time.getDate();
  var fileName="AccessionList_"+timePrint+".txt";
  
  for (var i=0;i<l.length;i++){
    if ( Objects.Name == "id" ) {
      str += l[i].id;
    } else {
      str += l[i].name;
    }
    if(i != (l.length-1)){str += "\n";}
  }
  _download(str,fileName);
}

var extAccList = new Array();
function _validateAccList(files){
  var elm = document.getElementById("list_upfile_msg");
  var lists = new Object(JSON.parse(localStorage.getItem('_Lists-origin')));
  var limit = 10000000;
  var accArray = new Array();
  var reader = new FileReader();
  document.getElementById("prm_list_up").disabled = true;
  
  if(!_isUndefined(files[0])){
    if(files[0].type != "text/plain"){
      elm.innerHTML="<font color='red'>Invalid file</font>"
      files[0].value = '';
      return;
    }
    if(files[0].size > limit){
      elm.innerHTML="<font color='red'>Too large!</font>"
      files[0].value = '';
      return;
    }
    
    reader.readAsText(files[0],"utf-8");
    reader.onload = function(ev){
      var accKeys = new Array();
      var validated = new Array();
      accArray = reader.result.split("\n");
      for (var i=0;i<lists.length;i++){
        if ( Objects.Name == "id" ) {
          accKeys[lists[i].id]=1;
        } else {
          accKeys[lists[i].name]=1;
        }
      }
      for (var a=0;a<accArray.length;a++){
        if (accArray[a] in accKeys) {
          validated.push(accArray[a]);
        }
      }
      extAccList = validated;
      document.getElementById("prm_list_up").disabled = false;
    }
  }
}

function _uploadAccList(){
  var elm = document.getElementById("list_upfile_msg");
  var lists = new Object(JSON.parse(localStorage.getItem('_Lists-origin')));
  var ret = "[";
  var deleted = "[";
  var numdel = 0;
  var keys = new Array();
  
  if(extAccList.length != 0){
    for (var i=0;i<extAccList.length;i++){
      for (var a=0;a<lists.length;a++){
        if(lists[a].id == extAccList[i] || lists[a].name == extAccList[i]){
          ret += JSON.stringify(lists[a])+",";
          keys[extAccList[i]] = 1;
        }
      }
    }
    for (var a=0;a<lists.length;a++){
      if ( Objects.Name == "id" ) {
        if(!(lists[a].id in keys)){
          deleted += JSON.stringify(lists[a])+",";
          numdel++;
        }
      }else{
        if(!(lists[a].name in keys)){
          deleted += JSON.stringify(lists[a])+",";
          numdel++;
        }
      }
    }
    ret = ret.substring(0, ret.length - 1);
    if(numdel>0){deleted = deleted.substring(0, deleted.length - 1);}
    ret += "]";
    deleted += "]";
    extAccList =new Array();
    localStorage.setItem("_Lists",ret);
    localStorage.setItem("_ListsDeleted",deleted);
    elm.innerHTML="";
    _showLoading();
    _execCanvas();
    _dialog_list();
  }else{
    elm.innerHTML="<font color='red'>Valid accessions were not found.</font>";
    return;
  }
}

///////////////////////////////////////////////////////////
// Phylogenetic tree
///////////////////////////////////////////////////////////
function _runPhylogen(){
  var chr = document.getElementById("prm_phy_chr");
  var st = document.getElementById("prm_phy_s");
  var ed = document.getElementById("prm_phy_e");
  var ajaxloader = document.getElementById("phy_ajaxloader");
  var res = document.getElementById("phy_result");
  var cds = 0;

  if(document.getElementById("prm_phy_gene").checked){cds = document.getElementById("prm_phy_gene").value;}
  ajaxloader.innerHTML="<img src=\"./images/loader.gif\" alt=\"Running...\" style=\"\" />Running...";
  res.innerHTML="";
  $.ajax({
    url: "./bin/"+_backendSelector("dnadist.php"),
    type: "POST",
    cache: false,
    data: {
      "prm_phy_chr":document.getElementById("prm_phy_chr").value,
      "prm_phy_s":document.getElementById("prm_phy_s").value,
      "prm_phy_e":document.getElementById("prm_phy_e").value,
      "prm_phy_qual":document.getElementById("prm_phy_qual").value,
      "prm_phy_dp":document.getElementById("prm_phy_dp").value,
      "prm_phy_list":document.getElementById("prm_phy_list").value,
      "prm_phy_cri":document.getElementById("prm_phy_cri").value,
      "prm_phy_gene":cds,
      "prm_phy_objid":document.getElementById("prm_phy_objid").value,
      "prm_phy_grp":Objects.NameSub
    },
    success: function(data) {
      ajaxloader.innerHTML = "";
      var datas = data.split("|");
      if(datas[2]){
        res.innerHTML = _escapeHTML(datas[2]);
        return;
      }
      var Time = new Date();
      var timePrint = Time.getFullYear()+"_"+(Time.getMonth()+1)+"_"+Time.getDate();
      var fileName=_escapeHTML(chr.value)+"_"+st.value+"b-"+ed.value+"b_"+timePrint+".nwk";
      res.innerHTML = _genPhyResult(data,fileName);
      showtree('newick','phy_svg');
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      ajaxloader.innerHTML = XMLHttpRequest.statu+" Error";
    }
  });
}

var DLDATA = "";
var DLNAME = "";
function _genPhyResult(data,fileName){
  var retString = "";
  var selectbox = "";
  var ret = data.split("|");
  var accessions = ret[0].split(",");
  DLDATA = ret[1];
  DLNAME = fileName;
  
  for(var i=0; i<accessions.length; i++){
    selectbox += "<option>"+accessions[i]+"</option>";
  }
  retString +=  "<hr>"+
                "<div height='100%' width='100%' style='text-align:left;'>"+
                "<font color='#008000'>The analysis has been finished!</font>"+
                "<table width='100%'>"+
                "<tr>"+
                "<td width='25%' align='left' style='padding-right:20px;'>"+
                "Sorted accessions"+
                "<select size='15' id='phy_acc_order' style='width:100%;font-family:Courier;'>"+
                selectbox+
                "</select>"+
                "</td>"+
                "<td width='75%'>"+
                "<select id='style'>"+
                "<option value='phylogram' selected='true'>Phylogram</option>"+
                "<option value='circlephylogram'>Circle phylogram</option>"+
                "<option value='cladogram'>Cladogram</option>"+
                "</select>"+
                "<button onclick=\"showtree('newick','phy_svg')\">Show</button>"+
                "<div id='phy_tree_res' style='height:230px; background-color:white; border:1px solid #cccccc;'>"+
                "<svg id='phy_svg' xmlns='http://www.w3.org/2000/svg' version='1.1' height='100%' width='100%'>"+
                "<g id='viewport'></g>"+
                "</svg>"+
                "</div>"+
                "</td>"+
                "</tr>"+
                "<tr>"+
                "<td>"+
                "<button id='phy_sorted' type='submit' onclick='_sortAccByPhylip();'>Apply now</>"+
                "</td>"+
                "<td>"+
                "<button type='submit' onClick='_indirDownload();'>Download</>"+
                "</td>"+
                "</tr>"+
                "</table>";
  $("#newick").val(DLDATA);
  return retString;
}

function _sortAccByPhylip(){
  var elm = document.getElementById("phy_acc_order");
  var acc = new Array();
  var sortedAcc = new Array();
  var ret = "[";
  var o = new Object(JSON.parse(localStorage.getItem("_Lists")));
  
  for(var i=0;i<o.length;i++){
    acc[o[i].id] = o[i];
  }
  for (var x=0;x<elm.options.length;x++) {
    if(elm.options[x].value in acc){
      sortedAcc.push(JSON.stringify(acc[elm.options[x].value]));
    }
  }
  ret += sortedAcc.join(",");
  ret += "]";
  localStorage.setItem("_Lists",ret);
  _showLoading();
  localStorage.removeItem("_ListsTgt");
  FROMSCROLL=false;
  _windowGffClose();
  _execCanvas();
}

///////////////////////////////////////////////////////////
// Exporting FASTA
///////////////////////////////////////////////////////////
function _genFasta(){
  var chr = document.getElementById("prm_fa_chr");
  var st = document.getElementById("prm_fa_s");
  var ed = document.getElementById("prm_fa_e");
  var ajaxloader = document.getElementById("fa_ajaxloader");

  ajaxloader.innerHTML="<img src=\"./images/loader.gif\" alt=\"Exporting...\" style=\"\" />Exporting...";
  $.ajax({
    url: "./bin/"+_backendSelector("fasta.php"),
    type: "POST",
    cache: false,
    data: {
      "prm_fa_chr":chr.value,
      "prm_fa_s":st.value,
      "prm_fa_e":ed.value,
      "prm_fa_tgt":document.getElementById("prm_fa_tgt").value,
      "prm_fa_qual":document.getElementById("prm_fa_qual").value,
      "prm_fa_dp":document.getElementById("prm_fa_dp").value,
      "prm_fa_list":document.getElementById("prm_fa_list").value,
      "prm_fa_name":document.getElementById("prm_fa_name").value,
      "prm_fa_nameS":document.getElementById("prm_fa_nameS").value,
      "prm_fa_ref":document.getElementById("prm_fa_ref").value,
      "prm_fa_width":document.getElementById("prm_fa_width").value,
      "prm_fa_avd":document.getElementById("prm_fa_avd").value,
      "prm_fa_p3prm":"",
      "prm_fa_Ns":document.getElementById("prm_fa_Ns").value,
      "prm_type":"a"
    },
    success: function(data) {
      ajaxloader.innerHTML="";
      var Time = new Date();
      var timePrint = Time.getFullYear()+"_"+(Time.getMonth()+1)+"_"+Time.getDate();
      var fileName=_escapeHTML(chr.value)+"_"+st.value+"b-"+ed.value+"b_"+timePrint+".fasta";
      _download(data,fileName);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      ajaxloader.innerHTML=XMLHttpRequest.statu+" Error";
    }
  });
}

///////////////////////////////////////////////////////////
// Exporting CSV
///////////////////////////////////////////////////////////
function _genCSV(){
  var chr = document.getElementById("prm_csv_chr");
  var st = document.getElementById("prm_csv_s");
  var ed = document.getElementById("prm_csv_e");
  var ajaxloader = document.getElementById("csv_ajaxloader");

  ajaxloader.innerHTML="<img src=\"./images/loader.gif\" alt=\"Exporting...\" style=\"\" />Exporting...";
  $.ajax({
    url: "./bin/"+_backendSelector("csv.php"),
    type: "POST",
    cache: false,
    data: {
      "prm_csv_chr":chr.value,
      "prm_csv_s":st.value,
      "prm_csv_e":ed.value,
      "prm_pos_id":document.getElementsByName("prm_pos_id")[0].value,
      "prm_csv_qual":document.getElementById("prm_csv_qual").value,
      "prm_csv_dp":document.getElementById("prm_csv_dp").value,
      "prm_csv_list":document.getElementById("prm_csv_list").value,
      "prm_csv_keyword":document.getElementsByName("prm_csv_keyword")[0].value
    },
    success: function(data) {
      ajaxloader.innerHTML="";
      var Time = new Date();
      var timePrint = Time.getFullYear()+"_"+(Time.getMonth()+1)+"_"+Time.getDate();
      var fileName=_escapeHTML(chr.value)+"_"+st.value+"b-"+ed.value+"b_"+timePrint+".csv";
      _download(data,fileName);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      console.log("x");
      ajaxloader.innerHTML=XMLHttpRequest.statu+" Error";
    }
  });
}

///////////////////////////////////////////////////////////
// Gen p3
///////////////////////////////////////////////////////////
function _genPrimer3Query(){
  var chr = document.getElementById("prm_p3_chr");
  var flk = document.getElementById("prm_p3_flk");
  var st = document.getElementById("prm_p3_s");
  var ed = document.getElementById("prm_p3_e");
  var tgt = document.getElementById("prm_p3_tgt");
  var dp = document.getElementById("prm_p3_dp");
  var q = document.getElementById("prm_p3_qual");
  var variant = document.getElementById("prm_p3_var");
  var tgte = document.getElementById("prm_p3_tgt_e");
  //var li = document.getElementById("prm_p3_list");
  var avd = document.getElementById("prm_p3_avd");
  var res = document.getElementById("p3_query_res");
  var p3Ns = document.getElementById("prm_p3_Ns");
  var chrv = _escapeHTML(chr.value);
  var tgtv = parseInt(tgt.value);
  var tgtev = parseInt(tgte.value);	
  //accession[0] = li.value; //for genarate each accession-based sequence. (disabled)
  var fileName = "";

  $.ajax({
    url: "./bin/"+_backendSelector("fasta.php"),
    type: "POST",
    cache: false,
    data: {
      "prm_fa_chr":chrv,
      "prm_fa_s":parseInt(st.value),
      "prm_fa_e":parseInt(ed.value),
      "prm_fa_tgt":parseInt(tgt.value)+"-"+parseInt(tgte.value),
      "prm_fa_qual":q.value,
      "prm_fa_dp":dp.value,
      "prm_fa_var":variant.value,
      //"prm_fa_list":accession[0],
      "prm_fa_list":_getList("db").toString(),
      "prm_fa_name":localStorage.getItem("_Name"),
      "prm_fa_nameS":localStorage.getItem("_NameSub"),
      "prm_fa_ref":"REFERENCE",
      "prm_fa_width":"80",
      "prm_fa_avd":parseInt(avd.value),
      "prm_fa_p3prm":"",
      "prm_fa_Ns":p3Ns.value,
      "prm_type":"b"
    },
    success: function(data) {
      res.innerHTML="<hr><br>"+data;
    }
  });
}

///////////////////////////////////////////////////////////
// Run Primer3 (Supports v2.3.x)
///////////////////////////////////////////////////////////
function _runPrimer3(){
  var chr = document.getElementById("prm_rp3_chr");
  var flk = document.getElementById("prm_rp3_flk");
  var st = document.getElementById("prm_rp3_s");
  var ed = document.getElementById("prm_rp3_e");
  var tgt = document.getElementById("prm_rp3_tgt");
  var dp = document.getElementById("prm_rp3_dp");
  var q = document.getElementById("prm_rp3_qual");
  var variant = document.getElementById("prm_rp3_var");
  var tgte = document.getElementById("prm_rp3_tgt_e");
  var avd = document.getElementById("prm_rp3_avd");
  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 p3Ns = document.getElementById("prm_rp3_Ns");
  var runP3Res = document.getElementById("run_p3_res");
  var runP3Hist = document.getElementById("run_p3_hist");
  var chrv = _escapeHTML(chr.value);
  var tgtv = parseInt(tgt.value);
  var tgtev = parseInt(tgte.value);	
  var fileName = "";


  var p3Params = prdmi.value+","+prdmx.value+","+sizeopt.value+","+sizmax.value+","+sizmin.value+","
      +tmopt.value+","+tmmx.value+","+tmmi.value+","+tmdif.value+","+lowmsk.value;
  var resTblStr = "<hr><table class=\"fontCourierNew\" style=\"margin-left:150px;\" cellspacing=\"0\"  width=\"60%\"><tr><td>";
  var resTblEnd = "</td></tr></table>";
  runP3Res.innerHTML = resTblStr+"<img src=\"./images/loader.gif\" alt=\"Running...\" style=\"\" />Running Primer3, you can close this dialog."+resTblEnd;

  $.ajax({
    url: "./bin/"+_backendSelector("fasta.php"),
    type: "POST",
    cache: false,
    data: {
      "prm_fa_chr":chrv,
      "prm_fa_s":parseInt(st.value),
      "prm_fa_e":parseInt(ed.value),
      "prm_fa_tgt":parseInt(tgt.value)+"-"+parseInt(tgte.value),
      "prm_fa_qual":q.value,
      "prm_fa_dp":dp.value,
      "prm_fa_var":variant.value,
      "prm_fa_list":_getList("db").toString(),
      "prm_fa_name":localStorage.getItem("_Name"),
      "prm_fa_nameS":localStorage.getItem("_NameSub"),
      "prm_fa_ref":"REFERENCE",
      "prm_fa_width":"80",
      "prm_fa_avd":parseInt(avd.value),
      "prm_fa_p3prm":p3Params,
      "prm_fa_Ns":p3Ns.value,
      "prm_type":"c"
    },
    success: function(data) {
      var date = new Date();
      var array=data.split("---SPLIT---");
      var resTblStr = "<table class=\"fontCourierNew\" style=\"margin-left:75px;\" cellspacing=\"0\"  width=\"80%\"><tr><td>";
      var resTblEnd = "</td></tr></table>";
      fileName=chrv+"_"+parseInt(tgt.value)+"_"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
      var target = fileName.split("_");
      var message = "<strong>Your request: "+target[0]+" "+target[1]+"</strong><br><font color='#008000'>Primer designing has been finished!</font><br><br>";
      var resCont = "You can download the result from this button ->\
          <button type=\"submit\" name=\"prm_rp3_submit\" onclick=\"_getP3Result();\">Download</button>";
      runP3Res.innerHTML="";
      if(array[0].match(/^Error/)){
        runP3Res.innerHTML=array[0]+"<br>";
        return;
      }
      if(array[1]=="Cookies"){resCont="Cookies Required: Cookies are not enabled on your browser.";}
      var rtnP3Array = array[1].split("--split--");
      var rtnTblStr = "<table class=\"fontCourierNew\" width=\"585px\"style=\"margin-left:60px;\" cellspacing=\"0\" border=\"1\" ><tr><td>";
      var rtnTblEnd = "</td></tr></table><br>";
      var lPrmList = rtnP3Array[1].split("-");
      var rPrmList = rtnP3Array[2].split("-");
      var lPrm = lPrmList[0].split(":");
      var rPrm = rPrmList[0].split(":");
      var rtnSeqArray = rtnP3Array[0].split("");
      var t = lPrmList.length;
      var prmCand="";
      for(var i=0; i<t; i++){
        var eachLPrm = lPrmList[i].split(":");
        var eachRPrm = rPrmList[i].split(":");
        if(!eachLPrm[0]){
          prmCand="<strong>NO PRIMERS FOUND</strong><br>";
          break;
        }
        if(i==0){
          prmCand = prmCand+"<input type=\"radio\" name=\"chPrimer\" value=\""+eachLPrm[0]+":"+eachLPrm[1]+":"+eachRPrm[0]+":"+eachRPrm[1]+":"+i+"\" checked=\"checked\" onclick=\"_switchP3Result();\">&nbsp;Left:&nbsp;"+eachLPrm[2]+"&nbsp;&nbsp;&nbsp;Right:&nbsp;"+eachRPrm[2]+"<br>";
        }else{
          prmCand = prmCand+"<input type=\"radio\" name=\"chPrimer\" value=\""+eachLPrm[0]+":"+eachLPrm[1]+":"+eachRPrm[0]+":"+eachRPrm[1]+":"+i+"\" onclick=\"_switchP3Result();\" />&nbsp;Left:&nbsp;"+eachLPrm[2]+"&nbsp;&nbsp;&nbsp;Right:&nbsp;"+eachRPrm[2]+"<br>";
        }
      }
      prmCand= prmCand+"<br>";
      
      var y = rtnSeqArray.length;
      var strCount = 0;
      var strRealCount = 0;
      var pointer = 0;
      var tag = "false";
      for(var x=0; x<y; x++){
        strRealCount++;
        if(rtnSeqArray[x].match(/</)){
          tag = "true";
        }
        if(tag == "true"){
          if(rtnSeqArray[x].match(/>/)){
            tag = "false";
          }
        }else{
          if(rtnSeqArray[x].match(/[ATGCNWSMKRYBDHVatgcnwsmkrybdhv]/)){
            strCount++;
            pointer=0;
            if(rtnSeqArray[x+1]=="<" && rtnSeqArray[x+2]=="/"){pointer=7;}//</font> +7
            if(strCount == lPrm[0]){
              rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"<font color='#ff6699'>";
            }else if(strCount == parseInt(lPrm[0])+parseInt(lPrm[1])){
              rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"</font>";
            }
            else if(strCount == parseInt(rPrm[0])-parseInt(rPrm[1])+1){
              rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"<font color='#0099ff'>";
            }
            else if(strCount == parseInt(rPrm[0])+1){
              rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"</font>";
            }
          }else{
            console.log("Unexpected char");
          }
        }
      }
      var rtnP3 = rtnTblStr+"<span id=\"resSeq\"><!--:-->"+rtnSeqArray.join("")+"<!--:--></span>"+rtnTblEnd;
      runP3Res.innerHTML="<hr>"+resTblStr+message+prmCand+resTblEnd+rtnP3+resTblStr+resCont+resTblEnd;
      _storeP3Res(fileName+"---SPLIT---"+array[0]+"---SPLIT---"+"<hr>"+resTblStr+message+prmCand+resTblEnd+""+rtnP3+""+resTblStr+resCont+resTblEnd);
      runP3Hist.innerHTML="<hr><div align=\"center\"><p><strong>Previous result was overwritten with latest one.</align></strong></p></div>";
    }
  });
}

///////////////////////////////////////////////////////////
// store primer3 result with $_SESSION
///////////////////////////////////////////////////////////
function _storeP3Res(string){
  var runP3Res = document.getElementById("run_p3_res");
  $.ajax({
    url: "./bin/session.php",
    type: "POST",
    async: false,
    cache: false,
    data: {
      "init":"storeP3Res",
      "string":string
    },
    success: function(data) {
      //console.log("stored:"+data);
    }
  });
}

function _getP3Result(){
  var chr = document.getElementById("prm_rp3_chr");
  var tgt = document.getElementById("prm_rp3_tgt");
  $.ajax({
    url: "./bin/session.php",
    type: "POST",
    async: false,
    cache: false,
    data: {
      "init":"load",
      "string":"1"
    },
    success: function(data) {
      array=data.split("---SPLIT---");
      if(array[3]=="true"){
        fileName=array[0];
        _download(array[1],fileName);
      }
    }
  });
}

///////////////////////////////////////////////////////////
// Switching primer position
///////////////////////////////////////////////////////////
function _switchP3Result(){
  var resSeq = document.getElementById("resSeq");
  var radioList = document.getElementsByName("chPrimer");
  var radioListLen = radioList.length;
  var primerPos = "";
  for(var i=0; i<t; i++){
    if (radioList[i].checked) {
      primerPos = radioList[i].value;
      break;
    }
  }
  var primerPosArray = primerPos.split(":");
  $.ajax({
    url: "./bin/session.php",
    type: "POST",
    cache: false,
    data: {
      "init":"load",
      "string":"1"
    },
    success: function(data) {
      array=data.split("---SPLIT---");
      if(array[3]=="true"){
        var splitedArray = array[2].split("<!--:-->");
        var seqarray = splitedArray[1].split("");
        var seq = seqarray.join("");
        seq = seq.replace(/<br>/g, "@");
        seq = seq.replace(/(.*)<font color='#ff6699'>([@\s\n\rATGCNWSMKRYBDHVatgcnwsmkrybdhv]*)<\/font>(.*)/, "$1$2$3");
        seq = seq.replace(/(.*)<font color='#0099ff'>([@\s\n\rATGCNWSMKRYBDHVatgcnwsmkrybdhv]*)<\/font>(.*)/, "$1$2$3");
        seq = seq.replace(/@/g, "<br>");
        var rtnSeqArray = seq.split("");
        var y = rtnSeqArray.length;
        var strCount = 0;
        var strRealCount = 0;
        var pointer = 0;
        var tag = "false";
        for(var x=0; x<y; x++){
          strRealCount++;
          if(rtnSeqArray[x].match(/</)){
            tag = "true";
          }
          if(tag == "true"){
            if(rtnSeqArray[x].match(/>/)){
              tag = "false";
            }
          }else{
            if(rtnSeqArray[x].match(/[ATGCNWSMKRYBDHVatgcnwsmkrybdhv]/)){
              strCount++;
              pointer=0;
              if(rtnSeqArray[x+1]=="<" && rtnSeqArray[x+2]=="/"){pointer=7;}//</font> +7
              if(strCount == primerPosArray[0]){
                rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"<font color='#ff6699'>";
              }else if(strCount == parseInt(primerPosArray[0])+parseInt(primerPosArray[1])){
                rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"</font>";
              }
              else if(strCount == parseInt(primerPosArray[2])-parseInt(primerPosArray[3])+1){
                rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"<font color='#0099ff'>";
              }
              else if(strCount == parseInt(primerPosArray[2])+1){
                rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"</font>";
              }
            }else{
              console.log("Unexpected char");
            }
          }	
        }
        resSeq.innerHTML=rtnSeqArray.join("");
      }else if(array[3]=="false"){
        resSeq.innerHTML="";
      }else{
        //pass
      }
    }
  });
}

///////////////////////////////////////////////////////////
// File download
///////////////////////////////////////////////////////////
function _download(content,name){
  dlTarget=new Blob([content],{type:"text/plain"});
  var a = document.createElement("a");
  a.download = name;
  a.href = window.URL.createObjectURL(dlTarget);
  e = document.createEvent('MouseEvent');
  e.initEvent("click",true,true);
  a.dispatchEvent(e);
}

function _indirDownload(){
  _download(DLDATA,DLNAME);
}

///////////////////////////////////////////////////////////
// Double click for zoom in
///////////////////////////////////////////////////////////
function _execDblClick(x) {
  if(_cvtZoom(Objects.Zoom)>1){
    var t=parseInt(x/Objects.BlockW);
    if (t==0) t=1;
    var b=(parseInt(Objects.Pos)+t)*_cvtZoom(Objects.Zoom);
    var p=_checkPos(parseInt(b/_cvtZoom(_cvtZoomDown(Objects.Zoom)))-(Objects.Block/2)+1,_cvtZoomDown(Objects.Zoom));
    localStorage.setItem("_Pos", new String(p));
    localStorage.setItem("_Zoom", _cvtZoomDown(Objects.Zoom));
    _showLoading();
    _drawMessageOnScreen("zoomInPos",x);
    _messageOnScreen("Zoom in "+Objects.Zoom+" to "+_cvtZoomDown(Objects.Zoom)+" per block");
    FROMSCROLL=false;
    _execCanvas();
  } else {
    _messageOnScreen("Minimum zoom scale");
  }
  // Unlink cell information
  if($("#dialog_infocell").hasClass("ui-dialog-content")){
   $("#dialog_infocell").dialog("close");
  }
}

///////////////////////////////////////////// Get chromosome
function _getChr(id) {
  var a=new Object();
  var o=new Object(JSON.parse(localStorage.getItem("_Chrs")));
  if (_isEmpty(id)) {
    a.id=o[0].id;
    a.size=o[0].size;
    a.centromere=o[0].centromere;
  } else if (id == "max") {
    a.size=0;
    for(i=0;i<o.length;i++){
      if(parseInt(o[i].size)>parseInt(a.size)){
        a.size=o[i].size;
      }
    }
  } else {
    for(i=0;i<o.length;i++){
      if(o[i].id==id){
        a.id=o[i].id;
        a.size=o[i].size;
        a.centromere=o[i].centromere;
        break;
      }
    }
  }
  return a;
}
///////////////////////////////////////////// Get list of accession by mode
function _getList(str) {
  var a=new Array();
  var o=new Object(JSON.parse(localStorage.getItem("_Lists")));
  for(var i=0;i<o.length;i++){
    if(str=="id"){
      a[i]=o[i].id;
    }else if(str=="db"){
      a[i]=o[i].db;
    }else if(str=="name"){
      a[i]=o[i].name;
    }else if(str=="grp"){
      a[i]=o[i].grp;
    }else if(str=="variety"){
      a[i]=o[i].variety;
    }else if(str=="origin"){
      a[i]=o[i].origin;
    }else if(str=="type"){
      a[i]=o[i].type;
    }
  }
  return a;
}

///////////////////////////////////////////// Get list of tracks
function _getTrack(str) {
  var s=0;
  var a=new Array();
  var o=new Object(JSON.parse(localStorage.getItem("_Tracks")));
  if (str=="list") {
    for(var i=0;i<o.length;i++){
      a[i]=o[i].track;
    }
    return a;
  }
  if ( str=="view" ) {
    for(var i=0;i<o.length;i++){
      if (o[i].p==1){
        a.push(o[i].track);
      }
    }
    return a;
  }
}

///////////////////////////// Set accession data to localStorage
function _setData(str) {
  var n=str.split(";");
  for (var i=0; i<n.length; i++) {
     var a=n[i].split("|");
     _setCompressedData(a[0], a[1]); // Rewrite if exists
  }
}

///////////////////////////// Hide loading 
function _hideLoading() {
  document.body.style.cursor = "default";
  _initEvents();
}

///////////////////////////// Show loading 
function _showLoading() {
  document.body.style.cursor = "wait";
  _removeEvents();
}

///////////////////////////// Moving head or tail
function _moveEdge(pos) {
  if ( pos == "s" ) {
    localStorage.setItem("_Pos", "1");
    msg="head";
  } else { 
    localStorage.setItem("_Pos",new String(_last(Objects.Zoom)-Objects.Block+1));
    msg="last";
  } 
  _showLoading();
  _messageOnScreen("Moving "+msg+" of "+Objects.Chr);
  FROMSCROLL=false;
  _execCanvas();
}

///////////////////////////// Moving page
function _movePage(str) {
  var p=Objects.Pos;
  var b=Objects.Block;
  var msg;
  if (str == "+") {
    var c=0;
    if ((p+b+b-1)>_last(Objects.Zoom)) {
      localStorage.setItem("_Pos",new String(_last(Objects.Zoom)-b+1));
    } else {
      localStorage.setItem("_Pos", new String(p+b));
    }
    msg="right";
  } else {
    if (p-b<1) {
      localStorage.setItem("_Pos", new String(1));
    } else {
      localStorage.setItem("_Pos", new String(p-b));
    }
    msg="left";
  }
  _setHistory("position,"+Objects.Chr+","+p+","+Objects.Zoom);
  _drawMessageOnScreen(msg);
  _showLoading();
  FROMSCROLL=false;
  _execCanvas();
}

///////////////////////////// Initialize canvas with size
function _initCanvas() {
  cvs0.width=Objects.titleWidth;
  cvs0.height=Objects.TrackH;
  ctx0.fillRect(0,0,cvs0.width, cvs0.height);
  ctx0.setTransform(1, 0, 0, 1, 0, 0);
  ctx0.font="11px 'Courier'";

  cvs1.width=Objects.canvasWidth;
  cvs1.height=Objects.TrackH;
  ctx1.fillRect(0,0,cvs1.width, cvs1.height);
  ctx1.setTransform(1, 0, 0, 1, 0, 0);
  ctx1.font="11px 'Courier'";

  cvs2.width=Objects.canvasWidth;
  cvs2.height=Objects.NavH;
  ctx2.fillRect(0,0,cvs2.width, cvs2.height);
  ctx2.setTransform(1, 0, 0, 1, 0, 0);
  ctx2.font="11px 'Century'";

  cvs3.width=Objects.titleWidth;
  cvs3.height=Objects.canvasHeight;
  ctx3.fillRect(0,0,cvs3.width,cvs3.height);
  ctx3.setTransform(1, 0, 0, 1, 0, 0);
  ctx3.font="11px 'Courier'";

  cvs4.width=Objects.canvasWidth;
  cvs4.height=Objects.canvasHeight;
  ctx4.fillStyle="#ffffff";
  ctx4.fillRect(0,0,cvs4.width,cvs4.height);
  ctx4.setTransform(1, 0, 0, 1, 0, 0);
  ctx4.font="10px 'Courier'";

  cvs5.width=Objects.titleWidth;
  cvs5.height=20;
  ctx5.fillStyle=_setColor().bgcolor;
  ctx5.fillRect(0,0,cvs5.width,cvs5.height);
  ctx5.setTransform(1, 0, 0, 1, 0, 0);
  ctx5.font="12px 'Courier'";

  cvs6.width=Objects.canvasWidth;
  cvs6.height=20;
  ctx6.fillStyle=_setColor().bgcolor;
  ctx6.fillRect(0,0,cvs6.width,cvs6.height);
  ctx6.setTransform(1, 0, 0, 1, 0, 0);
  ctx6.font="11px 'Courier'";

  if(Objects.canvasHeight < 130){
    var elementind = document.getElementById("ind"); 
    var indmode=localStorage.getItem("_Mode");
    if(indmode == "s" || indmode == "i" || indmode == "dp"){
      elementind.style.marginTop = ((-150)+(95-Objects.canvasHeight))+"px"; 
    }else if(indmode == "dp+s" || indmode == "dp+i" || indmode == "si"){
      elementind.style.marginTop = ((-150)+(113-Objects.canvasHeight))+"px"; 
    }else if(indmode == "dp+a"){
      elementind.style.marginTop = ((-150)+(130-Objects.canvasHeight))+"px"; 
  }
}
  cvs7.width=150;
  cvs7.height=135;
  ctx7.fillStyle='rgba(0,0,0,0)';
  ctx7.fillRect(0,0,cvs7.width,cvs7.height);
  ctx7.fillStyle='rgba(255,255,255,0.6)';
  ctx7.fillRect(4,cvs7.height-28,cvs7.width-8,23);
  ctx7.strokeStyle="#acacb3";
  ctx7.lineWidth=1;
  ctx7.strokeRect(4,cvs7.height-28,cvs7.width-8,23);
  ctx7.setTransform(1, 0, 0, 1, 0, 0);
  ctx7.font="10px 'Courier'";

  cvs8.width=Objects.canvasWidth;
  cvs8.height=1;
  ctx8.fillStyle='rgba(0,0,0,0)';
  ctx8.fillRect(0,0,cvs8.width,1);
  ctx8.setTransform(1, 0, 0, 1, 0, 0);
  ctx8.font="10px 'Courier'";

//pre-drawing:required
  cvs9.width=450;
  cvs9.height=44;
  ctx9.fillStyle=_setColor().bgcolor;
  ctx9.fillRect(0,0,cvs9.width,cvs9.height);
  ctx9.strokeStyle="#302833";
  ctx9.lineWidth=30;
  ctx9.beginPath();
  ctx9.moveTo(3,21);
  ctx9.lineTo(451,21);
  ctx9.stroke();
  ctx9.closePath();
  ctx9.lineWidth=23;
  ctx9.beginPath();
  ctx9.lineCap = "round";
  ctx9.moveTo(14,12);
  ctx9.lineTo(440,12);
  ctx9.stroke();
  ctx9.closePath();
  ctx9.beginPath();
  ctx9.lineCap = "round";
  ctx9.moveTo(14,34);
  ctx9.lineTo(440,34);
  ctx9.stroke();
  ctx9.closePath();
  ctx9.shadowOffsetX = 0;
  ctx9.shadowOffsetY = 0;
  ctx9.shadowBlur = 0;
  ctx9.strokeStyle="#999999";
  ctx9.lineWidth=3;
  ctx9.beginPath();
  ctx9.arc(384, 19, 9, 0, Math.PI*2, false);
  ctx9.stroke();
  ctx9.beginPath();
  ctx9.arc(419, 19, 9, 0, Math.PI*2, false);
  ctx9.stroke();
  ctx9.lineWidth=4;
  ctx9.beginPath();
  ctx9.moveTo(392,26);
  ctx9.lineTo(405,37);
  ctx9.closePath();
  ctx9.stroke();
  ctx9.beginPath();
  ctx9.moveTo(425,26);
  ctx9.lineTo(438,37);
  ctx9.closePath();
  ctx9.stroke();
  ctx9.fillStyle=_setColor().zoombar;
  ctx9.fillRect(383,13,2,12);
  ctx9.fillRect(378,17.5,12,2);
  ctx9.fillRect(413,17.5,12,2);
  ctx9.setTransform(1, 0, 0, 1, 0, 0);
  ctx9.font="10px 'Courier'";
  frameZoomb=ctx9.getImageData(0, 0, cvs9.width, cvs9.height);
  var elementcell = document.getElementById("cellinf"); 
  elementcell.style.top = '1px'; 
  elementcell.style.left = '1px';

  cvs10.width=1;
  cvs10.height=1;
  ctx10.fillStyle='rgba(0,0,0,0)';
  ctx10.fillRect(0,0,cvs10.width,cvs10.height);
  ctx10.setTransform(1, 0, 0, 1, 0, 0);
  ctx10.font="10px 'Courier'";

  cvs11.width=Objects.titleWidth;
  cvs11.height=parseInt(Objects.NavH/3);
  ctx11.fillStyle=_setColor().bgcolor;
  ctx11.fillRect(0,0,cvs11.width, cvs11.height);
  ctx11.setTransform(1, 0, 0, 1, 0, 0);
  ctx11.font="16px 'Courier'";
  
  // Set to main canvas height
  var offset=20;
  var divHeight=window.innerHeight-$('#content').offset().top-$('#content2').height()-$('#bottom').height()-offset;
  if ( Objects.canvasHeight < divHeight ) {
    divHeight=Objects.canvasHeight+10;
  }
  $('#content').css("height", divHeight);
  
  // Changing height during resize
  $(window).bind("resize", resizeWindow);
  function resizeWindow( e ) {
    divHeight=$(window).height()-$('#content').offset().top-$('#content2').height()-$('#bottom').height()-offset;
    if ( Objects.canvasHeight < divHeight ) {
      divHeight=Objects.canvasHeight+10;
    } $('#content').css("height", divHeight);
  }
}

///////////////////////////// Print area
function _printArea(area) {
  t=area*_cvtZoom(Objects.Zoom);
  if (t<1000) {
    return String(t)+" bp";
  } else if (t>=1000 && t<1000000) {
    return String(t/1000)+" kbp";
  } else if (t>=1000000) {
    return String(t/1000000)+" mbp";
  }
}

///////////////////////////// Print pos by zoom
function _printPos(pos) {
  z=_cvtZoom(Objects.Zoom);
  t=parseInt(pos*z);
  if (z<1000) {
    return String(t)+" b";
  } else if (z>=1000 && z<1000000) {
    return String((t/1000))+" k";
  } else if (z>=1000000) {
    return String((t/1000000))+" m";
  }
}

///////////////////////////// Drawing Snpblock: Estimation of SNP "blocks"
function _getSnpblock(str) {
  var o=new Object(JSON.parse(localStorage.getItem('_Snpblock')));
  for (var x=0; x<o.length; x++) {
    var pattern=new RegExp(str);
    if(o[x].id.match(pattern)) {
      return o[x].rate;
    }
  }
}

/////////////////////////////////////////////// Stop drag when mouse up
function _getData_p(d) {
  var s;
  var t=0;
  var p=0
  var b=Math.abs(parseInt(d/Objects.BlockW));
  var setP;
  if (d>0){
    s="right";
    t=Objects.BlockW-d%Objects.BlockW;
    n=d+t;
    b=parseInt(n/Objects.BlockW);
    if(Objects.Pos-b<1){
      n=0;
      b=Objects.Pos-1;
      p=1;
    } else {
      p=Objects.Pos-b;
    }
    setP=p;
  } else {
    s="left";
    t=Objects.BlockW+d%Objects.BlockW;
    n=d-t;
    b=Math.abs(n/Objects.BlockW);
    max=_last(Objects.Zoom);
    p=Objects.Pos+Objects.Block;
    if(p+b-1>max){
      p=max-(max-p);
      n=-((max-p+1)*Objects.BlockW);
      b=(max-p+1);
    }
    setP=p-Objects.Block+b;
  }
  // Set canvas by block width
  ctx2.clearRect(0, 30, cvs2.width, 30);
  ctx4.clearRect(0, 0, Objects.canvasWidth, Objects.canvasHeight);
  ctx4.putImageData(frameCellwoI, n, 0);
  ctx1.clearRect(0, 0, cvs1.width, cvs1.height);
  ctx1.putImageData(frameTrack, n, 0);
  ctx0.clearRect(0, 0, cvs0.width, cvs0.height);
  ctx0.putImageData(frameTrackTitle, 0, 0);
  ctx6.putImageData(frameSNP, n, 0);
  _drawMeter(setP,null);
  _drawRules();
  if (Objects.Indicator=="on") {
    _drawIndicator();
    _drawDirection();
  }
  // If occured gap
  if (b>0) {
    _showLoading();
    localStorage.setItem("_Pos", setP);  // need load, first position
    _setHistory("position,"+Objects.Chr+","+setP+","+Objects.Zoom);
    FROMSCROLL=false;
    _execCanvas(p,b,s);   // Load part of datas
  }
}

///////////////////////////// Stringfy of array data
function _mergeObject(o){
  var str;
  str="{\"dp\":\"";
  if(o.dp == null){
    str=str+"";
  } else {
    str=str+o.dp;
  }
  str=str+"\"";
  if(o.rdp != undefined){
    str=str+",\"rdp\":\"";
    if(o.rdp == null){
      str=str+"";
    } else {
      str=str+o.rdp;
    }
    str=str+"\"";
  }
  if(o.s != undefined){
    str=str+",\"s\":\""+o.s+"\"";
  }
  if(o.i != undefined){
    str=str+",\"i\":\""+o.i+"\"";
  }
  if(o.d != undefined){
    str=str+",\"d\":\""+o.d+"\"";
  }
  if(o.hs != undefined){
    str=str+",\"hs\":\""+o.hs+"\"";
  }
  if(o.hi != undefined){
    str=str+",\"hi\":\""+o.hi+"\"";
  }
  if(o.hd != undefined){
    str=str+",\"hd\":\""+o.hd+"\"";
  }
  str=str+"}";
  return str; 
}

///////////////////////////// Set part of data
function _setData_p(datas,s,b) {
  var n=datas.split(";");
  for (var i=0; i<n.length; i++) {
    var a=n[i].split("|");
    var o=JSON.parse(_getCompressedData(a[0]));
    var j=new Object(JSON.parse(a[1]));
    var t="[";
    if(s=="left"){
      for(var k=0; k<o.length-b; k++) {
      t=t+_mergeObject(o[k+b])+",";
      }
      for(var k=0; k<b; k++) {
        t=t+_mergeObject(j[k]);
        if(k<b-1){t=t+",";}
      }
    } else {
      for(var k=0; k<b; k++) {
        t=t+_mergeObject(j[k])+",";
      }
      for(var k=0; k<o.length-b; k++) {
        t=t+_mergeObject(o[k]);
        if(k<o.length-b-1){t=t+",";}
      }
    }
    var t=t+"]";
    _setCompressedData(a[0], t); // Rewrite if exists
  }
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

/////////////////////////////////////////////// Change display mode
function _changeMode(str){
  if ( Objects.Snpblock == "off" ) {
    localStorage.setItem("_Mode", str);
    _drawCanvas();
  } else {
    _messageOnScreen("Mode is fixed reason why 'Snpblock' is on.");
  }
}

/////////////////////////////////////////////// Change display mode(switch)
function _changeModeSW(str){
  if ( Objects.Snpblock == "off" ) {
    if (localStorage.getItem("_Mode") == str){
      localStorage.setItem("_Mode", "dp");
    } else {
      localStorage.setItem("_Mode", str);
    }
    _drawCanvas();
  } else {
    _messageOnScreen("Mode is fixed reason why 'Snpblock' is on.");
  }
}

/////////////////////////////////////////////// Change direction of reference
function _changeDirRef(){
  if ( localStorage.getItem("_DirRef") == "+" ) {
    localStorage.setItem("_DirRef", "-");
  } else {
    localStorage.setItem("_DirRef", "+");
  }
}

/////////////////////////////////////////////// Change select chromosome for search ID
function _changeChromosomeSearch(kwd){
  var chr=$('#prm_chr').val();
  $('#prm_chr').blur(); // focus out from select box
  _showLoading();
  _messageOnScreen("Moving to "+kwd);
  FROMSCROLL=false;
  _execCanvas();
  // Set chromosome option on dialog 'Search'
  $('#prm_position_chr').val(chr);
}

/////////////////////////////////////////////// Change select chromosome 
function _changeChromosome(){
  var chr=$('#prm_chr').val();
  localStorage.setItem('_Chr', chr);
  localStorage.setItem('_Pos', '1');
  $('#prm_chr').blur(); // focus out from select box
  _showLoading();
  _messageOnScreen("Loading "+chr);
  FROMSCROLL=false;
  _execCanvas();
  // Set chromosome option on dialog 'Search'
  $('#prm_position_chr').val(chr);
}

/////////////////////////////////////////////// Change zoom
function _changeZoomS(zoom){
  var msg;
  var flag;
  var cZoom=_cvtZoom(Objects.Zoom);
  var tZoom=_cvtZoom(zoom);
  var scrMsg="";
  var toZoom="";
  var o = _getChr(Objects.Chr);

  // Zoom in when over 1b
  if(zoom=='+') {
    if ( _cvtZoom(Objects.Zoom) > 1 ){
      var b=(parseInt(Objects.Pos)+(Objects.Block/2))*_cvtZoom(Objects.Zoom);
      var p=_checkPos(parseInt(b/_cvtZoom(_cvtZoomDown(Objects.Zoom)))-(Objects.Block/2)-1,_cvtZoomDown(Objects.Zoom));
      localStorage.setItem("_Pos", new String(p));
      localStorage.setItem("_Zoom", _cvtZoomDown(Objects.Zoom));
      msg="zoomIn";
      flag=true;
    } else {
      msg="Minimum zoom scale";
      flag=false;
    }
  }
  // Zoom out when under 100k
  if(zoom=='-') {
    if (_cvtZoom(Objects.Zoom) < 100000 && (_cvtZoom(_cvtZoomUp(Objects.Zoom))*Objects.Block <= o.size) ){
      var b=(parseInt(Objects.Pos)+(Objects.Block/2))*_cvtZoom(Objects.Zoom);
      var p=_checkPos(parseInt(b/_cvtZoom(_cvtZoomUp(Objects.Zoom)))-(Objects.Block/2)+1,_cvtZoomUp(Objects.Zoom));
      localStorage.setItem("_Pos", new String(p));
      localStorage.setItem("_Zoom", _cvtZoomUp(Objects.Zoom));
      flag=true;
      msg="zoomOut";
    } else {
      msg="Maximum zoom scale";
      flag=false;
    }
  }
  if(msg=="zoomIn"){
    _drawMessageOnScreen(msg);
    scrMsg="Zoom in "+Objects.Zoom+" to "+_cvtZoomDown(Objects.Zoom)+" per block";
    _messageOnScreen(scrMsg);
    toZoom=_cvtZoomDown(Objects.Zoom);
  } else if ( msg=="zoomOut") {
    scrMsg="Zoom out "+Objects.Zoom+" to "+_cvtZoomUp(Objects.Zoom)+" per block";
    _messageOnScreen(scrMsg);
    toZoom=_cvtZoomUp(Objects.Zoom);
  } else {
    _messageOnScreen(msg);
  }
  if(flag){
    drCnt=0;
    timerArray.push(setInterval(function(){_trfMain(scrMsg,Objects.Zoom,toZoom);},50));
    _showLoading();
    FROMSCROLL=false;
    _execCanvas();
  }
}

////////////////////////////////////////animation
function _trfMain(m,czoom,zoom){
  var scale=_cvtZoom(zoom)/_cvtZoom(czoom);
  if(scale <= 1){
    scale=Math.pow(1-(1-scale), 1/10);
    ctx4.putImageData(frameCell, 0, 0);
    ctx4.drawImage(cvs4,parseInt((Objects.canvasWidth-(Objects.canvasWidth*scale))/2) ,0 ,parseInt(Objects.canvasWidth*scale) ,Objects.canvasHeight ,0,0 ,Objects.canvasWidth ,Objects.canvasHeight );
    frameCell=ctx4.getImageData(0, 0, cvs4.width, cvs4.height);
    _messageOnScreen(m);
    drCnt++;
    if( drCnt > 9 ){
      for(var x=0; x<timerArray.length; x++){
        clearInterval(timerArray.shift());
      }
    }
  }else{
    scale=Math.pow(scale, 1/10);  
    ctx4.putImageData(frameCell, 0, 0);
    ctx4.drawImage(cvs4,0 ,0 ,Objects.canvasWidth ,Objects.canvasHeight ,parseInt((Objects.canvasWidth/2)-Objects.canvasWidth/2/scale),0 ,parseInt(Objects.canvasWidth/scale) ,Objects.canvasHeight );
    frameCell=ctx4.getImageData(0, 0, Objects.canvasWidth , cvs4.height);
    ctx4.fillStyle="#ffffff";
    ctx4.fillRect(0, 0, parseInt((Objects.canvasWidth/2)-Objects.canvasWidth/2/(scale*Math.pow(scale, drCnt+1))), Objects.canvasHeight);
    ctx4.fillRect(parseInt((Objects.canvasWidth/2)+Objects.canvasWidth/2/(scale*Math.pow(scale, drCnt+1))), 0, parseInt((Objects.canvasWidth/2)-Objects.canvasWidth/2/(scale*Math.pow(scale, drCnt+1))), Objects.canvasHeight);
    _messageOnScreen(m);
    drCnt++;
    if( drCnt > 9){
      for(var x=0; x<timerArray.length; x++){
        clearInterval(timerArray.shift());
      }
    }
  }
}

/////////////////////////////////////////////// Change zoom
function _changeZoom(zoom){
  var msg;
  var flag;
  var cZoom=_cvtZoom(Objects.Zoom);
  var tZoom=_cvtZoom(zoom);
  var scrMsg="";
  var o = _getChr(Objects.Chr);
  
  if(zoom != Objects.Zoom){
    if(tZoom*Objects.Block > o.size){
      console.log("!");
      msg="This window size will be larger than ["+o.id+"].";
      flag = false;
    }else{
      var b=(parseInt(Objects.Pos)+(Objects.Block/2))*_cvtZoom(Objects.Zoom);
      var p=_checkPos(parseInt(b/_cvtZoom(zoom))-(Objects.Block/2)+1,zoom);
      localStorage.setItem('_Pos', new String(p));
      localStorage.setItem('_Zoom', zoom);
      if ( cZoom > tZoom ) { msg="zoomInC" }
      else { msg="zoomOut"; }
      flag=true;
    }
  } else {
    msg="Currently zoom scale is "+Objects.Zoom+" per block";
    flag=false;
  }
  if(msg=="zoomInC"){
    _drawMessageOnScreen(msg,tZoom,cZoom);
    scrMsg="Zoom in "+Objects.Zoom+" to "+zoom+" per block";
    _messageOnScreen(scrMsg);
  } else if ( msg=="zoomOut" ) {
     scrMsg="Zoom in "+Objects.Zoom+" to "+zoom+" per block";
    _messageOnScreen(scrMsg);
  } else {
    _messageOnScreen(msg);
  }
  if(flag){
    drCnt=0;
    timerArray.push(setInterval(function(){_trfMain(scrMsg,Objects.Zoom,zoom);},50));
    _showLoading();
    FROMSCROLL=false;
    _execCanvas();
  }
  // Set zoom option on dialog 'Search'
  $('#prm_position_zoom').val(zoom);
}

/////////////////////////////////////////////// Details accession
function _changeRef(){
  var i=document.getElementById("prm_chref").value;
  var o=new Object(JSON.parse(localStorage.getItem('_Lists')));
  if(Objects.Onebase!="off"){
  _dlg_chref_cancel();
  return;
  }

  if ( localStorage.getItem("_Ref") != o[i].db ) {
    _changeEff('off');
    _changeOnebase('off');
    localStorage.setItem("_Ref", o[i].db);
    msg="Changing reference "+o[i].id;
  } else {
    localStorage.setItem("_Ref", "Reference");
    msg="Reset reference";
  }
  // Estimation of SNP 'blocks' in changing reference
  if (localStorage.getItem("_Snpblock") != "off") {
    _execSnpblock(localStorage.getItem("_Ref"));
  }
  _changeNull();
  _changeNull();//require
  _showLoading();
  _messageOnScreen(msg);
  FROMSCROLL=false;
  _execCanvas();
  _dlg_chref_cancel();
}

/////////////////////////////////////////////// Message on screen
function _messageOnScreen(str){
  ctx4.textAlign="left";
  ctx4.fillStyle="#ffffff";
  if(cvs4.height < 37){
    ctx4.fillRect(((cvs4.width-350)/2),1,350,11);
    ctx4.strokeStyle="#b0c4de";
    ctx4.lineWidth=2;
    ctx4.strokeRect(((cvs4.width-350)/2),1,350,11);
    ctx4.font="Bold 8px 'Century'";
    ctx4.fillStyle="#000000";
    ctx4.fillText(str,((cvs4.width-350)/2)+20,1+9);
  }else if(cvs4.height < 74){
    ctx4.fillRect(((cvs4.width-350)/2),cvs4.height/6,350,35);
    ctx4.strokeStyle="#b0c4de";
    ctx4.lineWidth=5;
    ctx4.strokeRect(((cvs4.width-350)/2),cvs4.height/6,350,35);
    ctx4.font="Bold 13px 'Century'";
    ctx4.fillStyle="#000000";
    ctx4.fillText(str,((cvs4.width-350)/2)+20,cvs4.height/6+20);
  }else{
    ctx4.fillRect(((cvs4.width-350)/2),cvs4.height/4,350,60);
    ctx4.strokeStyle="#b0c4de";
    ctx4.lineWidth=7;
    ctx4.strokeRect(((cvs4.width-350)/2),cvs4.height/4,350,60);
    ctx4.font="Bold 13px 'Century'";
    ctx4.fillStyle="#000000";
    ctx4.fillText(str,((cvs4.width-350)/2)+20,(cvs4.height/4)+35);
  }
}

/////////////////////////////////////////////// view each variants
function _changeOnebase(base){
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  var zm = _cvtZoom(en.nuc_max);
  if(!zm){zm=4000;}
  if ( localStorage.getItem("_Ref") == "Reference") {
    if (localStorage.getItem('_Onebase')=="on" || base == "off"){
      localStorage.setItem('_Onebase', "off");
    }else{
      if (_cvtZoom(Objects.Zoom) > zm){
        localStorage.setItem("_Onebase", "off");
      }else{
        localStorage.setItem('_Onebase', "on");
      }
    }
    if ( localStorage.getItem("_Snpblock") != "off" && localStorage.getItem('_Onebase') == "on" ) {
      localStorage.setItem('_Onebase', "off");
    }
  }
  _drawCanvas();
}

/////////////////////////////////////////////// WGS or Custom track
function _changeDepth(ctrl){
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  if(en.cstm_track == "enabled"){
    if (localStorage.getItem("_CSTM") == "on" || ctrl == "off"){
      localStorage.setItem('_CSTM', "off");
    }else{
      localStorage.setItem('_CSTM', "on");
    }
  _drawCanvas();
  }
}

/////////////////////////////////////////////// Change variant Effect
function _changeEff(eff){
  if ( localStorage.getItem("_Ref") == "Reference") {
    if (localStorage.getItem('_Eff')=="on" || eff == "off") {
      localStorage.setItem('_Eff', "off");
    } else {
      localStorage.setItem('_Eff', "on");
    }
    if ( localStorage.getItem("_Snpblock") != "off" && localStorage.getItem('_Eff') == "on" ) {
      localStorage.setItem('_Snpblock', "off");
    }
  }
  _drawCanvas();
}

/////////////////////////////////////////////// Change snpblock
function _changeSnpblock(){
  if ( localStorage.getItem("_Snpblock")=="off" ) {
    localStorage.setItem('_Eff', "off");
    localStorage.setItem('_Mode', localStorage.getItem("_Mode"));
    _execSnpblock(localStorage.getItem("_Ref"));
  } else {
    localStorage.setItem("_Snpblock", "off");
  }
  _drawCanvas();
  if ( localStorage.getItem('_Snpblock') == "[]" ) {
    _messageOnScreen("Snpblock data is not found");
  }
}

/////////////////////////////////////////////// Change NULL on/off
function _changeNull(){
  if (localStorage.getItem("_Null")=="false"){
    localStorage.setItem("_Null", "true");
  } else {
    localStorage.setItem("_Null", "false");
  }
  _drawCanvas();
}

/////////////////////////////////////////////// Change color gradient from color manager
function _changeColorGradient(){
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  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 i=0; i<colorObjects.length; i++){
    var array = colorObjects[i].split("_");
    en[array[1]+"_"+array[2]+"_col"]=$(colorObjects[i]).val();
  }
  localStorage.setItem("_Env",JSON.stringify(en));
  grad_DP = gra_hexcolor(en.depth_min_col,en.depth_max_col);
  grad_S = gra_hexcolor(en.snp_min_col,en.snp_max_col);
  grad_INDEL = gra_hexcolor(en.indel_min_col,en.indel_max_col);
  grad_CSTM_array[0] = gra_hexcolor(en.cstm_min_col,en.cstm_max_col);
  _drawCanvas();
}

function _changeCondColorGradient(){
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  var colorObjects=["#manager_cstm_max_para0","#manager_cstm_min_para0","#manager_cstm_max_para1","#manager_cstm_min_para1","#manager_cstm_max_para2","#manager_cstm_min_para2","#manager_cstm_max_para3","#manager_cstm_min_para3"];
  for(var i=0; i<colorObjects.length; i++){
    var array = colorObjects[i].split("_");
    if(array[3] == "para0"){
      en[array[1]+"_"+array[2]+"_col"] = $(colorObjects[i]).val();
    }else{
      en[array[1]+"_"+array[2]+"_col_"+array[3]] = $(colorObjects[i]).val();
    }
  }
  localStorage.setItem("_Env",JSON.stringify(en));
  grad_CSTM_array[0] = gra_hexcolor(en.cstm_min_col,en.cstm_max_col);
  grad_CSTM_array[1] = gra_hexcolor(en.cstm_min_col_para1,en.cstm_max_col_para1);
  grad_CSTM_array[2] = gra_hexcolor(en.cstm_min_col_para2,en.cstm_max_col_para2);
  grad_CSTM_array[3] = gra_hexcolor(en.cstm_min_col_para3,en.cstm_max_col_para3);
  _drawCanvas();
}

/////////////////////////////////////////////// Change range of gradient from color manager
function _changeRangeOfGrad(dest){
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  var colorObjects=[ dest+"_slider_max", dest+"_slider_min"];
  for(var i=0; i<colorObjects.length; i++){
    var array = colorObjects[i].split("_");
    if(((array[0]=="depth" || array[0]=="cstm"))){
      en[array[0]+"_"+array[2]]=$("#"+colorObjects[i]).val();
    }else{
      var keys = Object.keys(en);
      for (var a=0; a<keys.length; a++) {
        var regexp = new RegExp(array[0]+"_.*[kb]");
        if(keys[a].match(regexp)){
          var keySp = keys[a].split("_");
          var percentage = $("#"+colorObjects[i]).val();
          var value = parseInt(_cvtZoom(keySp[1])*(percentage/100));
          if(value < 1 ){value=1;}
          if(array[0]==dest && array[2]=="min"){
            Objects[array[0]+"_"+array[2]+"_rate"]=percentage/100;
            en[array[0]+"_"+array[2]]=value;
          }else{
            en[keys[a]]=value;
          }
        }
      }
    }
  }
  localStorage.setItem("_Env",JSON.stringify(en));
  _drawCanvas();
}

function _setMinColor(dest){
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  if(dest+"_min_rate" in Objects){
    en[dest+"_min"]=parseInt(_cvtZoom(localStorage.getItem("_Zoom"))*Objects[dest+"_min_rate"]);
    if(en[dest+"_min"]<1){en[dest+"_min"]=1;}
    localStorage.setItem("_Env",JSON.stringify(en));
  }else{
    //pass
  }
}

//////////////////////////////////////////////// view object id on each track
function _viewObjectID(){
  var isConflict=false;
  if (localStorage.getItem("_TrackID")!="on"){
    isConflict = _trackConflict();
    if(!isConflict){localStorage.setItem("_TrackID", "on");}
  }else{
    localStorage.setItem("_TrackID", "off");
  }
  _drawCanvas();
  if(isConflict){_messageOnScreen("No space for viewing the feature ID");}
  var evt = document.createEvent("HTMLEvents");//reloading main canvas by track resizing
  evt.initEvent("scroll", true, true);
  content.dispatchEvent(evt);
}

//////////////////////////////////////////////// Check confliction of feature ID on tracks.
function _trackConflict(){
  var to=new Object(JSON.parse(localStorage.getItem("_Tracks")));
  var ta=_getTrack("view");
  var ret=false;
  for ( i=0; i<ta.length; i++) {
    for ( j=0; j<to.length; j++) {
      if ( ta[i] == to[j].track ) {
        var prevRow = new Array(0,0,0,0,0);
        var prevEnd=0;
        var o=new Object(JSON.parse(localStorage.getItem("_Track_"+j)));
        for (var k=0;k<o.length;k++){
          var end=(parseInt(o[k].rs)*Objects.BlockW)+100;
          if(((o[k].rs*Objects.BlockW) < prevRow[o[k].h]) && prevRow[o[k].h] != 0 && o[k].id != ""){
            ret=true;
          }
          prevRow[o[k].h]=end;
        }
      }
    }
  }
  return ret;
}

/////////////////////////////////////////////// escape HTML
function _escapeHTML(str) {
  return str.replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;')
  .replace(/'/g, '&#039;');
}

/////////////////////////////////////////////// 
function _getVisibleArea(mode){
  var ONDIALOG=false;
  if ($('#dialog_csv').is(":visible")) ONDIALOG=true;
  if ($('#dialog_fa').is(":visible")) ONDIALOG=true;
  if ($('#dialog_p3').is(":visible")) ONDIALOG=true;
  if ($('#dialog_track').is(":visible")) ONDIALOG=true;
  if ($('#dialog_reset').is(":visible")) ONDIALOG=true;

  if(!ONDIALOG){
    var eleCont = document.getElementById("content");
    var boundsCont = eleCont.getBoundingClientRect(); 
    var contTop = boundsCont.top;
    var eleCont2 = document.getElementById("content2");
    var boundsCont2 = eleCont2.getBoundingClientRect(); 
    var cont2Top = boundsCont2.top;
    var visible = cont2Top-contTop+parseInt(Objects.BlockH*1.5);
    var accStr = eleCont.scrollTop;
    var skipTop = parseInt(accStr/Objects.BlockH);// considering value=0
    var visibleCont = parseInt(visible/Objects.BlockH);//top +1 bottom +1
    var baseobj=new Object(_getList("db"));
    
    if(isNaN(skipTop)){skipTop = 1;}
    if(isNaN(visibleCont)){
      if(visibleCont > baseobj.length){
        visibleCont=baseobj.length-1;
      }else{
        visibleCont = parseInt(cont2Top/localStorage.getItem("_BlockH"));
      }
    }else{
      if(visibleCont > baseobj.length){
        visibleCont=baseobj.length-1;
      }else{
        visibleCont=visibleCont-1;
      }
    }
    if(skipTop==0){skipTop=1;}
    VIEWSTART=skipTop;
    VIEWLEN=visibleCont;
    var str="";
    var array = new Array;
    array=_NgetList("db",skipTop,visibleCont+1,"_Lists")
    for(var i=0; i < array.length; i++){
      str += array[i];
      if(i != visibleCont){
        str += ",";
      }
    }
    localStorage.setItem("_ListsTgt", str);
  }
}

function _isUndefined(value){
  var a;
  if(value === a){
    return 1;
  }else{
    return 0;
  }
}

function times(str, n) {
  var	i;
  var part = str;
  var res = '';
  for (i = 1; i <= n; i <<= 1, part += part) {
  if (n & i) res += part;
  }
  return res;
}

function _overWriteColorFromEnv(){
  var en=new Object(JSON.parse(localStorage.getItem("_Env")));
  grad_DP = gra_hexcolor(en.depth_min_col,en.depth_max_col);
  grad_S = gra_hexcolor(en.snp_min_col,en.snp_max_col);
  grad_INDEL = gra_hexcolor(en.indel_min_col,en.indel_max_col);
  grad_CSTM_array[0] = gra_hexcolor(en.cstm_min_col,en.cstm_max_col);
  grad_CSTM_array[1] = gra_hexcolor(en.cstm_min_col_para1,en.cstm_max_col_para1);
  grad_CSTM_array[2] = gra_hexcolor(en.cstm_min_col_para2,en.cstm_max_col_para2);
  grad_CSTM_array[3] = gra_hexcolor(en.cstm_min_col_para3,en.cstm_max_col_para3);
}

function _resetMultiCondEnv(str){
  if(parseInt(str) == 0){
    var condArray = localStorage.getItem("_CrtCondition").split("|");
    for(var i=0; i<condArray.length; i++){
      var tgt = 'select[name=cond_select_row'+i+']';
      if(i==0){
        $(tgt).val(0);
      }else{
        $(tgt).val("");
      }
    }
    _setMultiCond();
  }else{
    var org = "";
    $.ajax({
      url: "./bin/env.php",
      cache: false,
      async: false,
      success: function(data) {
        org = data;
      }
    });
    var orgen=new Object(JSON.parse(org));
    var en=new Object(JSON.parse(localStorage.getItem("_Env")));
    var colorObjects=["cstm_max_col","cstm_min_col","cstm_max_col_para1","cstm_min_col_para1","cstm_max_col_para2","cstm_min_col_para2","cstm_max_col_para3","cstm_min_col_para3"];
    for(var i=0; i<colorObjects.length; i++){
      en[colorObjects[i]] = orgen[colorObjects[i]];
    }
    localStorage.setItem("_Env",JSON.stringify(en));
    grad_CSTM_array[0] = gra_hexcolor(en.cstm_min_col,en.cstm_max_col);
    grad_CSTM_array[1] = gra_hexcolor(en.cstm_min_col_para1,en.cstm_max_col_para1);
    grad_CSTM_array[2] = gra_hexcolor(en.cstm_min_col_para2,en.cstm_max_col_para2);
    grad_CSTM_array[3] = gra_hexcolor(en.cstm_min_col_para3,en.cstm_max_col_para3);
    _drawCanvas();
    _dialog_cond();
  }
}

function _externalParser(){
  var url = location.search;
  var query = url.split("?");
  if(query.length < 2){return;}
  var prm = query[1].split("&");
  var object = new Object();
  var windowSize=100;

  //  e.g.) http://yourserver/index.html?id=AAA&st=111&en=222&chr=BBB
  //  id: If you set transcript id to this parameter, the transcript object is highlighted on track. (Not required)
  //  st: Target start position
  //  en: Target end position
  //  chr: Name of taget sequence
  //  acc: Comma separated accessions if(!_isUndefined(o[i])){

  for(i=0;i<prm.length;i++){
    var keyVal = prm[i].split("=");
    object[keyVal[0]]=keyVal[1];
  }
  
  // Accessions
  if(!_isUndefined(object["acc"])){
    localStorage.setItem("_Ext_accessions", object["acc"]);
    _execLists();
  }
  
  //Position
  if(!_isUndefined(object["chr"]) && !_isUndefined(object["st"]) && !_isUndefined(object["en"])){
    var len = object["en"]-object["st"];
    var blks = parseInt((len*1.1)/windowSize);
    var optBlks="";
    var locString="the target";
    var leftPos=1;
    var b=0;
    var c=0;
    var modLeftPos=0;
    
    object["st"]=parseInt(object["st"]);
    object["en"]=parseInt(object["en"]);
    if (!_isEmpty(localStorage.getItem("_Block"))){windowSize=localStorage.getItem("_Block");}
    
    if(blks < 1){blks=1;}
    var scale = Math.floor(Math.log(blks)/Math.log(10))+1;
    if(scale==3 && blks > 900){scale=4;}
    if (scale > 1){//processing for Block-size and position
      b = (blks/Math.pow(10,(scale-1)));
      c = parseInt(b)*Math.pow(10,(scale-1));
      if(scale < 4){
        if(len*1.1 > c*windowSize){c = parseInt(b+1)*Math.pow(10,(scale-1));}
        leftPos=parseInt(object["st"]/c)-(parseInt((windowSize-parseInt(len/c)-2)/2));
        optBlks=c+"b";
      }else{
        if(len*1.1 > c*1000*windowSize){c = parseInt(b+1)*Math.pow(10,(scale-1));}
        leftPos=parseInt(object["st"]/c)-(parseInt((windowSize-parseInt(len/c))/2));
        optBlks=c/1000+"k";
      }
    }else{
      b = (blks/Math.pow(10,(scale-1)));
      c = parseInt(b)*Math.pow(10,(scale-1));
      if(len*1.1 > c*windowSize){c = parseInt(b+1)*Math.pow(10,(scale-1));}
      leftPos=parseInt(object["st"]/c)-(parseInt((windowSize-parseInt(len/c)-2)/2));
      optBlks=c+"b";
    }
    if(scale < 4){
      p=_checkPos_Chr(leftPos*c,optBlks,object["chr"]);
    }else{
      p=_checkPos_Chr(parseInt(leftPos*c),optBlks,object["chr"]);
    }
    if(!_isUndefined(object["id"])){localStorage.setItem("_Keyword", object["id"]);}
    localStorage.setItem("_Chr", object["chr"]);
    localStorage.setItem("_Zoom", optBlks);
    localStorage.setItem("_Pos", p);
    localStorage.setItem("_Block", windowSize);
  }
  location.replace('./');
}

function _backendSelector(str){
  var en = new Object(JSON.parse(localStorage.getItem("_Env")));
  var script = str.split("\.");
  var ret = "";
  switch (en.backend) {
    case "oracle":
      ret = "oracle/"+script[0]+"_oracle."+script[1];
      break;
    default: 
      ret = str;
      break;
  }
  return ret;
}

var overflowObject = new Object();
var compressedStorage = true;
function _setCompressedData(key,val){
  if(compressedStorage == true){
    try{
      localStorage.setItem(key,LZString.compressToUTF16(val));
    }catch(e){
     // alert("The LocalStorage has overflowed. The TASUKE will be reset after 10 second.");
      console.log(e.message);
      setTimeout(_dlg_reset_confirm(),5000);
      //overflowObject[key] = val;
    }
  }else{
    localStorage.setItem(key,val);
  }
}

function _getCompressedData(key){
  var val = "";
  if(compressedStorage == true){
    if (localStorage.getItem(key) === null) {
      if(key in overflowObject){
        //alert("Invalid key was found. The TASUKE will be reset after 10 second.");
        console.log(e.message);
        //setTimeout(_dlg_reset_confirm(),5000);
        return;
      }else{
        //val = overflowObject[key];
      }
    }else{
      val = LZString.decompressFromUTF16(localStorage.getItem(key));
    }
  }else{
    val = localStorage.getItem(key);
  }
  return val;
}

function _getTitleColor(str){
  var col = new Object(JSON.parse(localStorage.getItem("_GrpCol")));
  return col[str];
}

function _changeTitleColor(){
  var i = $("select[name=prm_grpcol_switch]").val();
  if(i==1){
    localStorage.setItem('_ColorCode',"on");
  }else{
    localStorage.setItem('_ColorCode',"off");
  }
  _drawCanvas();
}

function _drawTitleColor(){
  _setTitleColor();
  _drawCanvas();
}

function tasuke_version(){
  var version = "1.4.0";
  return version;
}


