/*
* draw.js
* http://tasuke.dna.affrc.go.jp/
*
* Author: Jungsok Kim, Ryutaro Itoh
*
* Copyright (c) 2013 National Institute of Agrobiological Sciences   
*
*/

///////////////////////////// Drawing canvas
function _drawCanvas() {
  storage.setItem("_exportFlg",0);
  Objects.titleWidth=parseInt(storage.getItem("_TitleW"));//14 letters
  Objects.titleIndent=5;
  Objects.titleGrp=parseInt(parseInt(storage.getItem("_TitleW")*0.7));//7 letters
  Objects.titleY=11;
  Objects.Tracks=_getTrack("view");
  if(storage.getItem("_TrackID")=="on"){Objects.TrackH=_getTrack("view").length*80+1;}
  else{Objects.TrackH=_getTrack("view").length*40+1; }
  Objects.NavH=50;
  Objects.id=_getList("id");
  Objects.name=_getList("name");
  Objects.db=_getList("db");
  Objects.grp=_getList("grp");
  Objects.variety=_getList("variety");
  Objects.origin=_getList("origin");
  Objects.origin_2=_getList("origin_2");
  Objects.type=_getList("type");
  Objects.other_1=_getList("other_1");
  Objects.other_2=_getList("other_2");
  Objects.Block=parseInt(storage.getItem("_Block"));
  Objects.BlockW=parseInt(storage.getItem("_BlockW"));
  Objects.BlockH=parseInt(storage.getItem("_BlockH"));
  Objects.Zoom=storage.getItem("_Zoom");
  Objects.Amino=storage.getItem("_Amino");
  if ( Objects.Zoom == "1b" ) Objects.TrackH=Objects.TrackH+20;
  if ( Objects.Zoom == "1b" && Objects.Amino == "on" ) Objects.TrackH=Objects.TrackH+45;
  Objects.Chr=_escapeHTML(storage.getItem("_Chr"));
  Objects.Pos=parseInt(storage.getItem("_Pos"));
  Objects.Mode=storage.getItem("_Mode");
/*
  if(storage.getItem("_titleFlg") == 1) {
  	titlestr = _getTitle();
  	var titleary = titlestr.split(",");
  	var title = titleary[0];
  	var subtitle = titleary[1];
   	Objects.Name=title;
  	Objects.NameSub=subtitle;
	storage.setItem("_Name",title);
	storage.setItem("_NameSub",subtitle);
	storage.setItem("_titleFlg","0");
  } else {

  	Objects.Name=storage.getItem("_Name");
  	Objects.NameSub=storage.getItem("_NameSub");
  }
*/
  Objects.Name=storage.getItem("_Name");
  Objects.NameSub=storage.getItem("_NameSub");
  Objects.Eff=storage.getItem("_Eff");
  Objects.Onebase=storage.getItem("_Onebase");
  Objects.Snpblock=storage.getItem("_Snpblock");
  Objects._Null=storage.getItem("_Null");
  Objects.Indicator=storage.getItem("_Indicator");
  Objects.Keyword=storage.getItem("_Keyword");
  Objects.canvasWidth=Objects.Block*Objects.BlockW;
  Objects.canvasHeight=Objects.id.length*Objects.BlockH;
    if(Objects.canvasHeight==0) Objects.canvasHeight = 1;
  Objects.Conditions = JSON.parse(storage.getItem("_Conditions"));
  if (typeof rangestart === undefined) {
	rangestart = "";
  }
  if (typeof rangeend === undefined) {
        rangeend = "";
  }
  _addPrimer3Track(storage.getItem("_Prm_str"));
  _addBlastTrack(storage.getItem("_Blst_str"));

  if(phenotypeFlg){
	  _getPhenolist();
	  var phenotype = storage.getItem("_Phenotype");
	  _getPheno(phenotype);
	  Objects.TotalChrsSize=_getTotalChrsSize();
	  Objects.ChrBeginPosOnAll=_getChrBeginPosOnAll();
	  Objects.Plot=storage.getItem("_Plot");
  }
  
  var CaWid = Objects.canvasWidth+265;
  var Pos;
  if(/k/.test(Objects.Zoom)) {
        Pos = Objects.Zoom.replace(/k/,"000");
  } else {
        Pos = Objects.Zoom.replace(/b/,"");
  }
  var start = (Objects.Pos-1)*Pos+1;
  var startrim = String( start ).replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,' );
  var end = (Objects.Pos-1)*Pos+Pos*Objects.Block;
  var endtrim = String( end ).replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,' );
  //$("#showPos").html("&nbsp;&nbsp;<span style=\"background:white;text-align:left;font-size:16px;font-family:Helvetica;\">&nbsp;"+Objects.Chr+":"+startrim+"-"+endtrim+"bp&nbsp;</span>&nbsp;<input type=\"text\" id=\"searchTrk\" name=\"ONDIALOG\" size=\"35\" placeholder=\"eg.Os01g0100100-01,chr01:1-100\"></input><button name=\"GO\" onclick=\"searchOnTrack();\">GO</button>");
  $("#showPos").html("&nbsp;&nbsp;<span style=\"text-align:left;font-size:16px;font-family:Helvetica;color:white;position:relative;top:5px\">&nbsp;"+Objects.Chr+":"+startrim+"-"+endtrim+"&nbsp;</span>&nbsp;<input type=\"text\" id=\"searchTrk\" name=\"ONDIALOG\" size=\"35\" placeholder=\"eg.Os01g0100100-01,chr01:1-100\" style=\"position:relative;top:2px\"></input><button name=\"GO\" onclick=\"searchOnTrack();\" style=\"position:relative;top:2px\">SEARCH</button>");
  storage.setItem("_nowPos",Objects.Chr+":"+startrim+"-"+endtrim+"bp");
  //$("#tasuke").css("min-width",CaWid+"px");
  $("#tasuke").css("min-width",parseInt(CaWid)+parseInt(20)+"px");
  //$("#content").css("min-width",CaWid+"px");
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  var zm = _cvtZoom(en.nuc_max);
  if(!zm){zm=4000;}
  if (_cvtZoom(Objects.Zoom) > zm && Objects.Onebase=="on"){
    storage.setItem("_Onebase", "off");
    _drawCanvas();
  }
  _overWriteColorFromEnv();
  _setMinColor("snp");
  _setMinColor("indel");
  _setMenu();
  _hideLoading();
  _initCanvas();
  _drawTitle(null);
  _drawTOP();
  _drawRefName();
  _drawZoombar();
  _drawNULLBlock();
  if(phenotypeFlg){
	  if (storage.getItem('_Tpos') === undefined) {
	  	_drawPlot();
	  } else {
		_drawPlot(storage.getItem('_Tpos'));
	  }
/*
	  if (storage.getItem("_GWAS") == "off") {
                _drawPhyloName();
          }
*/
  } else {
	$("#track").css('border-bottom','1px #c3c3c3 solid');
  }
  if ( Objects.Snpblock == "off" ) {
    if(Objects.Onebase == "off"){
      switch (Objects.Mode) {
        case "dp":
          _drawDPBlock()
          $('#snpt').hide("slow");
          break;
        case "dp+s":
          _drawDPBlock()
          x = (Objects.Zoom != "1b") ? _drawSNPBlock(1) : _drawSNPBlock(3);
          $('#snpt').show("slow");
          break;
        case "dp+i":
          _drawDPBlock()
          x = (Objects.Zoom != "1b") ? _drawINDELBlock(1) : _drawINDELBlock(3);
          $("#snpt").show("slow");
          break;
        case "dp+a":
          _drawDPBlock()
          x = (Objects.Zoom != "1b") ? _drawSNPBlock(2) : _drawSNPBlock(3);
          x = (Objects.Zoom != "1b") ? _drawINDELBlock(2) : _drawINDELBlock(3);
          $("#snpt").show("slow");
          break;
        case "s":
          //x = (Objects.Zoom != "1b") ? _drawSNPBlock(0,"ctx4") : _drawSNPBlock(3);
          x = (Objects.Zoom != "1b") ? _drawSNPBlock(0) : _drawSNPBlock(3);
          $("#snpt").show("slow");
          break;
        case "i":
          x = (Objects.Zoom != "1b") ? _drawINDELBlock(0) : _drawINDELBlock(3);
          $('#snpt').show("slow");
          break;
        case "si":
          x = (Objects.Zoom != "1b") ? _drawSNPBlock(4) : _drawSNPBlock(3);
          x = (Objects.Zoom != "1b") ? _drawINDELBlock(4) : _drawINDELBlock(3);
          $("#snpt").show("slow");
          break;
      }
    }else{
      if(/dp/.test(Objects.Mode)) _drawDPBlock();
      _drawGTVariant();
      if(Objects.Mode == 'dp') {
          $('#snpt').hide("slow");
      } else {
         $('#snpt').show("slow");
      }
    }
  } else {
    if (Objects.Mode == "dp" || Objects.Mode == "dp+s" || Objects.Mode == "dp+i" || Objects.Mode == "dp+a") {
      _drawDPBlock()
      _drawSNPEstimationBlock();
      x = (Objects.Zoom != "1b") ? _drawSNPBlock(1) : _drawSNPBlock(3);
      $('#snpt').show("slow");
    } else{
      _drawSNPEstimationBlock();
      x = (Objects.Zoom != "1b") ? _drawSNPBlock(5) : _drawSNPBlock(3);
      $("#snpt").show("slow");
    }
  }
  _drawRegionHighlightCvs(cvs4);
//  _drawRegionHighlight(start,end);

  // for draginw without indicator
  frameCellwoI=ctx4.getImageData(0, 0, cvs4.width, cvs4.height);
  // Indicator
  if ( Objects.Indicator == "on" ) {
    _drawIndicator();
    _drawDirection();
  } else{
    var element = document.getElementById("cvs_ind"); 
    element.style.width = '0px'; 
    element.style.height = '0px'; 
    $('#prm_idc').val("off");
  }

  // when canvas height is changed
  var crtCvs1H=cvs1.height;
  var prtMesFeatID=false;
  if(storage.getItem("_TrackID")=="on") {
    Objects.TrackH=_getTrack("view").length*80+1;
  } else{
    Objects.TrackH=_getTrack("view").length*40+1;
  }
  if ( Objects.Zoom == "1b" ) Objects.TrackH=Objects.TrackH+20;
  if ( Objects.Zoom == "1b" && Objects.Amino == "on" ) Objects.TrackH=Objects.TrackH+45;
  if(crtCvs1H != Objects.TrackH && Objects.Zoom != "1b"){
    prtMesFeatID=true;
    crtCvs1H = Objects.TrackH;
    _drawCanvas();
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("scroll", true, true);
    content.dispatchEvent(evt);
  }

  // Capture image from canvas
  frameCell=ctx4.getImageData(0, 0, cvs4.width, cvs4.height);
  frameTitle=ctx3.getImageData(0, 0, cvs3.width, cvs3.height);
  frameChr=ctx2.getImageData(0, 0, cvs2.width, 37);
  frameNav=ctx2.getImageData(0, 30, cvs2.width, 20);
  frameTrackTitle=ctx0.getImageData(0, 0, cvs0.width, cvs0.height);
  frameTrackwR=ctx1.getImageData(0, 0, cvs1.width, cvs1.height);
  frameSNPTitle=ctx5.getImageData(0, 0, cvs5.width, cvs5.height);
  frameSNP=ctx6.getImageData(0, 0, cvs6.width, cvs6.height);
  frameZoomb=ctx9.getImageData(0, 0, cvs9.width, cvs9.height);
  frameInd=ctx7.getImageData(0, 0, cvs7.width, cvs7.height);

  if(phenotypeFlg){
	  framePlot = ctx12.getImageData(0, 0, cvs12.width, cvs12.height);
  }

  if(prtMesFeatID){
    _messageOnScreen("Viewing the feature ID was turned off");
    prtMesFeatID=false;
  }
  _setClickPhenotypeMainEvent();
  _checkInput();
  //_closeErr();
  //$('#content').css('min-width','');
  //$('#content').css('max-width',window.innerWidth - 38);

  // for TEST
/*
  var date="";
  $.ajax({
    url: "./bin/test.php",
    cache: false,
    async: false,
  });
*/
}

///////////////////////////// Drawing meter by _drawTOP()
function _drawMeter(pos,pointer) {
  var blk=Objects.Block;
  var end=pos+blk;
  var m=parseInt(blk/10);
  
  ctx2.clearRect(0, 27, cvs2.width, cvs2.height);

  // Meter
  ctx2.beginPath();
  ctx2.moveTo(0,39);
  ctx2.lineTo(cvs2.width,39);
  ctx2.closePath();
  ctx2.lineWidth=1;
  ctx2.strokeStyle=_setColor().chrborder;
  ctx2.stroke();
  ctx2.fillStyle=_setColor().detailarea;
  ctx2.fillRect(0,40,cvs2.width,50);
  ctx2.fillStyle=_setColor().meterstring;
  ctx2.textAlign="left";
  //ctx2.font="11px 'Century'";
  ctx2.font="11px 'Helvetica'";
  ctx2.fillText(_printPos(pos),2, 52);
  ctx2.textAlign="center";
  for (var i=1; i<m; i++) ctx2.fillText(_printPos(pos+parseInt(blk/m)*i),cvs2.width/m*i, 52);
  ctx2.textAlign="right";
  ctx2.fillText(_printPos(end),cvs2.width-2, 52);
  if ( pointer != null ) {
    if(pointer >=parseInt(cvs2.width/2)) {
    	ctx2.beginPath();
    	ctx2.moveTo(pointer,40);
    	ctx2.lineTo(pointer-10,28);
    	ctx2.lineTo(pointer-2,28);
    	ctx2.closePath();
    	ctx2.fillStyle=_setColor().pointercolor;
    	ctx2.fill();
   	ctx2.fillStyle=_setColor().pointerstringcolor;
    	ctx2.textAlign="right";
    	ctx2.fillText(_printPos(pos+parseInt(pointer/Objects.BlockW)), pointer-12, 36);
    } else {
        ctx2.beginPath();
        ctx2.moveTo(pointer,40);
        ctx2.lineTo(pointer+2,28);
        ctx2.lineTo(pointer+10,28);
    	ctx2.closePath();
    	ctx2.fillStyle=_setColor().pointercolor;
    	ctx2.fill();
    	ctx2.fillStyle=_setColor().pointerstringcolor;
	ctx2.textAlign="left";
        ctx2.fillText(_printPos(pos+parseInt(pointer/Objects.BlockW)), pointer+13, 36);
    }
  }
}

/////////////////////////////////////////////////////////// Draw chromosome
function _drawChromosome(){
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  ctx2.clearRect(0, 0, cvs2.width, 30);
  o=_chromosome();
  ctx2.beginPath();
  if(o.centromere > 0){
    ctx2.moveTo(6,8);
    ctx2.lineTo(o.centromere-5,8);
    ctx2.lineTo(o.centromere+5,25);
    ctx2.lineTo(o.width-6, 25);
    ctx2.arcTo(o.width, 25, o.width, 20, 6);
    ctx2.lineTo(o.width, 17);
    ctx2.arcTo(o.width, 8, o.width-5, 8, 6);
    ctx2.lineTo(o.centromere+5,8);
    ctx2.lineTo(o.centromere-5,25);
    ctx2.lineTo(6,25);
    ctx2.arcTo(1, 25, 1, 16, 6);
    ctx2.lineTo(0, 15);
    ctx2.arcTo(1, 8, 6, 8, 6);
  } else {
    ctx2.moveTo(6,25);
    ctx2.lineTo(o.width-6, 25);
    ctx2.arcTo(o.width, 25, o.width, 20, 6);
    ctx2.lineTo(o.width, 17);
    ctx2.arcTo(o.width, 8, o.width-5, 8, 6);
    ctx2.lineTo(6,8);
    ctx2.arcTo(1, 8, 1, 14, 6);
    ctx2.lineTo(0, 17);
    ctx2.arcTo(1, 25, 6, 25, 6);	
  }
  ctx2.closePath();
  ctx2.fillStyle=_setColor().chrcolor;
  ctx2.fill();
  ctx2.lineWidth=1;
  ctx2.strokeStyle=_setColor().chrborder;
  ctx2.stroke();
  ctx2.fillStyle=_setColor().chrstringcolor;
  ctx2.font="12px 'Helvetica'";
  ctx2.textAlign='right';
  ctx2.fillText(en.chromosome_name+Objects.Chr,o.width-5, 20);
  // Box area on chromosome
  ctx2.fillStyle=_setColor().chrareacolor;
  ctx2.fillRect(o.pos-1, 9, o.area+1, 16);
  // Start position of details meter
  var half=cvs2.width/2;
/*
  ctx2.fillStyle=_setColor().chrcolor;
  ctx2.fillRect(half+half/5*2, 11, (half+half/5*2-o.s1)-(half+half/5*2), 12);
  ctx2.fillRect(half+half/5*3, 11, (half+half/5*3+o.s2)-(half+half/5*3), 12);
  ctx2.moveTo(half+half/5*2,11);
  ctx2.lineTo(half+half/5*2-o.s1,11);
  if ( o.s1 < half/5*2 ) ctx2.lineTo(half+half/5*2-o.s1,23);
  ctx2.moveTo(half+half/5*2,23);
  ctx2.lineTo(half+half/5*2-o.s1,23);
  ctx2.moveTo(half+half/5*3,11);
  ctx2.lineTo(half+half/5*3+o.s2,11);
  if ( o.s2 < half/5*2 ) ctx2.lineTo(half+half/5*3+o.s2,23);
  ctx2.moveTo(half+half/5*3,23);
  ctx2.lineTo(half+half/5*3+o.s2,23);
  ctx2.lineWidth=1.5;
  ctx2.stroke();
*/
  // Show area
/*
  ctx2.fillStyle=_setColor().detailarea;
  ctx2.fillRect(half+half/5*2, 10, half/5, 14);
  ctx2.fillStyle=_setColor().detailstring;
  ctx2.textAlign='center';
  ctx2.fillText("Show "+_printArea(Objects.Block),half+half/5*2+half/5/2, 21);
*/

  // draw RegionHighLight
  var regHighlights = storage.getItem("_RegHighlights");
  while(regHighlights != null && regHighlights != '') {
    var hls = JSON.parse(regHighlights);
    if( !(hls instanceof Array) ) break;
    var chrSize = _getChr(Objects.Chr).size;
    for(var i=0,hlsLen=hls.length; i<hlsLen; i++) {
      if(hls[i].chr != Objects.Chr) continue;
      var st = hls[i].st;
      var en = hls[i].en;
      var stX = parseInt( o.width * st / chrSize );
      var widthX = parseInt(o.width * (en - st + 1)  / chrSize);
//      if(widthX < 1) widthX = 1;
      ctx2.lineWidth=1;
      ctx2.strokeStyle = "rgba(0,0,0,0.8)";
      ctx2.strokeRect(stX, 5, widthX, 22);
//      ctx2.fillStyle = "rgba(0,255,0,0.7)";
//      ctx2.fillRect(stX, 5, widthX, 22);
    }
    break;
  }

  ctx2.fillStyle=_setColor().detailstring;
  ctx2.font="11px 'Helvetica'";
  ctx2.textAlign='left';
  //ctx2.fillText(_printPos(Objects.Pos),half+half/5*2+6, 9);
  ctx2.fillText(_printPos(Objects.Pos),o.pos+6, 9);
/*
  ctx2.beginPath();
  ctx2.moveTo(half+half/5*2,10);
  ctx2.lineTo(half+half/5*2-3,2);
  ctx2.lineTo(half+half/5*2+3,2);
  ctx2.closePath();
  ctx2.fillStyle="orange";
  ctx2.fill();
*/
  ctx2.beginPath();
  ctx2.moveTo(o.pos,10);
  ctx2.lineTo(o.pos-3,2);
  ctx2.lineTo(o.pos+3,2);
  ctx2.closePath();
  ctx2.fillStyle="orange";
  ctx2.fill();
}

///////////////////////////// Drawing top
function _drawTOP() {
  _drawMeter(parseInt(storage.getItem('_Pos')),null);
  _drawChromosome();
  _drawTracks();
}

///////////////////////////// Drawing sequence name
function _drawRefName(){
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  ctx11.fillStyle=_setColor().reftitle;
  ctx11.font="14px 'Arial'";
  //ctx11.textAlign="center";
  ctx11.textAlign="left";

  var pxByChar = 7;
  var stringX = parseInt(Objects.titleWidth/2 - (140 - Objects.titleWidth)/2 - (en.reference_name.length - 9)*pxByChar);
	if(stringX < 0) stringX = 0;
  var strinxMaxW = Objects.titleWidth - stringX - 2;
	if(strinxMaxW < 100) strinxMaxW = 100;
  ctx11.fillText(en.reference_name, stringX, 11, strinxMaxW);
}

///////////////////////////// Drawing tracks
function _drawTracks(fastaPos) {
  var to=new Object(JSON.parse(storage.getItem("_Tracks")));
//  var to_prm=new Object(JSON.parse(storage.getItem("_Tracks_rpm")));
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  var ta=_getTrack("view");
  var rowHeight=40;
  if (storage.getItem("_TrackID")=="on"){
    isConflict = _trackConflict();
    if(isConflict){
      storage.setItem("_TrackID", "off");
    }else{
      rowHeight=80;
    }
  }

  ctx0.clearRect(0, 0, cvs0.width, cvs0.height);
  ctx0.fillStyle="#dcdcdc";
  ctx0.fillRect(0, 0, cvs0.width, cvs0.height);
  ctx1.clearRect(0, 0, cvs1.width, cvs1.height);
  ctx0.fillStyle=_setColor().tracktitle;
  ctx0.textAlign="right";
  ctx0.font="12px 'Arial'";
  ctx1.textAlign="center";
  ctx1.font="10px 'Arial'";

  // Each tracks
  for (var i=0, taLen=ta.length; i<taLen; i++) {
    for (var j=0, toLen=to.length; j<toLen; j++) {
      if ( ta[i] == to[j].track ) {
        ctx0.fillText(to[j].track,cvs0.width-5, i*rowHeight+10);   // Title
	if(to[j].track=="Primer3 Result"){
           _drawTrack("_Track_prm",i,fastaPos,to[j].h,to[j].c,to[j].t,rowHeight);
	} else if(to[j].track=="Blast Result") {
	   _drawTrack("_Track_blst",i,fastaPos,to[j].h,to[j].c,to[j].t,rowHeight);
        }else{
          _drawTrack("_Track_"+j,i,fastaPos,to[j].h,to[j].c,to[j].t,rowHeight); // Track
        }
      }
    }
  }

  // References
  var revBase = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'M':'K', 'K':'M', 'R':'Y', 'Y':'R', 'N':'N'};
  if ( Objects.Zoom == '1b' ) {
    if ( storage.getItem('_Ref') == "Reference" ) {
      //ctx0.font="Bold italic 13px 'Courier'";
      ctx0.font="Bold 13px 'Arial'";
      ctx0.fillStyle=_setColor().reftitle;
    }
    ctx0.fillText(en.reference_name, cvs0.width-20, cvs0.height-1);
    ctx0.font="11px 'Century'";
    ctx0.fillStyle="black";
    ctx0.beginPath();
    ctx0.arc(cvs0.width-10, cvs0.height-6, 6, 0, Math.PI*2, false);
    ctx0.fill();
    ctx0.fillStyle="white";
    ctx0.fillRect(cvs0.width-15, cvs0.height-7, 10, 2);
    if ( storage.getItem("_DirRef") == "+" ) {
      ctx0.fillRect(cvs0.width-11, cvs0.height-11, 2, 10);
    }
    ctx0.fillStyle=_setColor().tracktitle;
    var f=new Object(JSON.parse(storage.getItem('_FASTA')));
    var ArrF=new Array();
    for (var i=0,fLen=f.length; i<fLen; i++){
      var s=f[i].f;
      if ( storage.getItem("_DirRef") == "-" ) {
        var ls=true;
        if ( s == s.toUpperCase() ) ls=false;
        s = revBase[ f[i].f.toUpperCase() ];
        if(!s) s="";	// Not verified
        if ( ls ) s=s.toLowerCase();
      }
      ArrF.push(s);
    }
    for (e=0, fLen=f.length; e<fLen; e++){
      if(fastaPos == e) {
        ctx1.fillStyle=_setColor().fastabold;
        yPos=cvs1.height-8;
      }else{
        ctx1.fillStyle=_setColor().fasta;
        yPos=cvs1.height-1;
      }
      var strF=ArrF[e];
      ctx1.fillText(strF, (e*Objects.BlockW)+(Objects.BlockW/2), yPos);
    }
    // Amino acids when '1b'
    if ( Objects.Amino == "on" ) {
      ctx0.font = "12px 'Arial'";
      ctx0.fillText("Amino acids", cvs0.width-5, cvs0.height-35);
      _drawAmino(ArrF);
    }
  }
  _drawRegionHighlightCvs(cvs1);

  // Capture tracks without rules
  frameTrack=ctx1.getImageData(0, 0, cvs1.width, cvs1.height);
  // draw scale bar.
  _drawRules();
}

///////////////////////////// Drawing Rules
function _drawRules() {
  var ta=_getTrack("view");
  var rowHeight=40;
  if(storage.getItem("_TrackID")=="on"){rowHeight=80;}
  var m=parseInt(Objects.Block/(rowHeight/4));
  for(var i=0;i<m+1;i++){
    var lw = 0.2;
    var lc = [26,26,26,0.5];
    if (i==0 || i==m) {
      lw = 6;
      lc = [208,208,208,0.5];
    }
    ctx1.beginPath();
    ctx1.moveTo(Objects.canvasWidth/ m * i, 0);

    ctx1.lineTo(Objects.canvasWidth/ m * i, cvs1.height);
/*
    if(storage.getItem("_Track_prm") !== undefined){
      ctx1.lineTo(Objects.canvasWidth/ m * i, 400);
    } else {
      ctx1.lineTo(Objects.canvasWidth/ m * i, 80);
    }
*/
    ctx1.lineWidth = lw;
    ctx1.strokeStyle = "rgba(" + lc + ")";
    ctx1.stroke();
  }
}

///////////////////////////// Drawing amino acids
function _drawAmino(ArrF) {
  var yPos=cvs1.height-20;
  var t=parseInt(Objects.Pos)-parseInt(Objects.Pos/3)*3;
  if ( t > 0 ) t=3-t;
  for (var i=t; i<t+3; i++) {
    var subt=0;
    if ( i > t && i >2 ) subt=3;
    var ArrFLen = ArrF.length;
    for (var e=(i-subt); e<ArrFLen; e=e+3){
      if ( e+2 < ArrFLen ) { 
        var str="";
        if ( storage.getItem("_DirRef") === "+" ) {
          str=ArrF[e]+ArrF[e+1]+ArrF[e+2];
        } else {
          str=ArrF[e+2]+ArrF[e+1]+ArrF[e];
        }
        var aStr=_get_amino(str);
        if ( aStr !== "-" ) {
          if ( aStr === "M" ) {
            ctx1.lineWidth=3;
            ctx1.strokeStyle="green";
            ctx1.strokeRect(e*Objects.BlockW+1, yPos-10, Objects.BlockW*3-2, 13);
          } else if ( aStr === "*" ) {
            ctx1.lineWidth=3;
            ctx1.strokeStyle="brown";
            ctx1.strokeRect(e*Objects.BlockW+1, yPos-10, Objects.BlockW*3-2, 13);
          } else {
            ctx1.lineWidth=1;
            ctx1.strokeStyle="rgb(60,60,60)";
            ctx1.strokeRect(e*Objects.BlockW+1, yPos-10, Objects.BlockW*3-2, 13);
          }
          ctx1.fillStyle=_setColor().amino;
          ctx1.fillText(aStr, (e+1)*Objects.BlockW+(Objects.BlockW/2), yPos);
        }
      }
    }
    yPos=yPos-15;
  }
}

///////////////////////////// Drawing each tracks
function _drawTrack(name,hir,fastaPos,depth,color,type,rowHeight) {
  var yP=hir*rowHeight;
  var eachRowHeight=rowHeight/4;
  var yH=7;
  var o=new Object(JSON.parse(storage.getItem(name)));
  ctx1.lineWidth=1;

  var zoom = _cvtZoom(Objects.Zoom);
  var startRef = (Objects.Pos-1)*zoom+1;
  
  for (var k=0, oLen=o.length; k<oLen; k++){
/* Recalculate without rs/re, because the accuracy is lost and the bar shifts.
    var startS=o[k].rs;
    var startE=o[k].re;
    var width=(startE-startS)*Objects.BlockW;
*/
    var startS = (parseInt(o[k].pos) - startRef) / zoom;				// Gene left block from left edge of canvas(Decimal)
    var startE = (parseInt(o[k].pos) + parseInt(o[k]['length']) - startRef) / zoom;	// Gene right block from right edge of canvas(Decimal)
    var width = (startE-startS)*Objects.BlockW;						// Gene block width(Decimal)
    var Hs=o[k].h;	// Track row to draw;
    if ( _cvtZoom(Objects.Zoom) > 4000 || depth == 1 ) Hs=2;	// If drawing range is too wide, track cannot be drawn normally, so it will be put on one line.

    var leftBase = startS * Objects.BlockW;		// Gene left Coordinate from left edge of canvas
    var rightBase = startE * Objects.BlockW;		// Gene right Coordinate from left edge of canvas
    var topBase = yP + (Hs - 1) * eachRowHeight;	// Gene top Coordinate from top edge of canvas

    var keywd = Objects.Keyword;
    var o_id = o[k].id;

    // Gene highlight
    if ( o_id.match(keywd) && o[k].id != "" && keywd != "" ) {
      ctx1.fillStyle=_setColor().highlight;
      ctx1.fillRect(
		(startS - 1) * Objects.BlockW,
		topBase - 1,
		(startE - startS + 1) * Objects.BlockW+6,
		yH+2
	);
//      ctx1.fillRect((o[k].rs-1)*Objects.BlockW, yP+(Hs-1)*eachRowHeight-1, (o[k].re-o[k].rs+1)*Objects.BlockW+6, yH+2);
    }
    //Additional track(Primer3/Blast)
    if(o[k].t !== undefined && (o[k].t.match(/target/) || o[k].t.match(/hsp/))) {
	var transcript=o[k].t.split(";");
	for (var m=0, transcriptLen=transcript.length; m<transcriptLen; m++) {
                var transcripts=transcript[m].split("-");
                if ( transcripts[0] == "lPrm" ) {
                        ctx1.fillStyle="#ff6699";
                } else if( transcripts[0] == "target" ){
                        ctx1.fillStyle="#ff0000";
                } else if( transcripts[0] == "rPrm" ){
                        ctx1.fillStyle="#0099ff";
                } else if( transcripts[0] == "hsp" ) {
			ctx1.fillStyle = color;
		}
		var leftPx = leftBase + (width*(transcripts[1])/100);
		var rightPx = leftPx + width*(transcripts[2]/100) - 1;
		if(leftPx > cvs1.width || rightPx < 0) continue;
			if(leftPx < 0)  leftPx = 0;
			if(rightPx > cvs1.width) rightPx = cvs1.width;

		ctx1.fillRect(leftPx , topBase, rightPx-leftPx+1, yH);
//                ctx1.fillRect(startS*Objects.BlockW+(width*(transcripts[1])/100) ,yP+(Hs-1)*eachRowHeight, width*(transcripts[2]/100), yH);
        }
    }
    // Normal Track
    if ( _isEmpty(o[k].t))  {
      // Have no child = not transcript
      ctx1.fillStyle="black";
      ctx1.fillRect(leftBase, topBase, width, yH);
    } else if (o[k].t.match(/target/) || o[k].t.match(/hsp/)) {
      // Blast or Primer3 result.
    } else {// Transcripts
      ctx1.strokeStyle="#000000";
      ctx1.beginPath();
      ctx1.moveTo(leftBase, topBase + 4);
      ctx1.lineTo(rightBase, topBase + 4);
      ctx1.stroke();
      var transcript=o[k].t.split(";");
      var utrs = [];
      var exons = [];
      var cdss = [];
      var others = [];
      var target = [];
      for(var n=0,transcriptLen=transcript.length; n<transcriptLen;n++) {
        if(transcript[n].match(/^u/)) {
                utrs.push(transcript[n]);
        } else if (transcript[n].match(/^e/)) {
                exons.push(transcript[n]);
        } else if (transcript[n].match(/^a/)) {
		others.push(transcript[n]);
        } else if (transcript[n].match(/^c/)) {
                cdss.push(transcript[n]);
	}
      }

      // Rejoin array
      transcript = [];
      transcript = transcript.concat(others).concat(exons).concat(cdss).concat(utrs);

      for (var m=0, transcriptLen=transcript.length; m<transcriptLen; m++) {
        var transcripts=transcript[m].split("-");
        if ( transcripts[0] === "u" ) {
          ctx1.fillStyle="sandybrown";
        } else if( transcripts[0] === "c" ){
          ctx1.fillStyle=color;
        } else if( transcripts[0] === "e" ){
          ctx1.fillStyle="green";
        } else if( transcripts[0] === "a" ){
          ctx1.fillStyle="yellow";
        }
        ctx1.fillRect(leftBase + (width*(transcripts[1])/100), topBase, width*(transcripts[2]/100), yH);
      }
    }
    // Strand arrow
    if ( !_isEmpty(o[k].strand) ) {
      ctx1.strokeStyle="orange";
      ctx1.beginPath();
      if ( parseInt(o[k].strand) ) {
        ctx1.moveTo(rightBase, topBase + 4);
        ctx1.lineTo(rightBase + 7, topBase + 4);
        ctx1.moveTo(rightBase + 4, topBase);
        ctx1.lineTo(rightBase + 7, topBase + 4);
        ctx1.lineTo(rightBase + 4, topBase + 7);
      } else {
        ctx1.moveTo(leftBase, topBase + 4);
        ctx1.lineTo(leftBase - 7, topBase + 4);
        ctx1.moveTo(leftBase - 4, topBase);
        ctx1.lineTo(leftBase - 7, topBase + 4);
        ctx1.lineTo(leftBase - 4, topBase + 7);
      }
      ctx1.stroke();
    }
    if(type=="DE"){
      /*
      console.log("!");
      ctx1.beginPath();
      ctx1.moveTo(startE*Objects.BlockW+10, yP+(Hs-1)*eachRowHeight);
      ctx1.lineTo(startE*Objects.BlockW, yP+(Hs-1)*eachRowHeight+parseInt(yH/2));
      ctx1.lineTo(startE*Objects.BlockW+10, yP+(Hs-1)*eachRowHeight+yH);
      ctx1.closePath();
      ctx1.fill();
      */
    }
    if(storage.getItem("_TrackID") == "on" && _cvtZoom(Objects.Zoom) < 5000 ){
      ctx1.textAlign="left";
      var metrics = ctx1.measureText(o[k].id);
      if(metrics.width>100){metrics.width=100;}
      ctx1.fillStyle=_setColor().bgcolor;
      ctx1.fillRect(leftBase, yP+(Hs*eachRowHeight)-12, metrics.width, 10);
      ctx1.fillStyle=_setColor().locusid;
      ctx1.fillText(o[k].id, leftBase, yP+(Hs*eachRowHeight)-2, metrics.width);
    }
  }
}

/////////////////////////////////////////////// Commas in number
function _numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

var ONINFOCELL=new Object();
var CELLINFODRAW;
var THISACC;
/////////////////////////////////////////////// Detail of cell
function _drawInfoCell(id,b,y,str){
  // Clear canvas
  ctx4.putImageData(frameCell, 0, 0);
  if(phenotypeFlg) {
    ctx12.putImageData(framePlot, 0, 0);
  }
  // Position
  var ao=new Object(JSON.parse(_getCompressedData(id)));
  var o=new Object(JSON.parse(str));
//console.log(str);
  CELLINFODRAW = Object(JSON.parse(str));
  var xo=b*Objects.BlockW;
  var yo=parseInt(y/Objects.BlockH)*Objects.BlockH;
  var yi=5;
  var xi=5;
  var width=460;
  var cstm=storage.getItem("_CSTM");
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  var elementView = document.getElementById("cvs_view");
  var bounds = elementView.getBoundingClientRect(); 
  var boux = bounds.left;
  var bouy = bounds.top;
  var element = document.getElementById("cellinf"); 
  element.style.top = (parseInt(bouy)+parseInt(yo)+Objects.BlockH+(document.body.scrollTop || document.documentElement.scrollTop))+'px'; 
  if(((parseInt(boux)+parseInt(xo)+Objects.BlockW)+420+(document.body.scrollLeft || document.documentElement.scrollLeft)) > (Objects.BlockW*(Objects.Block+2))+Objects.titleWidth){
    element.style.left = (parseInt(boux)+parseInt(xo)-(Objects.BlockW)-420+(document.body.scrollLeft || document.documentElement.scrollLeft))+'px'; 
  }else{
    element.style.left = (parseInt(boux)+parseInt(xo)+Objects.BlockW+(document.body.scrollLeft || document.documentElement.scrollLeft))+'px'; 
  }
  
  var cnt=0;
  for(var i in o){cnt++;}
  if(_cvtZoom(Objects.Zoom)>4000 || storage.getItem("_Ref") != "Reference"){
    if ( _isEmpty(ao[b].s) && _isEmpty(ao[b].i) && _isEmpty(ao[b].d) ){
      cvs10.height = 40;
    }else{
      cvs10.height = 75;
    }
  }else{
    if(cnt>1){
      cvs10.height = (65+(cnt*17));
    }else{
      cvs10.height = 40;
    }
  }
  cvs10.width=470;
  ctx10.clearRect(0, 0, cvs10.width, cvs10.height);
  ctx10.fillStyle='rgba(0,0,0,0)';
  ctx10.fillRect(0,0,cvs10.width,cvs10.height);

  // Range of cell
  var strRange="";
  THISACC = Objects.db[parseInt(y/Objects.BlockH)];
  if (Objects.Name=="id") strRange="["+Objects.id[parseInt(y/Objects.BlockH)]+": ";
  else strRange="["+Objects.name[parseInt(y/Objects.BlockH)]+": ";
  var e=(b+Objects.Pos)*_cvtZoom(Objects.Zoom);
  var s=e-_cvtZoom(Objects.Zoom)+1;
  if ( _cvtZoom(Objects.Zoom) > 1 ) strRange=strRange+_numberWithCommas(s)+" .. "+_numberWithCommas(e)+"]";
  else strRange=strRange+_numberWithCommas(e)+"]";

  // Flag this object
  ONINFOCELL.flag=true;
  ONINFOCELL.x=xi;
  ONINFOCELL.y=yi;
  ONINFOCELL.w=width;
  ONINFOCELL.cx=xo;
  ONINFOCELL.cy=yo;
  
  // Drawing selection
  ctx4.strokeStyle="rgba(255,0,0,0.5)";
  ctx4.lineWidth=2;
  ctx4.strokeRect(xo, yo, Objects.BlockW, Objects.BlockH);

  // Shape
  ctx10.strokeStyle="#b0c4de";
  ctx10.fillStyle="#ffffff";
  ctx10.textAlign="left";
  //ctx10.font="10px 'Courier'";
  ctx10.font = "11px 'Century'";
  ctx10.lineWidth=5;

  // prepared string
  var condArray = storage.getItem("_CrtCondition").split("|");
  var cond = parseInt(condArray[0]);
  var splitted_rdp;
  if(_isUndefined(ao[b].rdp)){
    splitted_rdp = "";
  }else{
    splitted_rdp = ao[b].rdp.split("%");
  }
  //var splitted_rdp = ao[b].rdp.split("%");
  var cstm_name = "";
  //if(Objects.Conditions.length > 1){
  //  cstm_name = _escapeHTML(en.cstm_kind)+":"+Objects.Conditions[cond].id.substr(0, 10);
  //}else{
    cstm_name = _escapeHTML(en.cstm_kind);
  //}
  var strCSTMPri=" "+cstm_name+" is "+splitted_rdp[cond]+".";
  var strCSTM = cstm_name+":";
  for(var a=0; a<Objects.Conditions.length; a++){
    if ( !_isEmpty(splitted_rdp[a]) ) {
      strCSTM += Objects.Conditions[a].id+"="+splitted_rdp[a];
    }else{
      
      strCSTM += Objects.Conditions[a].id+"=empty";
    }
    if(a<Objects.Conditions.length-1){strCSTM += ", "}
  }
//  var infoCellStrBoth=" &lt;Depth is "+ao[b].dp+".&gt; &lt;"+strCSTM+"&gt;<br><br>";

  // DEPTH Info
  var strDepth = "";
  if(_isEmpty(ao[b].dp)) {
    strDepth = "Depth is empty.";
  } else {
    strDepth = " Depth is " + ao[b].dp + ".";
  }

  var strDepthDetail = "";
  if(cstm == "off" || cstm == "disabled"){
    strDepthDetail = strDepth;
  } else {
    strDepthDetail = " &lt;" + strDepth + ".&gt; &lt;" + strCSTM + "&gt;";
    if ( _isEmpty(splitted_rdp[cond]) ) {
      strDepth = " is empty.";
    } else {
      if(splitted_rdp[cond] != "n" && splitted_rdp[cond] != "x"){
        strDepth = strCSTMPri;
      } else {
       strDepth = "";
      }
    }
  }
  ONINFOCELL.str = strRange + strDepthDetail + "<br><br>";

  // PopUp size
  var popHeight = 30;
  ONINFOCELL.h=30;
  if( !_isEmpty(ao[b].s) || !_isEmpty(ao[b].i) || !_isEmpty(ao[b].d) ) {
    if(storage.getItem("_Ref") != "Reference" || _cvtZoom(Objects.Zoom)>4000){
      popHeight = 65;
      ONINFOCELL.h = 50;
    } else if (o.length) {// Variants
      popHeight = o.length*17+70;
      ONINFOCELL.h = o.length*17+70;
    }
  }
  ctx10.fillRect(xi, yi, width, popHeight);
  ctx10.strokeRect(xi, yi, width, popHeight);

  // draw Region/Depth info.
  ctx10.fillStyle="#000000";
  ctx10.fillText(strRange + strDepth, xi+10,yi+18);

  // Variant info
  var annclr = {MODIFIER:'#00BFFF', LOW:'#FFFF00', MODERATE:'#EE9A00', HIGH:'red'};
  if ( !_isEmpty(ao[b].s) || !_isEmpty(ao[b].i) || !_isEmpty(ao[b].d) ) {
    var st=new Array();
    var it=new Array();
    var dt=new Array();
      if ( !_isEmpty(ao[b].s) ) st=ao[b].s.split("^");
      if ( !_isEmpty(ao[b].i) ) it=ao[b].i.split("^");
      if ( !_isEmpty(ao[b].d) ) dt=ao[b].d.split("^");
//    if ( !_isEmpty(ao[b].s) ) st=ao[b].s.split("-");
//    if ( !_isEmpty(ao[b].i) ) it=ao[b].i.split("-");
//    if ( !_isEmpty(ao[b].d) ) dt=ao[b].d.split("-");

    // Variant:SNP
    var stNum = 0;
    if ( !_isEmpty(st) ) {
      if(parseInt(st[0])>_getMaxGraSNP()){
        ctx10.fillStyle=grad_S(1);
      } else {
        ctx10.fillStyle=grad_S(parseInt(st[0])/_getMaxGraSNP());
      }
      stNum = parseInt(st[0]);
    } else {
      ctx10.fillStyle="#fff";
    }
    ctx10.fillRect(xi+13,yi+30,10,10);
    ctx10.strokeStyle="#000";
    ctx10.lineWidth=1;
    ctx10.strokeRect(xi+13,yi+30,10,10);
    ctx10.fillStyle="#000";
    ctx10.fillText("SNP=" + stNum, xi+27,yi+38);

    // Variant:inDel
    var sum = 0;
    if ( !_isEmpty(it) || !_isEmpty(dt)) {
      if ( !_isEmpty(it) ) sum = parseInt(it[0]);
      if ( !_isEmpty(dt) ) sum = sum + parseInt(dt[0]);
      if(sum>_getMaxGraINDEL()){
        ctx10.fillStyle=grad_INDEL(1);
      } else {
        ctx10.fillStyle=grad_INDEL(sum/_getMaxGraINDEL());
      }
    } else {
      ctx10.fillStyle="#fff";
    }
    ctx10.fillRect(xi+75,yi+30,10,10);
    ctx10.strokeStyle="#000";
    ctx10.lineWidth=1;
    ctx10.strokeRect(xi+75,yi+30,10,10);
    ctx10.fillStyle="#000";
    ctx10.fillText("INDEL="+sum,xi+89,yi+38);

    // SnpEff
    if ( Objects.Eff == "on" ) {
      ctx10.fillStyle="blue";
      ctx10.fillText("SnpEff: ",xi+170,yi+38);
      if ( !_isEmpty(st) ) {
        var color = _getSnpeffImpactColor(st[1]);
/*
        if (parseInt(st[1])==0) color="#00BFFF";
        if (parseInt(st[1])==1) color="#FFFF00";
        if (parseInt(st[1])==2) color="#EE9A00";
        if (parseInt(st[1])==3) color="red";
*/
        var effstr;
        if (st[1] == 0) {
                effstr = "MODIFIER";
        } else if (st[1] == 1) {
                effstr = "LOW";
        } else if (st[1] == 2) {
                effstr = "MODERATE";
        } else if (st[1] == 3) {
                effstr = "HIGH";
        }

        ctx10.fillStyle=color;
        ctx10.fillRect(xi+210,yi+30,10,10);
        ctx10.strokeStyle="#000";
        ctx10.lineWidth=1;
        ctx10.strokeRect(xi+210,yi+30,10,10);
        ctx10.fillStyle="#000";
        ctx10.fillText(effstr,xi+255,yi+38);
        ctx10.fillStyle="#000";
        ctx10.fillText("SNP=",xi+225,yi+38);
      } else {
        ctx10.fillStyle="#fff";
        ctx10.fillRect(xi+210,yi+30,10,10);
        ctx10.strokeStyle="#000";
        ctx10.lineWidth=1;
        ctx10.strokeRect(xi+210,yi+30,10,10);
        ctx10.fillStyle="#000";
        ctx10.fillText("SNP 0",xi+225,yi+38);
      }
      if ( !_isEmpty(it) || !_isEmpty(dt)) {
        var comp1=0;
        var comp2=0;
        if ( !_isEmpty(it) ) comp1 = parseInt(it[1]);
        if ( !_isEmpty(dt) ) comp2 = parseInt(dt[1]);
        var max=0;
        if(comp1>comp2){
          max=comp1;
        } else {
          max=comp2;
        }
        var effstr;
        if (max==0) {
          effstr = "MODIFIER";
        } else if (max==1) {
          effstr = "LOW";
        } else if (max==2) {
          effstr = "MODERATE";
        } else if (max==3) {
          effstr = "HIGH";
        }
        color = _getSnpeffImpactColor(max);

        ctx10.fillStyle=color;
        ctx10.fillRect(xi+325,yi+30,10,10);
        ctx10.strokeStyle="#000";
        ctx10.lineWidth=1;
        ctx10.strokeRect(xi+325,yi+30,10,10);
        ctx10.fillStyle="#000";
        ctx10.fillText(effstr,xi+385,yi+38);
        ctx10.fillStyle="#000";
        ctx10.fillText("INDEL= ",xi+340,yi+38);
      } else {
        ctx10.fillStyle="#fff";
        ctx10.fillRect(xi+325,yi+30,10,10);
        ctx10.strokeStyle="#000";
        ctx10.lineWidth=1;
        ctx10.strokeRect(xi+325,yi+30,10,10);
        ctx10.fillStyle="#000";
        ctx10.fillText("INDEL 0",xi+340,yi+38);
      }
    } else if ( Objects.Snpblock != "off" ) {
      var cmp=_getSnpblock(Objects.db[parseInt(y/Objects.BlockH)]);
      if ( !_isEmpty(st) ) {
        if(parseInt(st[0])/_cvtZoom(Objects.Zoom)>=cmp){
          ctx10.fillStyle="blue";
          ctx10.fillText("Snpblock: "+st[0]+"/"+_cvtZoom(Objects.Zoom)+">="+cmp,xi+150,yi+38);
        }
      }
    }

    if(storage.getItem("_Ref") != "Reference" || _cvtZoom(Objects.Zoom)>4000) {
      // omit variant list.
      ctx10.fillText("(Only the number of variants are displayed.)",xi+8,yi+55);
      if(_cvtZoom(Objects.Zoom)>4000) {
        ONINFOCELL.str = ONINFOCELL.str + "(To display variant details, block size must be 4k or less.)";
      }
    } else {
      // draw variant list.
      chDtlCellView="pos";
      if("eff" in o[0] && o[0].eff != ""){
        if(chDtlCellView=="pos"){
          ONINFOCELL.str=ONINFOCELL.str+"<div id=\"chfmt\" align=right><button type=\"submit\" onClick=\"_changeFmtPos();\" >Change to each id</button></div>";
        }else{
          ONINFOCELL.str=ONINFOCELL.str+"<div id=\"chfmt\" align=right><button type=\"submit\" onClick=\"_changeFmtPos();\" >Change to each variants</button></div>";
        }
      }

      ONINFOCELL.each="";
      ONINFOCELL.str = ONINFOCELL.str + "<span id=cellDigInfo>";
      ctx10.fillStyle="brown";
//      if(o[0].eff != ""){
          ctx10.fillText($.format("%1$5s %2$15s %3$15s %4$15s %5$15s %6$15s %7$15s","POS","TYPE","REF","ALT","GT","QUAL","SnpEff"),xi+7,yi+60);
//      } else {
//          ctx10.fillText($.format("%1$10s %2$10s %3$10s %4$10s %5$10s %6$10s","POS","TYPE","REF","ALT","GT","QUAL"),xi+7,yi+60);
//      }
      var string="";
      string = "<table class = \"cellDigInfoTd\" width=\"100%\" style=\"margin-top: 10px; margin-bottom: 20px;\" border=\"1\" bordercolor=\"#DDDDDD\"> \
           <tr bgcolor=\"#CCCCCC\" style=\"height: 20px;\" ><td width=\"8%\">Position</td><td width=\"5%\">TYPE</td width=\"4%\"><td width=\"4%\">REF</td>\
           <td width=\"4%\">ALT</td><td width=\"4%\">GT</td><td width=\"5%\">QUAL</td>";
      string = string+"<td width=\"60%\">SnpEff</td><td width=\"10%\"></td></tr>";
      var effclr = {INTERGENIC:'#00BFFF',UPSTREAM:'#00BFFF',DOWNSTREAM:'#00BFFF',UTR_5_PRIME:'#00BFFF',UTR_3_PRIME:'#00BFFF',REGULATION:'#00BFFF',INTRAGENIC:'#00BFFF',GENE:'#00BFFF',INTRON_CONSERVED:'#00BFFF',INTRON:'#00BFFF',INTERGENIC_CONSERVED:'#00BFFF',SYNONYMOUS_START:'#FFFF00',NON_SYNONYMOUS_START:'#FFFF00',START_GAINED:'#FFFF00',SYNONYMOUS_CODING:'#FFFF00',SYNONYMOUS_STOP:'#FFFF00',EXON:'#FFFF00',CDS:'#FFFF00',TRANSCRIPT:'#FFFF00',CHROMOSOME_LARGE_DUPLICATION:'#FFFF00',SPLICE_SITE_REGION:'#FFFF00',SPLICE_SITE_BRANCH:'#FFFF00',SPLICE_SITE_BRANCH_U12:'#FFFF00',MICRO_RNA:'#FFFF00',NON_SYNONYMOUS_STOP:'#FFFF00',NON_SYNONYMOUS_CODING:'#EE9A00',CODON_CHANGE:'#EE9A00',CODON_INSERTION:'#EE9A00',CODON_CHANGE_PLUS_CODON_INSERTION:'#EE9A00',CODON_DELETION:'#EE9A00',CODON_CHANGE_PLUS_CODON_DELETION:'#EE9A00',UTR_5_DELETED:'#EE9A00',UTR_3_DELETED:'#EE9A00',CHROMOSOME_LARGE_INVERSION:'#EE9A00',NEXT_PROT:'#EE9A00',SPLICE_SITE_ACCEPTOR:'red',SPLICE_SITE_DONOR:'red',START_LOST:'red',EXON_DELETED:'red',FRAME_SHIFT:'red',STOP_GAINED:'red',STOP_LOST:'red',RARE_AMINO_ACID:'red',CHROMOSOME_LARGEDELETION:'red',EXON_DELETED_PARTIAL:'red',EXON_DUPLICATION:'red',EXON_DUPLICATION_PARTIAL:'red',EXON_INVERSION:'red',EXON_INVERSION_PARTIAL:'red',GENE_DELETED:'red',GENE_DUPLICATION:'red',GENE_FUSION:'red',GENE_FUSION_HALF:'red',GENE_FUSION_REVERESE:'red',GENE_REARRANGEMENT:'red',PROTEIN_PROTEIN_INTERACTION_LOCUS:'red',PROTEIN_STRUCTURAL_INTERACTION_LOCUS:'red',TRANSCRIPT_DELETED:'red'};

      for (i=0,oLen=o.length; i<oLen; i++) {
        var pos = o[i].pos;
        var variant = o[i].variant;
        var ref = o[i].ref;
        var reflen = ref.length;
        if (reflen > 7 ) {
          var refpart = ref.substr(0,6);
          ref = refpart+"..."
        }
        var alt = (o[i].alt);
        var altlen = alt.length;
        if (altlen > 7 ) {
          var altpart = alt.substr(0,6);
          alt = altpart+"..."
        }
	var jumpScript = "_execSearch(DAMMY_KEYWORD + '|" + pos + "|" + pos + "|" + Objects.Chr + "', false);";
//        var jumpScript = "_execSearch('the target|" + pos + "|" + pos + "|" + Objects.Chr + "', false);";

        var gt = o[i].gt;
        var qual = o[i].qual;
        ctx10.fillStyle="#000";
        ctx10.fillFont="Alial";
        ctx10.fillText(pos,xi+13,yi-10+(i+1)*17+70);
        ctx10.fillText(variant,xi+73,yi-10+(i+1)*17+70);
        ctx10.fillText(ref,xi+143,yi-10+(i+1)*17+70);
        ctx10.fillText(alt,xi+205,yi-10+(i+1)*17+70);
        ctx10.fillText(gt,xi+273,yi-10+(i+1)*17+70);
        ctx10.fillText(qual,xi+325,yi-10+(i+1)*17+70);
        if(o[i].eff != ""){
          var uniEffMap = {};
          var uniEffs = [];
//          var effs = Array();
//          var efftrim = Array();
          var effinfos = o[i].eff.split(",");
          for(en = 0,effinfosLen=effinfos.length;en<effinfosLen;en++) {
                if (/^[^\|]+\(/.test(effinfos[en])) {
//                if (/\(/.test(effinfos[en])) {
                        var efftmp = effinfos[en].split("(");
                        var effpls = efftmp[0].split("+");
                        if(!(effclr[effpls[0]] in uniEffMap)) uniEffs.push(effclr[effpls[0]]);
                        uniEffMap[effclr[effpls[0]]] = true;
                } else {
                        var efftmp = effinfos[en].split("|");
                        if(!(annclr[efftmp[2]] in uniEffMap)) uniEffs.push(annclr[efftmp[2]]);
                        uniEffMap[annclr[efftmp[2]]] = true;
                }
          }
//          var efftrim = Array.from(new Set(effs));	// Array.from added in ES2015. Prohibited for compatibility.
          for(clr=0,uniEffsLen=uniEffs.length; clr<uniEffsLen; clr++) {
                var color = uniEffs[clr];
                if(!color) color = _getSnpeffImpactColor(0);
                ctx10.fillStyle = color;
                ctx10.fillRect(xi+7+380+10*clr,yi-10+(i+1)*17+60,7.5,10);
          }
        }
        var targetend=+parseInt(o[i].pos)+parseInt(o[i].ref.length)-1;
        var target = THISACC+"---BLS---"+o[i].pos+"---BLS---"+targetend+"---BLS---"+o[i].variant;
        var effall = o[i].eff.split(",");
        string = string + "<tr style=\"height: 20px;\">" + 
		"<td width=\"8%\"><a href=\"javascript:" + jumpScript + "\" style=\"color:blue;\">" + Number(o[i].pos).toLocaleString() + "</a></td>" +
		"<td width=\"5%\">" + o[i].variant + "</td>" +
		"<td width=\"4%\">" + o[i].ref + "</td>" +
		"<td width=\"4%\">" + escape_html(o[i].alt) + "</td>" +
		"<td width=\"4%\">" + o[i].gt + "</td>" +
		"<td width=\"5%\">" + o[i].qual + "</td>";
        if(o[i].eff != ""){
          for (var x=0,effallLen=effall.length; x<effallLen; x++) {
            var col="#7fffd4";
            var font="black";
            var addclass="class = cellTdBlank";
            var effEach = effall[x].split("|");
            var eff = effEach[1].split("(");
            col = _getSnpeffImpactColor(effEach[0]);
            if(effEach[0]==="3") font="white";

            var effString = effall[x].replace(/^\d|(.*)/,"$1");
            if(effString=='|') effString = '';
            var snpeffObj = parseSnpEffStr(effString);
            var snpeffRowColors = getSnpEffRowColor(snpeffObj['id'], snpeffObj['name']);
            var fgRowColor = snpeffRowColors[0];
            var bgRowColor = snpeffRowColors[1];
            if(x > 0){
              string=string+"<tr style=\"height: 20px;\"><td class = cellTdBlank width=\"8%\"></td><td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td>\
              <td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td>\
              <td width=\"60%\" style=\"color:" + fgRowColor + ";background-color:" + bgRowColor + "\">" + effString + "</td><td width=\"10%\" class = cellTdBlank></td></tr>";
            } else {
              string = string + "<td width=\"60%\" style=\"color:" + fgRowColor + ";background-color:" + bgRowColor + "\">" + effString + "</td>" +
                      "<td width=\"10%\" rowspan=\"" + effall.length+"\" style=\"text-align:center;\">" + 
                      "<button style=\"width:64px;padding:0px;\" type=\"submit\" onClick=\"_dialog_p3('"+target+"');\" >Pick<br>primers</button>" + 
                      "</td></tr>";
            }
          }
          string=string+"<tr style=\"height: 20px;\"><td class = cellTdBlank width=\"8%\"></td><td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td>\
          <td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td>\
          <td class = cellTdBlank width=\"41%\"></td><td width=\"10%\" class = cellTdBlank></td></tr>";
        }else{
          string = string + "<td width=\"60%\"></td>" +
                  "<td width=\"10%\" style=\"text-align:center;\" >" + 
//                  "<button style=\"width:64px;padding:0px;margin-bottom:2px;\" type=\"submit\" onClick=\"" + jumpScript + "\">Jump</button>" +
                  "<button style=\"width:64px;padding:0px;\" type=\"submit\" onClick=\"_dialog_p3('"+target+"');\" >Pick<br>primers</button>" + 
                  "</td></tr>";
        }
      }
      string=string+"</table>";
      ONINFOCELL.each=string;
      ONINFOCELL.str=ONINFOCELL.str+ONINFOCELL.each+"&nbsp;</span>";
    }
  }
}

function _getEffCol(effver) {
	var envObj = JSON.parse(storage.getItem("_Env"));
        var effcol = "";
	if(effver === "EFF") {
		effcol = envObj["eff_col"];
	} else {
		effcol = envObj["ann_col"];
	}
/*
	var effcol="";
        $.ajax({
                url: "./bin/"+_backendSelector("getEffCol.php"),
                type: "POST",
                cache: false,
                async: false,
                data: {
                        "effver":effver
                },
                success: function(data) {
                        effcol=data;
                }
        });
*/
        return effcol;
}

var chDtlCellView="pos";
function _changeFmtPos(){
var o=CELLINFODRAW;
var view= Array();
var div = document.getElementById( "cellDigInfo" );
var chfmt = document.getElementById( "chfmt" );
if(chDtlCellView=="pos"){
  chDtlCellView="obj";
  var string="";
  var regit = Array();
  for (i=0; i<o.length; i++) {
     var targetend=+parseInt(o[i].pos)+parseInt(o[i].ref.length)-1;
     var target = THISACC+"---BLS---"+o[i].pos+"---BLS---"+targetend+"---BLS---"+o[i].variant;
     var effall = o[i].eff.split(",");
     string = "<table class = \"cellDigInfoTd\" width=\"100%\" style=\"margin-top: 10px; margin-bottom: 20px;\" border=\"1\" bordercolor=\"#DDDDDD\"> \
     <tr bgcolor=\"#CCCCCC\" style=\"height: 20px;\" ><td width=\"17%\" >ID</td><td width=\"12%\">Effect</td><td width=\"8%\">Position</td>\
     <td width=\"5%\">TYPE</td width=\"4%\"><td width=\"4%\">REF</td><td width=\"4%\">ALT</td><td width=\"4%\">GT</td><td width=\"5%\">QUAL</td><td width=\"31%\">SnpEff</td><td class = cellTdBlank width=\"10%\"></td></tr>";
     var effEach = effall[0].split("---BLS---");
     for (var x=0; x<effall.length; x++) {
      var effEach = effall[x].split("|");

      var effObj = parseSnpEffStr(effall[x]);
      var id = effObj['id'];
      var name = effObj['name'];
      var eff = effObj['eff'];

      var rowColors = getSnpEffRowColor(id, name);
      var rowBgColor = rowColors[1];
      var rowFgColor = rowColors[0];
      var col="#7fffd4";
      var font="black";
      var addclass="class = cellTdBlank";
      var col = _getSnpeffImpactColor(effEach[effEach.length-1]);
      if(parseInt(effEach[effEach.length-1]) === 3) font = "white";

      if(id==""){effEach[9]="NONE";}
      var jumpScript = "_execSearch(DAMMY_KEYWORD + '|" + o[i].pos + "|" + o[i].pos + "|" + Objects.Chr + "', false);";
      var effString = effall[x].replace(/^\d|(.*)/,"$1");
      if(effString=='|') effString = '';
      if(view[id]){
        if(id in regit){
          if(id+":"+eff in regit){
          }else{
            view[id] = view[id] + "<tr style=\"height: 20px;color:" + rowFgColor + ";background-color:" + rowBgColor + ";\" >" + 
              "<td "+addclass+" width=\"25%\" style=\"background-color:white;\"></td>" +
              "<td style=\"color:" + font + ";background-color:" + col + ";\">"+eff+"</td>" + 
              "<td><a href=\"javascript:" + jumpScript + "\" style=\"color:blue;\">" + Number(o[i].pos).toLocaleString() + "</a></td>" + 
              "<td>"+o[i].variant+"</td>" +
              "<td>"+o[i].ref+"</td>" + 
              "<td>"+ escape_html(o[i].alt) +"</td>" + 
              "<td>"+o[i].gt+"</td>" + 
              "<td>"+o[i].qual+"</td>" + 
              "<td>"+ effString +"</td>" + 
              "<td style=\"text-align:center;\">" + 
//              "<button type=\"submit\" style=\"width:64px;padding:0px;margin-bottom:2px;\" onClick=\"" + jumpScript + "\">Jump</button>" +
              "<button type=\"submit\" style=\"width:64px;padding:0px;\" name=\"prm_p3_"+i+"\" onClick=\"_dialog_p3('"+target+"');\" >Pick<br>primers</button>" + 
              "</td></tr>";
          }
        }else{
          view[id] = "<tr style=\"height: 20px;color:" + rowFgColor + ";background-color:" + rowBgColor + ";\">" + 
            "<td "+addclass+" width=\"25%\">"+id+"</td>" +
            "<td style=\"color:" + font + ";background-color:" + col + ";\">"+eff+"</td>" + 
            "<td><a href=\"javascript:" + jumpScript + "\" style=\"color:blue;\">" + Number(o[i].pos).toLocaleString() + "</a></td>" + 
            "<td>"+o[i].variant+"</td>" +
            "<td>"+o[i].ref+"</td>" + 
            "<td>"+ escape_html(o[i].alt) +"</td>" + 
            "<td>"+o[i].gt+"</td>" + 
            "<td>"+o[i].qual+"</td>" + 
            "<td>"+ effString +"</td>" + 
            "<td style=\"text-align:center;\">" + 
//            "<button type=\"submit\" style=\"width:64px;padding:0px;margin-bottom:2px;\" onClick=\"" + jumpScript + "\">Jump</button>" +
            "<button type=\"submit\" style=\"width:64px;padding:0px;\" name=\"prm_p3_"+i+"\" onClick=\"_dialog_p3('"+target+"');\" >Pick<br>primers</button>" + 
            "</td></tr>";
        }
      }else{
        view[id] = "<tr style=\"height: 20px;color:" + rowFgColor + ";background-color:" + rowBgColor + ";\">" + 
          "<td width=\"17%\" bgcolor=\"#DDDDDD\" >"+id+"</td>" +
          "<td width=\"12%\" style=\"color:" + font + ";background-color:" + col + ";\">"+eff+"</td>" + 
          "<td width=\"8%\"><a href=\"javascript:" + jumpScript + "\" style=\"color:blue;\">" + Number(o[i].pos).toLocaleString() + "</a></td>" +
          "<td width=\"4%\">"+o[i].variant+"</td>" + "<td width=\"4%\">"+o[i].ref+"</td>" + "<td width=\"4%\">"+ escape_html(o[i].alt) +"</td>" +
          "<td width=\"4%\">"+o[i].gt+"</td>" + 
          "<td width=\"4%\">"+o[i].qual+"</td>" + 
          "<td width=\"42%\">"+ effString +"</td>" + 
          "<td style=\"text-align:center;\">" + 
//          "<button type=\"submit\" style=\"width:64px;padding:0px;margin-bottom:2px;\" onClick=\"" + jumpScript + "\">Jump</button>" +
          "<button type=\"submit\" style=\"width:64px;padding:0px;\" name=\"prm_p3_"+i+"\" onClick=\"_dialog_p3('"+target+"');\" >Pick<br>primers</button>" + 
          "</td></tr>";
        regit[id]="";
      }

     }
    
  }
  var res = _sortByKey(view,"");
  for (var prop in res){
    if(prop != "remove"){
      string=string+view[res[prop]]+"<tr style=\"height: 20px;\"><td class = cellTdBlank width=\"17%\"><td class = cellTdBlank width=\"12%\"><td class = cellTdBlank width=\"8%\"></td><td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td>\
      <td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td><td class = cellTdBlank width=\"4%\"></td>\
      <td class = cellTdBlank width=\"42%\"></td><td class = cellTdBlank></td></tr>";
    }
  }
  string=string+"</table>";
  div.innerHTML = string;
  chfmt.innerHTML = "<div id=\"chfmt\" align=right><button type=\"submit\" onClick=\"_changeFmtPos();\" >Change to each variants</button></div>";
}else{
  chDtlCellView="pos";
  div.innerHTML = ONINFOCELL.each;
  chfmt.innerHTML = "<div id=\"chfmt\" align=right><button type=\"submit\" onClick=\"_changeFmtPos();\" >Change to each id</button></div>";
}
}

var effver2col = [];
function parseSnpEffStr(str) {
	var funcGetEffcol = function(ver) {
		var col = "";
		if(ver in effver2col) {
			col = effver2col[ver];
		} else {
			col = _getEffCol(ver);
			effver2col[ver] = col;
		}
		return col;
	}

        var effEach = str.split("|");
	var effver = ""; var id = ""; var name = ""; var eff = "";
	if (/^[^\|]+\(/.test(str)) {
		effver = "EFF";
		effcol = funcGetEffcol(effver);
		effarr = effEach[0].split("(");
		eff = effarr[0];
		if(effEach.length > 10) {
			// new EFF format
			id = effEach[effcol];
			name = effEach[5];
		} else {
			// old EFF format
			id = effEach[4];
			name = effEach[7];
		}
	} else {
		effver = "ANN";
		effcol = funcGetEffcol(effver);
		eff = effEach[1];
		id = effEach[effcol];
		name = effEach[3];
	}
	return {'effver':effver, 'id':id, 'name':name, 'eff':eff};
}
function getSnpEffRowColor(id, name) {
	var rowBgColor = "none";
	var rowFgColor = "black";
	var hilightVarGene = storage.getItem("_HighlightVariantGene");
	if(hilightVarGene && (id !== hilightVarGene && name !== hilightVarGene)) {
		rowBgColor = "#DDDDDD";
		rowFgColor = "#999999";
	}
	return [rowFgColor, rowBgColor];
}

/////////////////////////////////////////////// Details accession on title
function _draw_detail_accession(i){

  var o=new Object(JSON.parse(storage.getItem('_Lists')));
y=i*Objects.BlockH+12;
  p=i*Objects.BlockH+(Objects.BlockH/2);
  p2=y;

var elemCont2 = document.getElementById("content2");
var bounds = elemCont2.getBoundingClientRect(); 
var boundsY = bounds.top;
var elemCont = document.getElementById("content");
var boundsB = elemCont.getBoundingClientRect(); 
var boundsBY = boundsB.top;
var hidreg =boundsBY+Objects.canvasHeight-boundsY-11;

if((Objects.canvasHeight - i*Objects.BlockH) <= 200+hidreg+Objects.BlockH ){
y=i*Objects.BlockH;
    p=i*Objects.BlockH+(Objects.BlockH/2);
    p2=y;
}
  ctx10.textAlign="left";
  ctx10.fillStyle="#ffffff";
  //ctx10.fillRect(5,5,270,180);
  ctx10.fillRect(5,5,360,230);
  ctx10.strokeStyle="#b0c4de";
  ctx10.lineWidth=5;
  ctx10.strokeRect(5,5,360,230);
  //ctx10.strokeRect(5,5,270,180);

  ctx10.fillStyle="#000000";
  ctx10.font="Bold 13px 'Century'";
 
  var names = [];
/*
  if( o[i].name.length > 14) {
	names = o[i].name.split(" ");
	ctx10.fillText("ID",30,25);
	ctx10.fillText("NAME",30,45);
  	ctx10.fillText("VARIETY",30,80);
  	ctx10.fillText("SUB VARIETY",30,100);
  	ctx10.fillText("ORIGIN",30,120);
  	ctx10.fillText("ORIGIN 2",30,140);
  	ctx10.fillText("TYPE",30,160);
  } else {
*/
	ctx10.fillText("ID",30,35);
  	ctx10.fillText("NAME",30,55);
  	ctx10.fillText("VARIETY",30,75);
  	ctx10.fillText("SUB VARIETY",30,95);
  	ctx10.fillText("ORIGIN",30,115);
  	ctx10.fillText("ORIGIN 2",30,135);
  	ctx10.fillText("TYPE",30,155);
  	ctx10.fillText("OTHER 1",30,175);
  	ctx10.fillText("OTHER 2",30,195);
  //}
  num = names.length;
  ctx10.font="12px 'Century'";
  //if (num == 0) {
  	ctx10.fillText(": "+o[i].id,135,35);
  	ctx10.fillText(": "+o[i].name,135,55);
  	ctx10.fillText(": "+o[i].variety,135,75);
  	ctx10.fillText(": "+o[i].grp,135,95);
  	ctx10.fillText(": "+o[i].origin,135,115);
  	ctx10.fillText(": "+o[i].origin_2,135,135);
  	ctx10.fillText(": "+o[i].type,135,155);
  	ctx10.fillText(": "+o[i].other_1,135,175);
  	ctx10.fillText(": "+o[i].other_2,135,195);
/*
  } else if(num > 0) {
	ctx10.fillText(": "+o[i].id,135,25);
        ctx10.fillText(": "+names[0],135,45);
        ctx10.fillText(names[1],140,60);
        ctx10.fillText(": "+o[i].variety,135,80);
        ctx10.fillText(": "+o[i].grp,135,100);
        ctx10.fillText(": "+o[i].origin,135,120);
        ctx10.fillText(": "+o[i].origin_2,135,140);
        ctx10.fillText(": "+o[i].type,135,160);
  }
*/

if(phenotypeFlg) {
	var phenotype = storage.getItem("_Phenotype");
  	if(storage.getItem("_Phenoexp") == null) {
        	_getPheno(phenotype);
  	}
	phenoexp = storage.getItem("_Phenoexp");
  	phenoexps = phenoexp.split("|");
 	var phenohash = new Array();
  	for(var j=0; j<phenoexps.length;j++) {
        	phenotmp = phenoexps[j].split(",");
        	phenohash[phenotmp[0]] = phenotmp[1];
  	}
  	ctx10.fillStyle="#000000";
  	ctx10.font="Bold 13px 'Century'";
	//if(num == 0) {
		ctx10.fillText(phenotype,30,215);
/*
	} else if (num > 0) {
		ctx10.fillText(phenotype,30,180);
	}
*/
	ctx10.font="12px 'Century'";
	//if(num == 0) {
		ctx10.fillText(": "+phenohash[o[i].id],135,215);
/*
	} else if (num > 0) {
		ctx10.fillText(": "+phenohash[o[i].id],135,180);
	}
*/
}
  // line between box to list
  ctx4.beginPath();
  ctx4.moveTo(5,p);
  ctx4.lineTo(70,p2);
  ctx4.closePath();
  ctx4.lineWidth=1;
  ctx4.strokeStyle="blue";
  ctx4.stroke();

}

///////////////////////////// Drawing Region Highlight
function _drawRegionHighlightCvs(cvs) {
  var hls = getRegionHighlightArray();
  if(hls.length == 0) return;

  var zoom = _cvtZoom(Objects.Zoom);
/*
  var Pos;
  if(/k/.test(Objects.Zoom)) {
    Pos = Objects.Zoom.replace(/k/,"000");
  } else {
    Pos = Objects.Zoom.replace(/b/,"");
  }
  var startRef = (Objects.Pos-1)*Pos+1;
  var endRef = (Objects.Pos-1)*Pos+Pos*Objects.Block;
*/
  var startRef = (Objects.Pos-1)*zoom+1;
  var endRef = ((Objects.Pos-1)+Objects.Block) * zoom;
  for(var i=0,hlsLen=hls.length; i<hlsLen; i++) {
    var chr = hls[i].chr;
    var st = hls[i].st;
    var en = hls[i].en;
    if(chr != Objects.Chr) continue;
    if(!st || !en || st > endRef || en < startRef) continue;

    if(st < startRef) st = startRef;
    if(en > endRef) en = endRef;
    var stX = (st - startRef) / zoom * Objects.BlockW;
    var widthX = (en - st + 1) / zoom * Objects.BlockW;
    if(widthX<1) widthX = 1;

    var hlRgb = "rgba(255, 0, 0, 0.08)";
    var ctx = cvs.getContext("2d");
    ctx.fillStyle = hlRgb;
    ctx.fillRect(stX, 0, widthX, cvs.height);
  }
}
///////////////////////////// Writing accession name
function _drawTitle(pos) {
/*
  var titleary = titlestr.split(",");
  var title = titleary[0];
  var subtitle = titleary[1];
*/
  ctx3.clearRect(0,0,cvs3.width,cvs3.height);
  ctx3.fillStyle="#dcdcdc";
  ctx3.fillRect(0,0,cvs3.width,cvs3.height); 
  var titleColor = storage.getItem('_ColorCode');
  var dest_subtitle = Objects["NameSub"];
  if(dest_subtitle == "subvariety"){dest_subtitle = "grp";}
  if(phenotypeFlg) {
  	phenoexp = storage.getItem("_Phenoexp");
  	phenoexps = phenoexp.split("|");
  	var phenohash = new Array();
  	for(i=0; i<phenoexps.length;i++) {
		phenotmp = phenoexps[i].split(",");
		phenohash[phenotmp[0]] = phenotmp[1];
	}
  }
  for(var i=0,idLen=Objects.id.length; i<idLen; i++) {
    if ( Objects.db[i] == storage.getItem('_Ref')) {
      ctx3.font="Bold italic 13px 'Courier'";
      ctx3.fillStyle=_setColor().reftitle;
    } else if (pos!=i){
      ctx3.font="11px 'Courier'";
      //ctx3.font="11px 'Arial'";
      if(titleColor == "on"){
        ctx3.fillStyle=_getTitleColor(Objects[dest_subtitle][i]);
      }else{
        ctx3.fillStyle=_setColor().title;
	
      }
    } else {
      ctx3.font="Bold 12px 'Courier'";
      //ctx3.font="Bold 12px 'Arial'";
      ctx3.fillStyle="#ff8c00";
    }
    var title_view = "";
    if (Objects.Name=="id"){
      title_view = Objects.id[i];
    }else{
      title_view = Objects.name[i];
    }
    var id_width = parseInt(Objects.titleWidth*0.7);
    var grp_width = Objects.titleWidth-id_width;
    //if(title_view.length>parseInt(id_width/7)-6){title_view = title_view.substring(0, parseInt(id_width/7)-6)+"~"; }
    if(title_view.length>parseInt(id_width/7)-5){title_view = title_view.substring(0, parseInt(id_width/7)-6)+"~"; }
    //}
    ctx3.fillText(title_view,Objects.titleIndent,Objects.BlockH*i+Objects.titleY);
    var sub_title_view = Objects[dest_subtitle][i];
    
    if(Objects[dest_subtitle][i].length>parseInt(grp_width/7)){sub_title_view = Objects[dest_subtitle][i].substring(0, parseInt(grp_width/7)-2)+"~"; }

    ctx3.fillText(sub_title_view, Objects.titleGrp - 27, Objects.BlockH*i+Objects.titleY);	//190613 Add
    if(phenotypeFlg){
/*
	    if ( Objects.NameSub == "variety" ) {
	      ctx3.fillText(sub_title_view, Objects.titleGrp - 27, Objects.BlockH*i+Objects.titleY);
	    } else if ( Objects.NameSub == "subvariety" ) {
	      ctx3.fillText(sub_title_view, Objects.titleGrp - 27, Objects.BlockH*i+Objects.titleY);
	    } else if ( Objects.NameSub == "origin"  || Objects.NameSub == "origin_2") {
	      ctx3.fillText(sub_title_view, Objects.titleGrp - 27, Objects.BlockH*i+Objects.titleY);
	    } else if ( Objects.NameSub == "type" ) {
	      ctx3.fillText(sub_title_view, Objects.titleGrp - 27, Objects.BlockH*i+Objects.titleY);
            } else if ( Objects.NameSub == "other_1" ) {
              ctx3.fillText(sub_title_view, Objects.titleGrp - 27, Objects.BlockH*i+Objects.titleY);
            } else if ( Objects.NameSub == "other_2" ) {
              ctx3.fillText(sub_title_view, Objects.titleGrp - 27, Objects.BlockH*i+Objects.titleY);
            }
*/
	    var phenonum = phenohash[Objects.id[i]];
	    if (phenonum) {
	    	ctx3.fillText(phenonum.substr(0,5), Objects.titleWidth - 32, Objects.BlockH*i+Objects.titleY);
	    }
/*
	    var plus_or_minus = "";
		if (Objects.PhenotypeExpressions[Objects.id[i]][Objects.Phenotype]){
			plus_or_minus = "+";
		}else{
			plus_or_minus = "-";
		}
		var phenonum = phenohash[Objects.id[i]];
		ctx3.fillText(phenonum, Objects.titleWidth - 15, Objects.BlockH*i+Objects.titleY);
*/
    }else{
/*
    	if ( Objects.NameSub == "variety" ) {
  	      ctx3.fillText(sub_title_view, Objects.titleGrp, Objects.BlockH*i+Objects.titleY);
  	    } else if ( Objects.NameSub == "subvariety" ) {
  	      ctx3.fillText(sub_title_view, Objects.titleGrp, Objects.BlockH*i+Objects.titleY);
  	    } else if ( Objects.NameSub == "origin" || Objects.NameSub == "origin_2") {
  	      ctx3.fillText(sub_title_view, Objects.titleGrp, Objects.BlockH*i+Objects.titleY);
  	    } else if ( Objects.NameSub == "type" ) {
  	      ctx3.fillText(sub_title_view, Objects.titleGrp, Objects.BlockH*i+Objects.titleY);
  	    }
*/
    }
  }
}

///////////////////////////// Drawing null block
function _drawNULLBlock() {
	var exportFlg = storage.getItem("_exportFlg");
	var targetCtx = null;
	if(exportFlg == 0) {
		targetCtx = ctx4;
	} else if(exportFlg == 1) {
		targetCtx = ctx16;
	} else {
		return;
	}
  	var cstm = storage.getItem('_CSTM');
  	var condArray = storage.getItem("_CrtCondition").split("|");
  	var cond = parseInt(condArray[0]);
	var o = {};
	for (var y=0, dbLen=Objects.db.length; y<dbLen; y++){
		if (exportFlg == 0) {
    			o=new Object(JSON.parse(_getCompressedData(Objects.db[y])));
		} else if (exportFlg == 1) {
			o=new Object(JSON.parse(_getCompressedData(Objects.db[y]+"dst")));
		}
		for (var x=0, oLen=o.length; x<oLen; x++) {
      			if(cstm === "off" || cstm === "disabled"){
        			if ( _isEmpty(o[x].dp) ) {
          				if (Objects._Null==="true"){
                                                targetCtx.fillStyle="PaleGoldenrod";
          				}else{
                                                targetCtx.fillStyle="white";
          				}
                                        targetCtx.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH);
        			}else{
          				if(o[x].dp === "x"){
						targetCtx.fillStyle="#595454";
						targetCtx.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH);
          				}
        			}
      			}else{
        			var splitted_rdp = o[x].rdp.split("%");
        			var valid = 0;
        			for(var a=0; a<condArray.length; a++){if(condArray[a]!=""){valid++;}}
        			var h = parseInt(Objects.BlockH/valid);
        			if(parseInt(Objects.BlockH%valid)!=0){h++;}
        			var drawn = 0;
				for (var b=0, condArraylen=condArray.length; b<condArraylen; b++) {
          				if(condArray[b] != ""){
            					cond = parseInt(condArray[b]);
            					if ( _isEmpty(splitted_rdp[cond]) ) {
              						if (Objects._Null==="true"){
                                                                targetCtx.fillStyle="PaleGoldenrod";
              						}else{
								targetCtx.illStyle="white";
              						}
							targetCtx.fillRect(x*Objects.BlockW, (y*Objects.BlockH)+(drawn*h), Objects.BlockW, h);
            					}else{
              						if(splitted_rdp[cond] === "x"){
								targetCtx.fillStyle="#595454";
								targetCtx.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH);
              						}
            					}
            					drawn++;
          				}
        			}
      			}
      			// For changing reference
      			if ( Objects.db[y] === storage.getItem('_Ref') ) {
				targetCtx.fillStyle="#595454";
				targetCtx.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH);
      			}
    		}
  	}
}
////////////////////////////////////////
/**
 * baseOffset:	Inner block offset for non-block mode (=gt[0])
 * row:		homo(fullheight)=null, hetero(top)=0, hetero(under)=1
**/
function _drawVriantByType(targetCtx, gt, refStr, altStr, eff, x, y, row) {
	var baseOffset = gt[0];
	var refLen = refStr.length;
	var altLen = altStr.length;

	if(gt[3] === "1") {
		geneHit = true;
	} else {
		geneHit = false;
	}

	var block=parseInt(x * Objects.BlockW);
	var top, height;
	if(row === null) {
		top = y * Objects.BlockH + 1;
		if(refLen < altLen) {
			height = Objects.BlockH-2;
		} else {
			height = Objects.BlockH-1;	// Block: DEL or SNP
		}
	} else {
		top = y * Objects.BlockH + parseInt(Objects.BlockH * 0.5) * row + 1;
		if(refLen < altLen) {
			height = Objects.BlockH - parseInt((Objects.BlockH)*0.5) - 1;	// "I" symbol: INS
		} else {
			height = parseInt(Objects.BlockH * 0.5) - 1;	// Block: DEL or SNP
		}
	}

	if(geneHit) {
		targetCtx.globalAlpha = 1.0;
	} else {
		targetCtx.globalAlpha = 0.1;
	}

	var drawn = true;
	if(altStr === '*') {
		// Missing allele. Ignore instead of DEL.
	} else if(dispIndel && refLen < altLen) {
		// Insertion
		_setInsColor(targetCtx, eff);

		// draw Insertion "I" symbol
		var left = parseInt(baseOffset)+block+calib;
		var horizLineHalfWidth = parseInt(Objects.BlockW * 0.2);
		var horizLineHeight = (parseInt(Objects.BlockH) * 0.2)-1;
		targetCtx.fillRect(left, top, 2, height);
		targetCtx.fillRect(left - horizLineHalfWidth, top, horizLineHalfWidth * 2 + 2, horizLineHeight);
		targetCtx.fillRect(left - horizLineHalfWidth, top + height - horizLineHeight, horizLineHalfWidth * 2 + 2, horizLineHeight);
		if(_cvtZoom(Objects.Zoom)===1){
			var txtX = left + horizLineHalfWidth + 2;
//			var txtX = left + parseInt(Objects.BlockW*0.75) - 3;	// *3/4
			var txtHoffset = parseInt((height + 2) * 0.5) + 2;
			var insStr = "";
			var isTransposon = /</.test(altStr);
			if(isTransposon) {
				insStr = altStr;
			} else {
				insStr = altStr.substr(1, altLen-refLen);
			}
//			if(refStr.length > 1) insStr = "+" + (altStr.length - refStr.length);
			targetCtx.fillStyle="#000";
			targetCtx.fillText(insStr, txtX, top + txtHoffset);
		}
	} else if(dispIndel && refLen > altLen){
		// Deletion
		_setDelColor(targetCtx, eff);

		var delLen = refLen-altLen;
		var width = parseInt(storage.getItem("_BlockW")/_cvtZoom(Objects.Zoom)) * delLen;
		if(width < 2 ){width=2;}
		targetCtx.fillRect(parseInt(baseOffset)+block, top, width, height);
		if(_cvtZoom(Objects.Zoom)===1){
			var txtHoffset = parseInt(height * 0.5) + 4;
			targetCtx.fillStyle="#fff";
			targetCtx.textAlign="center";
			for (var i=0; i<delLen; i++) {
				targetCtx.fillText("-", x * Objects.BlockW + (i*Objects.BlockW) + parseInt(Objects.BlockW * 0.5), top + txtHoffset);
			}
			targetCtx.textAlign="left";
		}
	} else if(dispSnp && refLen===altLen) {
		// SNP
		_setSnpColor(targetCtx, altStr, eff);

		var width = parseInt(storage.getItem("_BlockW")/_cvtZoom(Objects.Zoom));
		if(width < 2 ){width=2;}
		targetCtx.fillRect(parseInt(baseOffset)+block, top, width, height);
	} else {
		drawn = false;
	}
	targetCtx.globalAlpha = 1.0;

	return drawn;

  function _setInsColor(targetCtx, eff) {
          if(!targetCtx) return;

          var colorStr = "";
          if (Objects.Eff==="off") {
		colorStr = "rgb(213,94,0)";
          }else{
              colorStr = _getSnpeffImpactColor(eff);
          }
          targetCtx.fillStyle = colorStr;
  }
  function _setSnpColor(targetCtx, base, eff) {
          if(!targetCtx) return;

          var colorStr = "";
          if (Objects.Eff==="off") {
                switch(base) {
                  case "A":
                    colorStr = "rgb(255,193,37)";
                    break;
                  case "T":
                    colorStr = "rgb(218,107,169)";
                    break;
                  case "G":
                    colorStr = "rgb(60,179,113)";
                    break;
                  case "C":
                    colorStr = "rgb(0,100,255)";
                    break;
                  default:
                    colorStr = "rgb(185,175,235)";
                }
          }else{
              colorStr = _getSnpeffImpactColor(eff);
          }
          targetCtx.fillStyle = colorStr;
  }
  function _setDelColor(targetCtx, eff) {
          if(!targetCtx) return;

          var colorStr = "";
          if (Objects.Eff==="off") {
              colorStr = "rgb(86,180,233)";
          }else{
              colorStr = _getSnpeffImpactColor(eff);
          }
          targetCtx.fillStyle= colorStr;
  }
}
function _getSnpeffImpactColor(impact) {
	var colorStr = "";
	var impactInt = parseInt(impact);
	switch(impactInt) {
		case 0:
			colorStr = "rgb(0,191,255)";
			break;
		case 1:
			colorStr = "rgb(255,255,0)";
			break;
		case 2:
			colorStr = "rgb(238,154,0)";
			break;
		case 3:
			colorStr = "rgb(255,0,0)";
			break;
		default:
			colorStr = "rgb(0,191,255)";
			break;
	}
	return colorStr;
}

////////////////////////////////////////
// Use the following variables only in _drawGTVariant() and _drawVriantByType().
var dispIndel = false;
var dispSnp = false;
var calib=0
function _drawGTVariant() {
  var exportFlg = storage.getItem("_exportFlg");
  var targetCtx = null;
  if (exportFlg == 0) {
    targetCtx = ctx4;
  } else if (exportFlg == 1) {
    targetCtx = ctx16;
  } else {
    return;
  }

  dispIndel = false;
  dispSnp = false;
  if(/a/.test(Objects.Mode) || (/s/.test(Objects.Mode) && /i/.test(Objects.Mode))) {
    // SNP+INDEL
    dispIndel = true;
    dispSnp = true;
  } else {
    if(/s/.test(Objects.Mode)) {
        // SNP
        dispSnp = true;
    }
    if(/i/.test(Objects.Mode)) {
        // INDEL only
        dispIndel = true;
    }
  }

  if(parseInt(_cvtZoom(Objects.Zoom))/storage.getItem("_BlockW") < 2 ){calib=parseInt(storage.getItem("_BlockW")/_cvtZoom(Objects.Zoom)); }	// for INS

  var impact2checked = _getEffFilterMap();

  var sidKeys = ["hs", "hi", "hd"];
//  var sidKeys = ["hd", "hs", "hi"];

  var snpCnt=new Array();
  for(var sidIndex=0, sidKeysLen=sidKeys.length; sidIndex<sidKeysLen; sidIndex++) {
    // The switching of the display/non-display of SNP/INDEL is not determined here,
    // but is determined from the difference between length of REF<=>ALT in _drawVriantByType().
    // For "GT:1/2" variant

    for (var y=0,dbLen=Objects.db.length; y<dbLen; y++) {
      if (exportFlg === "0") {
        var o=new Object(JSON.parse(_getCompressedData(Objects.db[y])));
      } else if (exportFlg === "1") {
        var o=new Object(JSON.parse(_getCompressedData(Objects.db[y]+"dst")));
      }
      for (var x=0, oLen=o.length; x<oLen; x++) {
        if ( sidKeys[sidIndex] in o[x] ) {
          var str = o[x][sidKeys[sidIndex]];
          var strsp = str.split("%");
          var cnt=strsp.length;
          var numgt=0;
          for(var t=0; t < cnt; t++){
            var gt = strsp[numgt].split("^");
//            var gt = strsp[numgt].split("-");

            var refAlt = gt[1].split("/");
            var refStr = refAlt[0];
            var altStr = refAlt[1].split(",")[0];

            if(gt[2]==="0/0" || gt[2]==="0|0"){
		// Do not draw 
            } else if(gt[2]==="1/1" || gt[2]==="1|1"){
		if(!impact2checked[gt[4]]) continue;
                _drawVriantByType(targetCtx, gt, refStr, altStr, gt[4], x, y, null);
            } else if(gt[2]==="0/1" || gt[2]==="0|1") {
		if(!impact2checked[gt[4]]) continue;
                _drawVriantByType(targetCtx, gt, refStr, altStr, gt[4], x, y, 0);
            } else {
                // GT=1/2
                var bases = refAlt[1].split(',');
                var effs = gt[4].split(',');
                var drawnUpperRow = _drawVriantByType(targetCtx, gt, refStr, bases[0], effs[0], x, y, 0);

                // Lower block for GT:1/2 + hetero
                var drawRow = 1;
//                  if(drawnUpperRow) drawRow++;
                if(bases.length>1 && effs.length>1) {
                    // In the combination of Ins+Del hetero, Second variant Pos is shifted by 1base.
                    var diffAltLen = bases[1].length - refStr.length;
                    if(diffAltLen===0 && dispSnp) {
                        // +SNP
			_drawVriantByType(targetCtx, gt, refStr, bases[1], effs[1], x, y, drawRow);
//                       _drawVriantByType(targetCtx, gt, refStr.substr(0,1), bases[1].substr(0,1), effs[1], x, y, drawRow);
                    } else if(diffAltLen>0 && dispIndel) {
                        // +Ins
                        if(sidKeys[sidIndex]==="hd") {
                            // GT:1/2 and  Del+Ins Hetero
                            _drawVriantByType(targetCtx, gt, refStr, bases[1], effs[1], x-1, y, drawRow);
                        } else {
                            _drawVriantByType(targetCtx, gt, refStr, bases[1], effs[1], x, y, drawRow);
                        }
                    } else if(diffAltLen<0 && dispIndel) {
                        // +Del
                        if(sidKeys[sidIndex]==="hi") {
                            // GT:1/2 and  Ins+Del Hetero
                            _drawVriantByType(targetCtx, gt, refStr, bases[1], effs[1], x + 1, y, drawRow);
                        } else {
                            _drawVriantByType(targetCtx, gt, refStr, bases[1], effs[1], x, y, drawRow);
                        }                  
                    }
                }
            }
            numgt++;
          }	// split(%) loop
        }	// hd/hs/hi exist key

        // Aggregate density
        if(dispSnp) {
          if (!_isEmpty(o[x].s)) {
            var t=o[x].s.split("-");
            (_isEmpty(snpCnt[x])) ? snpCnt[x] = parseInt(t[0]) : snpCnt[x] = parseInt(snpCnt[x]) + parseInt(t[0]); // for SNP Rate
          }
        } else {
          var ti=0;
          var te=0;
          if (!_isEmpty(o[x].i)) {
            t=o[x].i.split("-");
            ti=parseInt(t[0]);
            te=parseInt(t[1]);
            (_isEmpty(snpCnt[x])) ? snpCnt[x] = parseInt(t[0]) : snpCnt[x] = parseInt(snpCnt[x]) + parseInt(t[0]); // for SNP Rate
          }
          if (!_isEmpty(o[x].d)) {
            t=o[x].d.split("-");
            ti=parseInt(ti)+parseInt(t[0]);
            if ( te < parseInt(t[1]) ) te=parseInt(t[1]);
            (_isEmpty(snpCnt[x])) ? snpCnt[x] = parseInt(t[0]) : snpCnt[x] = parseInt(snpCnt[x]) + parseInt(t[0]); // for SNP Rate
          }
        }

        if ( Objects.db[y] === storage.getItem('_Ref') ) {
            // If Acc is a reference, make the line black.
            // This processing should not be performed because reference cannot be changed in nonBlock Mode.
            targetCtx.fillStyle="#595454";
            targetCtx.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH);
        }
      }		// x loop
    }		// y loop
  }		// hd/hs/hi loop
  if(dispSnp) {
    _drawDensity(snpCnt, "SNP");
  } else {
    _drawDensity(snpCnt, "INDEL");
  }
}

///////////////////////////// Drawing Depth block
function _drawDPBlock() {
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  var dpmx =_getMaxGraDP();
  var cstm=storage.getItem('_CSTM');
  var exportFlg = storage.getItem("_exportFlg");

  var targetCtx = null;
  if (exportFlg == 0) {
    targetCtx = ctx4;
  } else if (exportFlg == 1) {
    targetCtx = ctx16;
  } else {
    return;
  }

  var condArray = storage.getItem("_CrtCondition").split("|");
  var cond = parseInt(condArray[0]);
  for (var y=0, dbLen=Objects.db.length; y<dbLen; y++) {
    var topBase = (y*Objects.BlockH);
    if (exportFlg == 0) {
    	var o=new Object(JSON.parse(_getCompressedData(Objects.db[y])));
    } else if (exportFlg == 1) {
    	var o=new Object(JSON.parse(_getCompressedData(Objects.db[y]+"dst")));
    }
    var offsetDP=en.depth_min-1;
    var offsetCSTM=en.cstm_min-1;
    for (var x=0, oLen=o.length; x<oLen; x++) {
      var left = x*Objects.BlockW;
      if(cstm==="on"){
        var splitted_rdp = o[x].rdp.split("%");
        var valid = 0;
        for(var a=0, aLen=condArray.length; a<aLen; a++){if(condArray[a]!=""){valid++;}}
        var h = parseInt(Objects.BlockH/valid);
        if(parseInt(Objects.BlockH%valid)!=0){h++;}
        var drawn = 0;
        for (var b=0, condArrayLen=condArray.length; b<condArrayLen; b++) {
          var top = topBase + (drawn*h)
          cond = parseInt(condArray[b]);
          if(condArray[b] !== ""){
            if(b > (valid-1)){
              if ( ! _isEmpty(splitted_rdp[cond]) ) {
                if(splitted_rdp[cond] === "n"){
               		targetCtx.fillStyle="#f2f2f2";
//             		targetCtx.fillRect(x*Objects.BlockW, (y*Objects.BlockH)+(drawn*h), Objects.BlockW, h); 
                }else if(splitted_rdp[cond] === "x"){
               		targetCtx.fillStyle="#595454";
//             		targetCtx.fillRect(x*Objects.BlockW, (y*Objects.BlockH)+(drawn*h), Objects.BlockW, h); 
                }else{
                  var dps = parseInt(splitted_rdp[cond])-(offsetCSTM);
                  if(dps<1){dps = 0;}
                  if(dps > en.cstm_max-offsetCSTM){
                    		targetCtx.fillStyle=grad_CSTM_array[b](1);
                  }else if(dps == 0){
                    		targetCtx.fillStyle=en.cstm_min_col;
                  }else{
                    		targetCtx.fillStyle=grad_CSTM_array[b](dps/(en.cstm_max-offsetCSTM));
                  }
//                  targetCtx.fillRect(x*Objects.BlockW, (y*Objects.BlockH)+(drawn*h), Objects.BlockW, h);
                }
                targetCtx.fillRect(left, top, Objects.BlockW, h);
              }
            }else{
              if ( ! _isEmpty(splitted_rdp[cond]) ) {
                if(splitted_rdp[cond] === "n"){
                  		targetCtx.fillStyle="#f2f2f2";
//                  		targetCtx.fillRect(x*Objects.BlockW, (y*Objects.BlockH)+(drawn*h), Objects.BlockW, h); 
                }else if(splitted_rdp[cond] === "x"){
                                targetCtx.fillStyle="#595454";
//                                targetCtx.fillRect(x*Objects.BlockW, (y*Objects.BlockH)+(drawn*h), Objects.BlockW, h);
                }else{
                  var dps = parseInt(splitted_rdp[cond])-(offsetCSTM);
                  if(dps<1) dps = 0;
                  if(dps > en.cstm_max-offsetCSTM){
                                targetCtx.fillStyle=grad_CSTM_array[b](1);
                  }else if(dps === 0){
                                targetCtx.fillStyle=en.cstm_min_col;
                  }else{
                                targetCtx.fillStyle=grad_CSTM_array[b](dps/(en.cstm_max-offsetCSTM));
                  }
//                  targetCtx.fillRect(x*Objects.BlockW, (y*Objects.BlockH)+(drawn*h), Objects.BlockW, h);
                }
                targetCtx.fillRect(left, top, Objects.BlockW, h);
              }
            }
            drawn++;
          }
        }
      }else{
        if ( ! _isEmpty(o[x].dp) ) {
          if(o[x].dp === "n"){
            		targetCtx.fillStyle="#f2f2f2";
//            		targetCtx.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH); 
          }else if(o[x].dp === "x"){
            		targetCtx.fillStyle="#595454";
//            		targetCtx.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH); 
          }else{
            var dps = parseInt(o[x].dp)-(offsetDP);
            if(dps<1) dps = 0;
            if(dps > dpmx-offsetDP){
              		targetCtx.fillStyle=grad_DP(1);  
            }else if(dps === 0){
              		targetCtx.fillStyle=en.depth_min_col;
            }else{
              		targetCtx.fillStyle=grad_DP(dps/(dpmx-offsetDP));
            }
//            targetCtx.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH); 
          }
          targetCtx.fillRect(left, topBase, Objects.BlockW, Objects.BlockH);
        } 
      }
      // For changing reference
      if ( Objects.db[y] === storage.getItem('_Ref') ) {
        	targetCtx.fillStyle="#595454";
        	targetCtx.fillRect(left, topBase, Objects.BlockW, Objects.BlockH); 
      }
    }
  }
}

///////////////////////////// Drawing Snpblock: Estimation of SNP "blocks"
function _drawSNPEstimationBlock() {
  for (var y=0, dbLen=Objects.db.length; y<dbLen; y++) {
    var cmp=_getSnpblock(Objects.db[y]);
    var o=new Object(JSON.parse(_getCompressedData(Objects.db[y])));
    for (var x=0, oLen=o.length; x<oLen; x++) {
      if ( ! _isEmpty(o[x].s) ) {
        var t=o[x].s.split("-");
        if(parseInt(t[0])/_cvtZoom(Objects.Zoom)>=cmp){
          ctx4.fillStyle="rgba(0,255,98,0.4)";
          ctx4.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH); 
        }
      }
      // For changing reference
      if ( Objects.db[y] == storage.getItem('_Ref') ) {
        ctx4.fillStyle="#595454";
        ctx4.fillRect(x*Objects.BlockW, y*Objects.BlockH, Objects.BlockW, Objects.BlockH); 
      }
    }
  }
}

///////////////////////////// Drawing SNP block
function _drawSNPBlock(mode) {
  var exportFlg = storage.getItem("_exportFlg");
  var targetCtx = null;
  if (exportFlg == 0) {
    targetCtx = ctx4;
  } else if (exportFlg == 1) {
    targetCtx = ctx16;
  } else {
    return;
  }

  var en=new Object(JSON.parse(storage.getItem("_Env")));
  var snpCnt=new Array();
  var snpMax=0;
  var offset=en.snp_min-1;
  var o = {};
  for (var y=0, dbLen=Objects.db.length; y<dbLen; y++) {
    if (exportFlg == 0) {
    	o=new Object(JSON.parse(_getCompressedData(Objects.db[y])));
    } else if (exportFlg == 1) {
    	o=new Object(JSON.parse(_getCompressedData(Objects.db[y]+"dst")));
    }
    for (var x=0,oLen=o.length; x<oLen; x++) {
      if (! _isEmpty(o[x].s) ) {
        var t=o[x].s.split("^");
//        var t=o[x].s.split("-");
        (_isEmpty(snpCnt[x])) ? snpCnt[x]=parseInt(t[0]) : snpCnt[x]=parseInt(snpCnt[x])+parseInt(t[0]); // for SNP Rate
        var snps = parseInt(t[0])-offset;
        if(snps<1){continue;}

	var snpGenehit = o[x].s.slice(-1)[0];	// Last element
	var funcSnpGrad;
	if(snpGenehit === "1") {
		targetCtx.globalAlpha = 1.0;
		funcSnpGrad = grad_S;
	} else {
		targetCtx.globalAlpha = 0.15;
		funcSnpGrad = grad_Snohit;
	} 

	// setColor
        if (Objects.Eff==="off") {
          if(parseInt(t[0])>_getMaxGraSNP()-offset){
		targetCtx.fillStyle = funcSnpGrad(1);
//                targetCtx.fillStyle=grad_S(1);
          } else {
		targetCtx.fillStyle = funcSnpGrad((snps)/(_getMaxGraSNP()-offset));
//                targetCtx.fillStyle=grad_S((snps)/(_getMaxGraSNP()-offset));
          }
        } else {
           _setSnpEffColor(targetCtx, t[1]);
        }

	// draw Block
	switch(mode) {
		case 0:
			targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW*0.1), (y*Objects.BlockH)+(Objects.BlockH*0.1), Objects.BlockW*0.8, Objects.BlockH*0.8);
			break;
		case 1:
			targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW*0.25), (y*Objects.BlockH)+(Objects.BlockH*0.25), Objects.BlockW*0.5, Objects.BlockH*0.5);
			break;
		case 2:
			targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW*0.25), (y*Objects.BlockH)+(Objects.BlockH*0.25), Objects.BlockW*0.5, Objects.BlockH*0.25);
			break;
		case 4:
			targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW*0.1), (y*Objects.BlockH)+(Objects.BlockH*0.1), Objects.BlockW*0.8, Objects.BlockH*0.4);
			break;
		case 5:
			targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW*0.17), (y*Objects.BlockH)+(Objects.BlockH*0.17), Objects.BlockW*0.67, Objects.BlockH*0.67);
			break;
	}
/*
        if ( mode == 0 ) {
      	    targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW/10), (y*Objects.BlockH)+(Objects.BlockH/10), Objects.BlockW/1.25, Objects.BlockH/1.25);
        } else if ( mode == 1 ) {
            targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW/4), (y*Objects.BlockH)+(Objects.BlockH/4), Objects.BlockW/2, Objects.BlockH/2);
        } else if ( mode == 2 ) {
   	    targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW/4), (y*Objects.BlockH)+(Objects.BlockH/4), Objects.BlockW/2, Objects.BlockH/4);
        } else if (mode ==4 ){
            targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW/10), (y*Objects.BlockH)+(Objects.BlockH/10), Objects.BlockW/1.25, Objects.BlockH/2.5);
        } else if (mode ==5 ){
	    targetCtx.fillRect(x*Objects.BlockW+(Objects.BlockW/6), (y*Objects.BlockH)+(Objects.BlockH/6), Objects.BlockW/1.5, Objects.BlockH/1.5);
        }
*/
        if ( mode == 3 ) {
 		targetCtx.fillRect(x*Objects.BlockW+1, y*Objects.BlockH+1, Objects.BlockW-2, Objects.BlockH-2);

		if ( t[4] === "1/1"  || t[4] === "1|1") {
			targetCtx.strokeStyle="#000000";
			targetCtx.lineWidth=0.5;
			targetCtx.strokeRect(x*Objects.BlockW+0.5, y*Objects.BlockH+0.5, Objects.BlockW-1, Objects.BlockH-1);
		}
		targetCtx.font="9px 'Courier'";
		if ( t[1] === "3" && Objects.Eff === "on") {
			targetCtx.fillStyle="#fff";
		} else {
			targetCtx.fillStyle="#000";
		}
		targetCtx.textAlign="center";
		if ( storage.getItem("_DirRef") === "+" ) {
			targetCtx.fillText(t[3], x*Objects.BlockW+(Objects.BlockW*0.5), Objects.BlockH*y+Objects.BlockH-(Objects.BlockH*0.2));
//			targetCtx.fillText(t[3], x*Objects.BlockW+(Objects.BlockW/2), Objects.BlockH*y+Objects.BlockH-(Objects.BlockH/5));
		}else{
			targetCtx.fillText(_reverseNucleotide(t[3]), x*Objects.BlockW+(Objects.BlockW*0.5), Objects.BlockH*y+Objects.BlockH-(Objects.BlockH*0.2));
//			targetCtx.fillText(_reverseNucleotide(t[3]), x*Objects.BlockW+(Objects.BlockW/2), Objects.BlockH*y+Objects.BlockH-(Objects.BlockH/5));
		}
        }
      }
    }
  }
  targetCtx.globalAlpha = 1.0;

  _drawDensity(snpCnt,"SNP");

  function _setSnpEffColor(targetCtx, eff) {
          if(targetCtx===null) return;
          switch(eff) {
                case "0":
                        targetCtx.fillStyle="#00BFFF";
                        break;
                case "1":
                        targetCtx.fillStyle="#FFFF00";
                        break;
                case "2":
                        targetCtx.fillStyle="#EE9A00";
                        break;
                case "3":
                        targetCtx.fillStyle="red";
                        break;
                default:
                        targetCtx.fillStyle="#00BFFF";
                        break;
          }
  }
}

///////////////////////////// Drawing SNP Rate
function _drawDensity(snpCnt,str) {
  var snpMax=0;
  var exportFlg = storage.getItem("_exportFlg");
  if (exportFlg == 0) {
  	ctx6.fillStyle="#ffffff";
  	ctx6.fillRect(0,0,cvs6.width,cvs6.height);
  } else if (exportFlg == 1) {
	ctx18.fillStyle="#ffffff";
        ctx18.fillRect(0,0,cvs6.width,cvs6.height);
  }
/*
  var thread=4;
  var snpCnt=new Array();
  for (var y=0; y<Objects.db.length; y++) {
    	var o=new Object(JSON.parse(_getCompressedData(Objects.db[y]+"dst")));
    	for (var x=0; x<o.length; x++) {
      		if (! _isEmpty(o[x].s) ) {
        		var t=o[x].s.split("-");
        		(_isEmpty(snpCnt[x])) ? snpCnt[x]=parseInt(t[0]) : snpCnt[x]=parseInt(snpCnt[x])+parseInt(t[0]); // for SNP Rate
   		}
	}
  }
*/
  // SNP rate
  for (var k=0; k<Objects.Block;k++)
    if (!_isEmpty(snpCnt[k]))
      if (snpCnt[k]>snpMax)
        snpMax=snpCnt[k];

  // SNP rate
  for(var k=0; k<Objects.Block;k++) {
    if (!_isEmpty(snpCnt[k])) {
      for(var i=0, len=parseInt(10*snpCnt[k]/snpMax); i<len; i++) {
	if (exportFlg === "0") {
        	if ( str === "SNP" ) ctx6.fillStyle="blue";
        	  else ctx6.fillStyle="brown";
		ctx6.fillRect(k*Objects.BlockW+0.5, 18-(i*2), Objects.BlockW-1, 1.2);
	} else if (exportFlg === "1") {
		if ( str === "SNP" ) ctx18.fillStyle="blue";
                  else ctx18.fillStyle="brown";
		ctx18.fillRect(k*Objects.BlockW+0.5, 18-(i*2), Objects.BlockW-1, 1.2);
	}
        //ctx6.fillRect(k*Objects.BlockW+0.5, 18-(i*2), Objects.BlockW-1, 1.2);
      }
    }
  }
 

  // Mark "SNP Rate"
  if (exportFlg == 0) {
  	ctx5.fillStyle=_setColor().snptitle;
  	ctx5.textAlign="left";
  	ctx5.font="12px 'Arial'";
  	ctx5.fillText(str+" density", 5, cvs5.height-1);
  	//ctx5.font="10px 'Courier'";
  	ctx5.font="10px 'Arial'";
  	ctx5.textAlign="right";
  	if(storage.getItem("_Color") == "2") {
  	  ctx5.fillStyle = _setColor().tracktitle;
  	} else {
  	  //ctx5.fillStyle = "#dcdcdc";
  	  ctx5.fillStyle = "#000";
  	}
  	ctx5.fillText(String((snpMax/(Objects.db.length*_cvtZoom(Objects.Zoom))).toFixed(4)),cvs5.width-2, 8);
  } else if (exportFlg == 1) {
        ctx17.fillStyle=_setColor().snptitle;
        ctx17.textAlign="left";
        ctx17.font="12px 'Arial'";
        ctx17.fillText(str+" density", 5, cvs5.height-1);
        //ctx5.font="10px 'Courier'";
        ctx17.font="10px 'Arial'";
        ctx17.textAlign="right";
        if(storage.getItem("_Color") == "2") {
          ctx17.fillStyle = _setColor().tracktitle;
        } else {
          //ctx5.fillStyle = "#dcdcdc";
          ctx17.fillStyle = "#000";
        }
        ctx17.fillText(String((snpMax/(Objects.db.length*_cvtZoom(Objects.Zoom))).toFixed(4)),cvs5.width-2, 8);
  }
  _drawRegionHighlightCvs(cvs6);
}

///////////////////////////// Drawing INDEL block
function _drawINDELBlock(mode) {
	var exportFlg = storage.getItem("_exportFlg");
	var targetCtx = null;
	if (exportFlg == 0) {
		targetCtx = ctx4;
	} else if(exportFlg == 1) {
		targetCtx = ctx16;
	} else {
		return;
	}

  	var en=new Object(JSON.parse(storage.getItem("_Env")));
  	var snpCnt=new Array();
  	var snpMax=0;
  	var offset=en.indel_min-1;
	var o = {};
	for (var y=0, dbLen=Objects.db.length; y<dbLen; y++) {
		var topBase = y * Objects.BlockH;
		if (exportFlg == 0) {
    			o=new Object(JSON.parse(_getCompressedData(Objects.db[y])));
		} else if (exportFlg == 1) {
			o=new Object(JSON.parse(_getCompressedData(Objects.db[y]+"dst")));
		}
		for (var x=0, oLen=o.length; x<oLen; x++) {
			var leftBase = x * Objects.BlockW;
      			var ti=0;
      			var te=0;
			var snpGenehit = false;
      			if (!_isEmpty(o[x].i) ) {
				t=o[x].i.split("^");
//        			t=o[x].i.split("-");
        			ti=parseInt(t[0]);
        			te=parseInt(t[1]);
				var hit = t.slice(-1)[0];
				snpGenehit = snpGenehit || (hit === "1");
        			(_isEmpty(snpCnt[x])) ? snpCnt[x]=parseInt(t[0]) : snpCnt[x]=parseInt(snpCnt[x])+parseInt(t[0]); // for SNP Rate
      			}
      			if (!_isEmpty(o[x].d) ) {
				t=o[x].d.split("^");
//       				t=o[x].d.split("-");
        			ti=parseInt(ti)+parseInt(t[0]);
        			if ( te < parseInt(t[1]) ) te=parseInt(t[1]);
				var hit = t.slice(-1)[0];
				snpGenehit = snpGenehit || (hit === "1");
        			(_isEmpty(snpCnt[x])) ? snpCnt[x]=parseInt(t[0]) : snpCnt[x]=parseInt(snpCnt[x])+parseInt(t[0]); // for SNP Rate
      			}
        	
			if(snpGenehit) {
				targetCtx.globalAlpha = 1.0;
			} else {
				targetCtx.globalAlpha = 0.15;
			}

      			var indels = ti-offset;
      			if((!_isEmpty(o[x].i) || !_isEmpty(o[x].d)) && indels > 0 ){
        			if (Objects.Eff=="off") {
          				if(indels>_getMaxGraINDEL()-offset){
						targetCtx.fillStyle=grad_INDEL(1);
          				} else {
						targetCtx.fillStyle=grad_INDEL(indels/(_getMaxGraINDEL()-offset));
          				}
        			} else {
          				switch(te) {
                                                case 0:
							targetCtx.fillStyle="#00BFFF";
                                                        break;
                                                case 1:
							targetCtx.fillStyle="#FFFF00";
                                                        break;
                                                case 2:
							targetCtx.fillStyle="#EE9A00";
                                                        break;
                                                case 3:
							targetCtx.fillStyle="red";
                                                        break;
            					default:
							targetCtx.fillStyle="#00BFFF";
              						break;
          				}
        			}
        			if ( mode == 0 ) {
					targetCtx.fillRect(leftBase + (Objects.BlockW/10), topBase + (Objects.BlockH/10), Objects.BlockW/1.25, Objects.BlockH/1.25);
        			} else if ( mode == 1 ) {
					targetCtx.fillRect(leftBase + (Objects.BlockW/4), topBase + (Objects.BlockH/4), Objects.BlockW/2, Objects.BlockH/2);
        			} else if ( mode == 2 ) {
					targetCtx.fillRect(leftBase + (Objects.BlockW/4), topBase + (Objects.BlockH/4)*2, Objects.BlockW/2, Objects.BlockH/4);
        			} else if ( mode == 4 ) {
					targetCtx.fillRect(leftBase + (Objects.BlockW/10), topBase + (Objects.BlockH/4)*2, Objects.BlockW/1.25, Objects.BlockH/2.5);
        			} else if ( mode == 3 ) {
          				if (!_isEmpty(o[x].i) ) {
						targetCtx.fillRect(leftBase + 0.5, topBase + 0.5, Objects.BlockW-1, Objects.BlockH-1);
            					if ( t[4] == "1/1" ) {
							targetCtx.strokeStyle="#000000";
							targetCtx.lineWidth=0.5;
							targetCtx.strokeRect(leftBase + 0.5, topBase + 0.5, Objects.BlockW-1, Objects.BlockH-1);
            					}
						targetCtx.fillStyle="#000";
						targetCtx.textAlign="left";
						var insStr = "";
						var isTransposon = /[^<]/.test(t[3]);
						if(isTransposon) {
							insStr = t[3];
						} else {
							insStr = t[3].substring(1,1+t[3].length-t[2].length);
							if( storage.getItem("_DirRef") == "+" ) insStr = _reverseNucleotide(insStr);
						}
						targetCtx.fillText(insStr, leftBase + (Objects.BlockW/5)+(Objects.BlockW), topBase + Objects.BlockH-(Objects.BlockH/4));
/*
            					if ( storage.getItem("_DirRef") == "+" ) {
							targetCtx.fillText(t[3].substring(1,1+t[3].length-t[2].length), leftBase + (Objects.BlockW/5)+(Objects.BlockW), topBase + Objects.BlockH-(Objects.BlockH/4));
            					}else{
							targetCtx.fillText(_reverseNucleotide(t[3].substring(1,1+t[3].length-t[2].length)), leftBase + (Objects.BlockW/5)+(Objects.BlockW), topBase + Objects.BlockH-(Objects.BlockH/4));
            					}
*/
          				}
          				if (!_isEmpty(o[x].d) ) {
            					var w=t[2].length-t[3].length;
            					if (w<1) w=1;
						targetCtx.fillRect(leftBase + 0.5, topBase + 0.5, w*Objects.BlockW-1, Objects.BlockH-1);
            					if ( t[4] == "1/1" ) {
							targetCtx.strokeStyle="#000000";
							targetCtx.lineWidth=0.5;
							targetCtx.strokeRect(leftBase + 0.5, topBase + 0.5, w*Objects.BlockW-1, Objects.BlockH-1);
            					}
						targetCtx.fillStyle="#fff";
            					for (i=0; i<w; i++) {
							targetCtx.textAlign="center";
							targetCtx.fillText("-", leftBase + (i*Objects.BlockW)+parseInt(Objects.BlockW/2), topBase + parseInt(Objects.BlockH/1.5));
            					}
          				}
        			}
     			}
  		}
  	}
	targetCtx.globalAlpha = 1.0;

  	if (Objects.Mode != "dp+a" && Objects.Mode != "si") {
    		_drawDensity(snpCnt,"INDEL");
  	}
}
/////////////////////////////////////////////// Redraw when drag
function _drawDrag(flag) {
  ctx4.clearRect(0, 0, Objects.canvasWidth, Objects.canvasHeight);
  ctx4.putImageData(frameCellwoI, XY.x2-XY.x1, 0);
  ctx2.clearRect(0, 30, cvs2.width, 20);
  ctx2.putImageData(frameNav, XY.x2-XY.x1, 30);
  ctx1.clearRect(0, 0, cvs1.width, cvs1.height);
  ctx1.putImageData(frameTrack, XY.x2-XY.x1, 0);
  ctx6.clearRect(0, 0, cvs6.width, cvs6.height);
  ctx6.putImageData(frameSNP, XY.x2-XY.x1, 0);
  
  if(phenotypeFlg){
	  ctx12.clearRect(0, 0, Objects.canvasWidth, Objects.canvasHeight);
	  ctx12.putImageData(framePlot1, XY.x2-XY.x1, 0);
  }
  
  // Current position with on center line
  if ( flag == "onCell" ) {
    ctx4.strokeStyle=_setColor().centeringcell;
    ctx4.lineWidth=2;
/*
    ctx4.strokeRect(0,0,cvs4.width,cvs4.height);
    ctx4.lineWidth=1;
*/
    ctx4.beginPath();
    ctx4.moveTo(cvs4.width/2, 0);
    ctx4.lineTo(cvs4.width/2, cvs4.height);
    ctx4.stroke();
/*
    ctx1.strokeStyle=_setColor().centeringtrack;
    ctx1.lineWidth=1;
    ctx1.beginPath();
    ctx1.moveTo(cvs4.width/2, 0);
    ctx1.lineTo(cvs4.width/2, cvs4.height);
    ctx1.stroke();
*/
    ctx4.strokeStyle="rgba(255,0,0,0.5)";
    ctx4.lineWidth=1;
    ctx4.beginPath();
    ctx4.moveTo(XY.x2, XY.y2);
    ctx4.lineTo(cvs4.width/2, XY.y2);
    ctx4.stroke();
    ctx4.fillStyle="black";
    ctx4.fillText(parseInt((XY.x2-cvs4.width/2)/Objects.BlockW*_cvtZoom(Objects.Zoom))+" from center", XY.x2, XY.y2-5);
/*
    if(phenotypeFlg){
	    ctx12.strokeStyle=_setColor().centeringcell;
	    ctx12.lineWidth=2;
	    ctx12.strokeRect(0,0,cvs12.width,cvs12.height);
	    ctx12.lineWidth=1;
	    ctx12.beginPath();
	    ctx12.moveTo(cvs12.width/2, 0);
	    ctx12.lineTo(cvs12.width/2, cvs12.height);
	    ctx12.stroke();
	    ctx12.strokeStyle="rgba(255,0,0,0.5)";
	    ctx12.lineWidth=1;
	    ctx12.beginPath();
	    ctx12.moveTo(XY.x2, XY.y2);
	    ctx12.lineTo(cvs12.width/2, XY.y2);
	    ctx12.stroke();
	    ctx12.fillStyle="black";
	    ctx12.fillText(parseInt((XY.x2-cvs12.width/2)/Objects.BlockW*_cvtZoom(Objects.Zoom))+" from center", XY.x2, XY.y2-5);
    }
*/
  } else if (flag == "onTrack") {
    ctx1.strokeStyle=_setColor().centeringtrack;
    ctx1.lineWidth=1;
    ctx1.beginPath();
    ctx1.moveTo(cvs4.width/2, 0);
    ctx1.lineTo(cvs4.width/2, cvs4.height);
    ctx1.stroke();
    ctx1.strokeStyle="rgba(255,0,0,0.5)";
    ctx1.lineWidth=1;
    ctx1.beginPath();
    ctx1.moveTo(XY.x2, XY.y2);
    ctx1.lineTo(cvs4.width/2, XY.y2);
    ctx1.stroke();
    ctx1.fillStyle="black";
    ctx1.fillText(parseInt((XY.x2-cvs4.width/2)/Objects.BlockW*_cvtZoom(Objects.Zoom))+" from center", XY.x2, XY.y2-5);    
  } else {
/*
    ctx4.strokeStyle=_setColor().centeringcell;
    ctx4.lineWidth=2;
    //ctx4.strokeRect(0,0,cvs4.width,cvs4.height);
    ctx1.strokeStyle=_setColor().centeringtrack;
    ctx1.lineWidth=1;
    ctx1.beginPath();
    ctx1.moveTo(cvs4.width/2, 0);
    ctx1.lineTo(cvs4.width/2, cvs4.height);
    ctx1.stroke();
    ctx4.strokeStyle=_setColor().centeringcell;
    ctx4.lineWidth=1;
    ctx4.beginPath();
    ctx4.moveTo(cvs4.width/2, 0);
    ctx4.lineTo(cvs4.width/2, cvs4.height);
    ctx4.stroke();
    ctx1.strokeStyle="rgba(255,0,0,0.5)";
    ctx1.lineWidth=1;
    ctx1.beginPath();
    ctx1.moveTo(XY.x2, XY.y2);
    ctx1.lineTo(cvs4.width/2, XY.y2);
    ctx1.stroke();
    ctx1.fillStyle="black";
    ctx1.fillText(parseInt((XY.x2-cvs4.width/2)/Objects.BlockW*_cvtZoom(Objects.Zoom))+" from center", XY.x2, XY.y2-5);
*/
    if(phenotypeFlg){
	    ctx12.strokeStyle=_setColor().centeringcell;
	    ctx12.lineWidth=2;
/*
	    ctx12.strokeRect(0,0,cvs12.width,cvs12.height);
	    ctx12.strokeStyle=_setColor().centeringcell;
	    ctx12.lineWidth=1;
*/
	    ctx12.beginPath();
	    ctx12.moveTo(cvs4.width/2, 0);
	    ctx12.lineTo(cvs4.width/2, cvs4.height);
	    ctx12.stroke();

            ctx12.strokeStyle="rgba(255,0,0,0.5)";
            ctx12.lineWidth=1;
            ctx12.beginPath();
            ctx12.moveTo(XY.x2, XY.y2);
            ctx12.lineTo(cvs12.width/2, XY.y2);
            ctx12.stroke();
            ctx12.fillStyle="black";
            ctx12.fillText(parseInt((XY.x2-cvs12.width/2)/Objects.BlockW*_cvtZoom(Objects.Zoom))+" from center", XY.x2, XY.y2-5);
    }
  }
  var m=(XY.x2-XY.x1)%Objects.BlockW;
  var p=Objects.Pos-(XY.x2-XY.x1)/Objects.BlockW;
  if (p>-1 && p+Objects.Block<_last(Objects.Zoom)) _drawMeter(p);
  if ( Objects.Indicator == "on" ) {
    _drawIndicator();
    _drawDirection();
  }
  // Capture tracks without rules
  _drawRules();
  if (phenotypeFlg) {
	_drawRulesforPlot();
  }
}

///////////////////////////// Drawing Indicator
function _drawIndicator() {
/*
  if(phenotypeFlg){
	  $('#phenotype_button_div').show();
  }
*/
  var Ix=cvs7.width-145;
  var Iy=5;
  var Ia=0;
  var element = document.getElementById("ind"); 

  if ( Objects.Eff == "off" ) {
    if (Objects.Snpblock == "off"){
      if (Objects.Onebase == "off"){
        switch (Objects.Mode) {
          case "dp":
/*
        	if(phenotypeFlg){
        		element.style.clip = 'rect(22px,150px,165px,0px)';
        	}else{
        		element.style.clip = 'rect(32px,150px,165px,0px)';
        	}
*/ 
       	    element.style.clip = 'rect(32px,150px,165px,0px)';
            Ia=36;
            Iy=Iy+Ia;
            _drawIndicator_DP(Ix,Iy);
            break;
          case "dp+s":
             Ia=18;
             Iy=Iy+Ia;
             if(phenotypeFlg){
            	 element.style.clip = 'rect(6px,150px,165px,0px)';
             }else{
            	 element.style.clip = 'rect(16px,150px,165px,0px)';
             }
            _drawIndicator_DP(Ix,Iy);
            _drawIndicator_SNP(Ix,Iy=Iy+18);
            _drawIndicator_Filter(Ia);
            break;
          case "dp+i":
            Ia=18;
            Iy=Iy+Ia;
            if(phenotypeFlg){
            	element.style.clip = 'rect(6px,150px,165px,0px)';
            }else{
            	element.style.clip = 'rect(16px,150px,165px,0px)';
            }
            _drawIndicator_DP(Ix,Iy);
            _drawIndicator_INDEL(Ix,Iy=Iy+18);
            _drawIndicator_Filter(Ia);
            break;
          case "dp+a":
        	if(phenotypeFlg){
        		element.style.clip = 'rect(-10px,150px,165px,0px)';
        	}else{
        		element.style.clip = 'rect(0px,150px,165px,0px)';
        	}
            _drawIndicator_DP(Ix,Iy);
            _drawIndicator_SNP(Ix,Iy=Iy+18);
            _drawIndicator_INDEL(Ix,Iy=Iy+18);
            _drawIndicator_Filter(Ia);
            break;
          case "s":
            Ia=36;
            Iy=Iy+Ia;
            if(phenotypeFlg){
            	element.style.clip = 'rect(0px,150px,165px,0px)';
            }else{
            	element.style.clip = 'rect(32px,150px,165px,0px)';
            }
            _drawIndicator_SNP(Ix,Iy);
            _drawIndicator_Filter(Ia);
            break;
          case "i":
            Ia=36;
            Iy=Iy+Ia;
            if(phenotypeFlg){
            	element.style.clip = 'rect(22px,150px,165px,0px)';
            }else{
            	element.style.clip = 'rect(32px,150px,165px,0px)';
            }
            _drawIndicator_INDEL(Ix,Iy);
            _drawIndicator_Filter(Ia);
            break;
          case "si":
            Ia=18;
            Iy=Iy+Ia;
            if(phenotypeFlg){
            	element.style.clip = 'rect(6px,150px,165px,0px)';
            }else{
            	element.style.clip = 'rect(16px,150px,165px,0px)';
            }
            _drawIndicator_SNP(Ix,Iy);
            _drawIndicator_INDEL(Ix,Iy=Iy+18);
            _drawIndicator_Filter(Ia);
            break;
        }
      }else{
        switch (Objects.Mode) {
          case "dp":
        	if(phenotypeFlg){
        		element.style.clip = 'rect(22px,150px,165px,0px)';
        	}else{
        		element.style.clip = 'rect(32px,150px,165px,0px)';
        	}
            Ia=36;
            Iy=Iy+Ia;
            _drawIndicator_DP(Ix,Iy);
            break;
          case "dp+s":
             Ia=18;
             Iy=Iy+Ia;
             if(phenotypeFlg){
            	 element.style.clip = 'rect(6px,150px,165px,0px)';
             }else{
            	 element.style.clip = 'rect(16px,150px,165px,0px)';
             }
            _drawIndicator_DP(Ix,Iy);
            _drawIndicator_Nuc(Ix,Iy=Iy+18);
            _drawIndicator_Filter(Ia);
            break;
          case "dp+i":
            Ia=18;
            Iy=Iy+Ia;
            if(phenotypeFlg){
            	element.style.clip = 'rect(6px,150px,165px,0px)';
            }else{
            	element.style.clip = 'rect(16px,150px,165px,0px)';
            }
            _drawIndicator_DP(Ix,Iy);
            _drawIndicator_IndelOnebase(Ix,Iy=Iy+18);
            _drawIndicator_Filter(Ia);
            break;
          case "dp+a":
        	  if(phenotypeFlg){
        		  element.style.clip = 'rect(-10px,150px,165px,0px)';
        	  }else{
        		  element.style.clip = 'rect(0px,150px,165px,0px)';
        	  }
            _drawIndicator_DP(Ix,Iy);
            _drawIndicator_Nuc(Ix,Iy=Iy+18);
            _drawIndicator_IndelOnebase(Ix,Iy=Iy+18);
            _drawIndicator_Filter(Ia);
            break;
          case "s":
            Ia=36;
            Iy=Iy+Ia;
            if(phenotypeFlg){
            	element.style.clip = 'rect(22px,150px,165px,0px)';
            }else{
            	element.style.clip = 'rect(32px,150px,165px,0px)';
            }
            _drawIndicator_Nuc(Ix,Iy);
            _drawIndicator_Filter(Ia);
            break;
          case "i":
            Ia=36;
            Iy=Iy+Ia;
            if(phenotypeFlg){
            	element.style.clip = 'rect(22px,150px,165px,0px)';
            }else{
            	element.style.clip = 'rect(32px,150px,165px,0px)';
            }
            _drawIndicator_IndelOnebase(Ix,Iy);
            _drawIndicator_Filter(Ia);
            break;
          case "si":
            Ia=18;
            Iy=Iy+Ia;
            if(phenotypeFlg){
            	element.style.clip = 'rect(6px,150px,165px,0px)';
            }else{
            	element.style.clip = 'rect(16px,150px,165px,0px)';
            }
            _drawIndicator_Nuc(Ix,Iy);
            _drawIndicator_IndelOnebase(Ix,Iy=Iy+18);
            _drawIndicator_Filter(Ia);
            break;
        }
      }
    }else{
      if(Objects.Mode == "dp" || Objects.Mode == "dp+s" || Objects.Mode == "dp+i" || Objects.Mode == "dp+a"){
    	  if(phenotypeFlg){
    		  element.style.clip = 'rect(-10px,150px,165px,0px)';
    	  }else{
    		  element.style.clip = 'rect(0px,150px,165px,0px)';
    	  }
        _drawIndicator_DP(Ix,Iy);
        _drawIndicator_SNP(Ix,Iy=Iy+18);
        _drawIndicator_SNPblock(Ix,Iy=Iy+18);
        _drawIndicator_Filter(Ia);
      }else{
        Ia=18;
        Iy=Iy+Ia;
        if(phenotypeFlg){
        	element.style.clip = 'rect(6px,150px,165px,0px)';
        }else{
        	element.style.clip = 'rect(16px,150px,165px,0px)';
        }
        _drawIndicator_SNP(Ix,Iy);
        _drawIndicator_SNPblock(Ix,Iy=Iy+18);
        _drawIndicator_Filter(Ia);
      }
    }
  } else {
    switch (Objects.Mode) {
      case "dp":
/*
    	  if(phenotypeFlg){
    		  element.style.clip = 'rect(22px,150px,165px,0px)';
    	  }else{
    		  element.style.clip = 'rect(32px,150px,165px,0px)';
    	  }
*/
	element.style.clip = 'rect(22px,150px,165px,0px)';
        Ia=36;
        Iy=Iy+Ia;
        _drawIndicator_DP(Ix,Iy);
        break;
      case "dp+s":
        //Ia=18;
        Ia=0;
        Iy=Iy+Ia;
/*
        if(phenotypeFlg){
        	//element.style.clip = 'rect(6px,150px,165px,0px)';
        	element.style.clip = 'rect(0px,150px,165px,0px)';
        }else{
        	element.style.clip = 'rect(16px,150px,165px,0px)';
        }
*/
	element.style.clip = 'rect(0px,150px,165px,0px)';
        _drawIndicator_DP(Ix,Iy);
        _drawIndicator_EFF(Ix,Iy=Iy+18,1);
        _drawIndicator_EFF(Ix,Iy=Iy+18,2);
        _drawIndicator_Filter(Ia);
        break;
      case "dp+i":
        //Ia=18;
        Ia=0;
        Iy=Iy+Ia;
/*
        if(phenotypeFlg){
        	//element.style.clip = 'rect(6px,150px,165px,0px)';
        	element.style.clip = 'rect(0px,150px,165px,0px)';
        }else{
        	element.style.clip = 'rect(16px,150px,165px,0px)';
        }
*/
	element.style.clip = 'rect(0px,150px,165px,0px)';
        _drawIndicator_DP(Ix,Iy);
        _drawIndicator_EFF(Ix,Iy=Iy+18,1);
        _drawIndicator_EFF(Ix,Iy=Iy+18,2);
        _drawIndicator_Filter(Ia);
        break;
      case "dp+a":
        //Ia=18;
        Ia=0;
        Iy=Iy+Ia;
/*
        if(phenotypeFlg){
        	element.style.clip = 'rect(0px,150px,165px,0px)';
        }else{
        	element.style.clip = 'rect(16px,150px,165px,0px)';
        }
*/
	element.style.clip = 'rect(0px,150px,165px,0px)';
        _drawIndicator_DP(Ix,Iy);
        _drawIndicator_EFF(Ix,Iy=Iy+18,1);
        _drawIndicator_EFF(Ix,Iy=Iy+18,2);
        _drawIndicator_Filter(Ia);
        break;
      case "s":
        Ia=18;
        Iy=Iy+Ia;
/*
        if(phenotypeFlg){
        	element.style.clip = 'rect(0px,150px,165px,0px)';
        }else{
        	element.style.clip = 'rect(32px,150px,165px,0px)';
        }
*/
	element.style.clip = 'rect(0px,150px,165px,0px)';
        _drawIndicator_EFF(Ix,Iy=Iy,1);
        _drawIndicator_EFF(Ix,Iy=Iy+18,2);
        _drawIndicator_Filter(Ia);
        break;
      case "i":
        Ia=18;
        Iy=Iy+Ia;
/*
        if(phenotypeFlg){
        	element.style.clip = 'rect(0px,150px,165px,0px)';
        }else{
        	element.style.clip = 'rect(32px,150px,165px,0px)';
        }
*/
	element.style.clip = 'rect(0px,150px,165px,0px)';
        _drawIndicator_EFF(Ix,Iy=Iy,1);
        _drawIndicator_EFF(Ix,Iy=Iy+18,2);
        _drawIndicator_Filter(Ia);
        break;
      case "si":
        Ia=18;
        Iy=Iy+Ia;
/*
        if(phenotypeFlg){
        	element.style.clip = 'rect(0px,150px,165px,0px)';
        }else{
        	element.style.clip = 'rect(32px,150px,165px,0px)';
        }
*/
	element.style.clip = 'rect(0px,150px,165px,0px)';
        _drawIndicator_EFF(Ix,Iy=Iy,1);
        _drawIndicator_EFF(Ix,Iy=Iy+18,2);
        _drawIndicator_Filter(Ia);
        break;
    }
  }
  if ( Objects._Null == "true" ) {
    _drawIndicator_NULL(Ix,Iy=Iy+18);
  }

  Iy=Iy+18+15; // For border of indicator
  ctx7.strokeStyle="#000080";
  ctx7.lineWidth=3;
  ctx7.strokeRect(cvs7.width-145,5+Ia,140,Iy-20-Ia);
  // Set information of indicator area
  Objects.Ix=Ix;
  Objects.Iy=Iy;
}

// Direction
var dirBlockW = 21;	// <= 25
var dirLeftOffset = 2;
var indDirBoxPos = {'left':{}, 'right':{}, 'leftpage':{}, 'rightpage':{}, 'zoomin':{}, 'zoomout':{}, 'clear':{}};
function _setIndDirBoxPos(type, left) {
	indDirBoxPos[type] = {'l':left+1, 't':cvs7.height-24.5, 'r':left+dirBlockW-2, 'b':cvs7.height-6.5, 'w':dirBlockW-2, 'h':16};
//	indDirBoxPos[type] = {'l':left, 't':cvs7.height-25.5, 'r':left+dirBlockW-1, 'b':cvs7.height-7.5, 'w':dirBlockW, 'h':18};
}
function _drawDirLeft(color) {
	var left = 1 * dirBlockW + dirLeftOffset;

	ctx7.strokeStyle = color;
	ctx7.lineWidth=4;
	ctx7.beginPath();
	ctx7.moveTo(left+9, cvs7.height-22);
	ctx7.lineTo(left+5, cvs7.height-17);
	ctx7.lineTo(left+9, cvs7.height-12);
	ctx7.closePath();
	ctx7.fill();
	ctx7.stroke();
//	console.log("DrawLeft");

	_setIndDirBoxPos('left', left);
}
function _drawDirRight(color) {
	var left = 4 * dirBlockW + dirLeftOffset;

	ctx7.strokeStyle = color;
	ctx7.lineWidth=4;
	ctx7.beginPath();
	ctx7.moveTo(left+11, cvs7.height-22);
	ctx7.lineTo(left+15, cvs7.height-17);
	ctx7.lineTo(left+11, cvs7.height-12);
	ctx7.closePath();
	ctx7.fill();
	ctx7.stroke();
//	console.log("DrawRight");

	_setIndDirBoxPos('right', left);
}
function _drawDirZoomIn(color) {
	var left = 2 * dirBlockW + dirLeftOffset;

	ctx7.fillStyle = color;
	ctx7.fillRect(left+4,cvs7.height-25.5,6,18);
	ctx7.fillRect(left-1,cvs7.height-20,16,6);
//	console.log("DrawZoomIn");

	_setIndDirBoxPos('zoomin', left);
}
function _drawDirZoomOut(color) {
	var left = 3 * dirBlockW + dirLeftOffset;

	ctx7.fillStyle = color;
	ctx7.fillRect(left+4,cvs7.height-20,16,6);
//	console.log("DrawZoomOut");

	_setIndDirBoxPos('zoomout', left);
}
function _drawDirLeftPage(color) {
	var left = 0 * dirBlockW + dirLeftOffset;

	ctx7.strokeStyle = color;
	ctx7.lineWidth=4;
	ctx7.beginPath();
	ctx7.moveTo(left+14, cvs7.height-22);
	ctx7.lineTo(left+11, cvs7.height-17);
	ctx7.lineTo(left+14, cvs7.height-12);
	ctx7.closePath();
	ctx7.moveTo(left+8, cvs7.height-22);
	ctx7.lineTo(left+5, cvs7.height-17);
	ctx7.lineTo(left+8, cvs7.height-12);
	ctx7.closePath();
	ctx7.fill();
	ctx7.stroke();
//	console.log("DrawLeftPage");

	_setIndDirBoxPos('leftpage', left);
}
function _drawDirRightPage(color) {
	var left = 5 * dirBlockW + dirLeftOffset;

	ctx7.strokeStyle = color;
	ctx7.lineWidth=4;
	ctx7.beginPath();
	ctx7.moveTo(left+11, cvs7.height-22);
	ctx7.lineTo(left+14, cvs7.height-17);
	ctx7.lineTo(left+11, cvs7.height-12);
	ctx7.closePath();
	ctx7.moveTo(left+5, cvs7.height-22);
	ctx7.lineTo(left+8, cvs7.height-17);
	ctx7.lineTo(left+5, cvs7.height-12);
	ctx7.closePath();
	ctx7.fill();
	ctx7.stroke();
//	console.log("DrawRightPage");

	_setIndDirBoxPos('rightpage', left);
}
function _drawDirClearHighlight(defColor, hlColor) {
	var left = 6 * dirBlockW + dirLeftOffset;

	if(isRegionHighlighted()) {
		ctx7.fillStyle = hlColor;
	} else {
		ctx7.fillStyle = defColor;
	}

	ctx7.save();
	ctx7.translate(left+dirBlockW/2 - 3, cvs7.height-16.5);
	for(var i=0; i<8; i++) {
		ctx7.fillRect(-1, -9.5, 2, 4);
		ctx7.rotate(Math.PI * 0.25);
	}
/*
	for(var i=0; i<6; i++) {
		ctx7.fillRect(-1.5, -8.5, 3, 4.5);
		ctx7.rotate(Math.PI * 0.333);	// <= ctx7.rotate((60 * Math.PI) / 180);
	}
*/
	ctx7.restore();

	_setIndDirBoxPos('clear', left);
}
function _drawDirection() {
    _drawDirLeft("black");
    _drawDirRight("black");
    _drawDirZoomIn("black");
    _drawDirZoomOut("black");
    _drawDirLeftPage("black");
    _drawDirRightPage("black");
    _drawDirClearHighlight("#aaaaaa", "#0000ee")
}

// Indicator: Filter bottom of right side
function _drawIndicator_Filter(Ia) {
  ctx7.fillStyle="white";
  ctx7.fillRect(cvs7.width-145,cvs7.height-54,140,18);
  ctx7.strokeStyle="#000080";
  ctx7.lineWidth=2.5;
  ctx7.strokeRect(cvs7.width-145,cvs7.height-54,140,18);
  //var str="QUAL>="+storage.getItem("_QUAL")+";";
  var headstr="VarFilt."
  var str="Q≧"+storage.getItem("_QUAL");
  var str2="DP≧"+storage.getItem("_DP");
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  //ctx7.font="11px 'Courier'";
  ctx7.font="12px 'Arial'";
  ctx7.fillText(headstr,cvs7.width-142,cvs7.height-42);
  ctx7.fillText(str,cvs7.width-102,cvs7.height-42);
  ctx7.fillText(str2,cvs7.width-52,cvs7.height-42);
}

// Indicator: NULL of Depth
function _drawIndicator_NULL(Ix,Iy) {
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  ctx7.fillStyle="#fff";
  ctx7.fillRect(Ix,Iy,140,18);
  ctx7.fillStyle="PaleGoldenrod";
  //ctx7.fillRect(Ix+40,Iy+3,80,12);
  ctx7.fillRect(Ix+40,Iy+3,65,10);
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  //ctx7.font="10px 'Courier'";
  ctx7.font="11px 'Arial'";
  if (storage.getItem('_CSTM') == "on"){
    ctx7.fillText(en.cstm_kind+"=NA",Ix+50,Iy+12);
  }else{
    //ctx7.fillText("DEPTH=NULL",Ix+50,Iy+12);
    ctx7.fillText("DEPTH=NA",Ix+50,Iy+12);
  }
}

// Indicator: EFF
function getEmptyIndEffPos() {
  return {"0":{}, "1":{}, "2":{}, "3":{}};
}
var indEffBoxPos = getEmptyIndEffPos();
function _drawIndicator_EFF(Ix,Iy,flag) {
  var effFilterMap = _getEffFilterMap();
  var funcSetBgColor = function(impact) {
	ctx7.fillStyle =_getSnpeffImpactColor(impact);
	if(impact.toString() in effFilterMap && !effFilterMap[impact.toString()]) {
		ctx7.fillStyle = "#DDDDDD";
	} else {
		ctx7.fillStyle = _getSnpeffImpactColor(impact);
	}
  }
  var funcSetFgColor = function(impact) {
	if(impact.toString() in effFilterMap && !effFilterMap[impact.toString()]) {
		ctx7.fillStyle = "#FFFFFF";
	} else {
		if(impact === 3) {
			ctx7.fillStyle = "white";
		} else {
			ctx7.fillStyle = "black";
		}
	}
  }
  var funcDrawBg = function(impact, x, y, w, h) {
	funcSetBgColor(impact);
	ctx7.fillRect(x, y, w, h);
	indEffBoxPos[String(impact)] = {"x":x, "y":y, "w":w, "h":h};
  }

  ctx7.fillStyle="#fff";
  ctx7.fillRect(Ix,Iy,140,18);
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  ctx7.font="11px 'Arial'";
  if(flag == 1) {
	ctx7.fillText("SnpEff",Ix+4,Iy+13);

	// MODIFIER
//	funcSetBgColor(0);
//	ctx7.fillRect(Ix+43,Iy+3,50,12);
	funcDrawBg(0, Ix+43, Iy+3, 50, 12);

	// LOW
//	funcSetBgColor(1);
//	ctx7.fillRect(Ix+95,Iy+3,40,12);
	funcDrawBg(1, Ix+95, Iy+3, 40, 12);
  } else if (flag == 2) {
	// MODERATE
//	funcSetBgColor(2);
//	ctx7.fillRect(Ix+43,Iy+3,50,12);
	funcDrawBg(2, Ix+43, Iy+3, 50, 12);

	// HIGH
//	funcSetBgColor(3);
//	ctx7.fillRect(Ix+95,Iy+3,40,12);
	funcDrawBg(3, Ix+95, Iy+3, 40, 12);
  }

  ctx7.textAlign="right";
  ctx7.font="9px 'Arial'";
  if(flag == 1) {
	funcSetFgColor(0);
	ctx7.fillText("MODIFIER",Ix+92,Iy+13);

	funcSetFgColor(1);
	ctx7.fillText("LOW",Ix+126,Iy+13);
  } else if (flag == 2) {
	funcSetFgColor(2);
	ctx7.fillText("MODERATE",Ix+93,Iy+13);
	funcSetFgColor(3);
	ctx7.fillText("HIGH",Ix+126,Iy+13);
  }
}

// Indicator: nucleotide
function _drawIndicator_Nuc(Ix,Iy) {
  ctx7.fillStyle="#fff";
  ctx7.fillRect(Ix,Iy,140,18);
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  //ctx7.font="10px 'Courier'";
  ctx7.font="11px 'Arial'";
  ctx7.fillText("SNP",Ix+4,Iy+13);
  ctx7.fillStyle="rgba(255,193,37,1.0)";
  ctx7.fillRect(Ix+43,Iy+3,22,12);
  ctx7.fillStyle="rgba(218,107,169,1.0)";
  ctx7.fillRect(Ix+67,Iy+3,22,12);
  ctx7.fillStyle="rgba(60,179,113,1.0)";
  ctx7.fillRect(Ix+91,Iy+3,22,12);
  ctx7.fillStyle="rgba(0,100,255,1.0)";
  ctx7.fillRect(Ix+115,Iy+3,21,12);
  ctx7.textAlign="right";
  //ctx7.font="8px 'Courier'";
  ctx7.font="11px 'Arial'";
  ctx7.fillStyle="#000";
  ctx7.fillText("A",Ix+57,Iy+13);
  ctx7.fillText("T",Ix+81,Iy+13);
  ctx7.fillStyle="#fff";
  ctx7.fillText("G",Ix+105,Iy+13);
  ctx7.fillText("C",Ix+129,Iy+13);
}

// Indicator: indel  one-base
function _drawIndicator_IndelOnebase(Ix,Iy) {
  ctx7.fillStyle="#fff";
  ctx7.fillRect(Ix,Iy,140,18);
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  //ctx7.font="10px 'Courier'";
  ctx7.font="11px 'Arial'";
  ctx7.fillText("INDEL",Ix+4,Iy+13);
  ctx7.fillStyle="rgba(213,94,0,1.0)";
  ctx7.fillRect(Ix+43,Iy+3,46,12);
  ctx7.fillStyle="rgba(86,180,233,1.0)";
  ctx7.fillRect(Ix+91,Iy+3,45,12);
  //ctx7.font="8px 'Courier'";
  ctx7.font="11px 'Arial'";
  ctx7.fillStyle="#fff";
  ctx7.fillText("INS",Ix+57,Iy+13);
  ctx7.fillText("DEL",Ix+104,Iy+13);
}

// Indicator: DEPTH and custom track
function _drawIndicator_DP(Ix,Iy) {
  var cstm=storage.getItem('_CSTM');
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  var cstm_max=en.cstm_max;
  
  ctx7.fillStyle="#fff";
  ctx7.fillRect(Ix,Iy,140,18);
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  //ctx7.font="10px 'Courier'";
  ctx7.font="11px 'Arial'";
  if(cstm=="on"){
    var condArray = storage.getItem("_CrtCondition").split("|");
    var cond = parseInt(condArray[0]);
    var valid = 0;
    var condArrayLen=condArray.length;
    for(var a=0; a<condArrayLen; a++){if(condArray[a]!=""){valid++;}}
//    for(var a=0; a<condArray.length; a++){if(condArray[a]!=""){valid++;}}
    var CondBlockHeight = parseInt(12/valid);
    var drawn = 0;
    var row = 0;
    ctx7.fillText(en.cstm_kind,Ix+5,Iy+13,35);
    ctx7.strokeStyle="#000";
    ctx7.lineWidth=0.2;
    ctx7.strokeRect(Ix+43,Iy+3,70,12);
    for(var b=0; b<condArrayLen; b++){
//    for(var b=0; b<condArray.length; b++){
      if(b==0){
        ctx7.fillStyle=en["cstm_max_col"];
      }else{
        ctx7.fillStyle=en["cstm_max_col_para"+b];
      }
      if(condArray[b] != ""){
        if(b > (valid-1)){
          row = valid-1;
        }else{
          row = drawn;
        }
        ctx7.fillStyle=grad_CSTM_array[b](0);
        ctx7.fillRect(Ix+43,Iy+3+parseInt(row*CondBlockHeight),17,CondBlockHeight);
        ctx7.fillStyle=grad_CSTM_array[b]((cstm_max*0.25)/cstm_max);
        ctx7.fillRect(Ix+59,Iy+3+parseInt(row*CondBlockHeight),17,CondBlockHeight);
        ctx7.fillStyle=grad_CSTM_array[b]((cstm_max*0.5)/cstm_max);
        ctx7.fillRect(Ix+76,Iy+3+parseInt(row*CondBlockHeight),17,CondBlockHeight);
        ctx7.fillStyle=grad_CSTM_array[b]((cstm_max*0.75)/cstm_max);
        ctx7.fillRect(Ix+93,Iy+3+parseInt(row*CondBlockHeight),17,CondBlockHeight);
        ctx7.fillStyle=grad_CSTM_array[b](1);
        ctx7.fillRect(Ix+110,Iy+3+parseInt(row*CondBlockHeight),26,CondBlockHeight);
        drawn++;
      }
    }
    ctx7.textAlign="right";
    ctx7.fillStyle="#000";
    ctx7.fillText(en.cstm_min,Ix+53,Iy+12);
    //ctx7.fillStyle="yellow";
    ctx7.fillStyle="black";
    ctx7.fillText(parseInt(cstm_max),Ix+134,Iy+12);
  }else{
    ctx7.fillText("DEPTH",Ix+5,Iy+13);
    ctx7.strokeStyle="#000";
    ctx7.lineWidth=0.2;
    //ctx7.strokeRect(Ix+43,Iy+3,70,12);
    ctx7.strokeRect(Ix+43,Iy+3,93,12);
    ctx7.fillStyle=grad_DP(0);
    ctx7.fillRect(Ix+43,Iy+3,17,12);
    ctx7.fillStyle=grad_DP((_getMaxGraDP()*0.25)/_getMaxGraDP());
    ctx7.fillRect(Ix+59,Iy+3,17,12);
    ctx7.fillStyle=grad_DP((_getMaxGraDP()*0.5)/_getMaxGraDP());
    ctx7.fillRect(Ix+76,Iy+3,17,12);
    ctx7.fillStyle=grad_DP((_getMaxGraDP()*0.75)/_getMaxGraDP());
    ctx7.fillRect(Ix+93,Iy+3,17,12);
    ctx7.fillStyle=grad_DP(1);
    ctx7.fillRect(Ix+110,Iy+3,26,12);
    ctx7.textAlign="right";
    ctx7.fillStyle="#000";
    ctx7.fillText(en.depth_min,Ix+53,Iy+12);
    ctx7.fillStyle="yellow";
    ctx7.fillText(_getMaxGraDP(),Ix+134,Iy+12);
  }
}

// Indicator: SNP
function _drawIndicator_SNP(Ix,Iy) {
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  ctx7.fillStyle="#fff";
  ctx7.fillRect(Ix,Iy,140,18);
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  //ctx7.font="10px 'Courier'";
  ctx7.font="11px 'Arial'";
  ctx7.fillText("SNP",Ix+5,Iy+13);
  ctx7.strokeStyle="#000";
  ctx7.lineWidth=0.2;
  //ctx7.strokeRect(Ix+43,Iy+3,70,12);
  ctx7.strokeRect(Ix+43,Iy+3,93,12);
  ctx7.fillStyle=grad_S((_getMaxGraSNP()*0.1)/_getMaxGraSNP());
  ctx7.fillRect(Ix+59,Iy+3,17,12);
  ctx7.fillStyle=grad_S((_getMaxGraSNP()*0.3)/_getMaxGraSNP());
  ctx7.fillRect(Ix+76,Iy+3,17,12);
  ctx7.fillStyle=grad_S((_getMaxGraSNP()*0.5)/_getMaxGraSNP());
  ctx7.fillRect(Ix+93,Iy+3,17,12);
  ctx7.fillStyle=grad_S(1);
  ctx7.fillRect(Ix+110,Iy+3,26,12);
  ctx7.fillStyle="#000";
  ctx7.textAlign="right";
  ctx7.fillText(en.snp_min-1,Ix+53,Iy+12);
  ctx7.fillText(_getMaxGraSNP(),Ix+133,Iy+12);
}

// Indicator: SNPblock
function _drawIndicator_SNPblock(Ix,Iy) {
  ctx7.fillStyle="#fff";
  ctx7.fillRect(Ix,Iy,140,18);
  ctx7.fillStyle="rgba(0,255,98,0.4)";
  ctx7.fillRect(Ix+40,Iy+3,60,12);
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  //ctx7.font="10px 'Courier'";
  ctx7.font="11px 'Arial'";
  ctx7.fillText("Snpblock",Ix+47,Iy+12);
}

// Indicator: INDEL
function _drawIndicator_INDEL(Ix,Iy) {
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  ctx7.fillStyle="#fff";
  ctx7.fillRect(Ix,Iy,140,18);
  ctx7.fillStyle="black";
  ctx7.textAlign="left";
  //ctx7.font="10px 'Courier'";
  ctx7.font="11px 'Arial'";
  ctx7.fillText("INDEL",Ix+5,Iy+13);
  ctx7.strokeStyle="#000";
  ctx7.lineWidth=0.2;
  //ctx7.strokeRect(Ix+43,Iy+3,70,12);
  ctx7.strokeRect(Ix+43,Iy+3,93,12);
  ctx7.fillStyle=grad_INDEL((_getMaxGraINDEL()*0.1)/_getMaxGraINDEL());
  ctx7.fillRect(Ix+59,Iy+3,17,12);
  ctx7.fillStyle=grad_INDEL((_getMaxGraINDEL()*0.3)/_getMaxGraINDEL());
  ctx7.fillRect(Ix+76,Iy+3,17,12);
  ctx7.fillStyle=grad_INDEL((_getMaxGraINDEL()*0.5)/_getMaxGraINDEL());
  ctx7.fillRect(Ix+93,Iy+3,17,12);
  ctx7.fillStyle=grad_INDEL(1);
  ctx7.fillRect(Ix+110,Iy+3,26,12);
  ctx7.fillStyle="#000";
  ctx7.textAlign="right";
  ctx7.fillText(en.indel_min-1,Ix+53,Iy+12);
  ctx7.fillStyle="#fff";
  ctx7.fillText(_getMaxGraINDEL(),Ix+133,Iy+12);
}

/////////////////////////////////////////////// Convert Canvas to PNG
function _drawExportImg() {
  o=_chromosome();
  _messageOnScreen("Now drawing this page.");
  var img=new Image();
  var type='image/png';
  var pngCanvas = document.createElement("canvas");
  var pngContext =pngCanvas.getContext('2d');

  var leftOffset = 5;
  var innerOffset = 10;

  pngCanvas.width = Objects.titleWidth+Objects.canvasWidth+10;
  if (phenotypeFlg && storage.getItem("_GWAS")=="on") {
  	pngCanvas.height = Objects.TrackH+Objects.NavH+Objects.canvasHeight+170;
  } else {
  	pngCanvas.height = Objects.TrackH+Objects.NavH+Objects.canvasHeight+90;
  }

  // fill Background color
  pngContext.fillStyle="#F7F7F9";
  pngContext.fillRect(0,0,pngCanvas.width, pngCanvas.height);

  // fill Title background color
  var cvs11BgPixel = cvs11.getContext('2d').getImageData(0, 0, 1, 1);
  pngContext.fillStyle="rgb(" + cvs11BgPixel.data[0] + "," + cvs11BgPixel.data[1] + "," + cvs11BgPixel.data[2] + ")";
  pngContext.fillRect(leftOffset, 5, Objects.titleWidth+5, pngCanvas.height - 15);

  // Reference name
  pngContext.drawImage(cvs11, leftOffset, 60);
/*
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  pngContext.fillStyle=_setColor().reftitle;
  pngContext.font="14px 'Arial'";
  pngContext.fillText(en.reference_name,Objects.titleWidth-80,70);
*/

  pngContext.drawImage(cvs2, Objects.titleWidth+innerOffset, 50);	// Position meter
  pngContext.drawImage(cvs9, Objects.titleWidth+o.width+10, 5);		// Block size panel

  // Chr+Position in Block size panel
  var nowPos = storage.getItem("_nowPos");
  pngContext.fillStyle="white";
  pngContext.font="16px 'Arial'";
  pngContext.fillText(nowPos, Objects.titleWidth + o.width + 20, 70);

  // Track top dividing line
  pngContext.beginPath();
  pngContext.moveTo(leftOffset, 110);
  pngContext.lineTo(pngCanvas.width,110);
  pngContext.strokeStyle="#c3c3c3";
  pngContext.lineWidth="1";
  pngContext.stroke();

  // Tracks (include oneBaseGuide, Primer3Result, BlastResult)
  pngContext.drawImage(cvs0, leftOffset, 110);
  pngContext.drawImage(cvs1, Objects.titleWidth+innerOffset, 110);

  var gwasH = 0;
/*
  var oneBaseH = 0;
  var p3Height = 0;
  if (storage.getItem("_Zoom") == "1b") {
	oneBaseH = 66;
  }
  if (storage.getItem("_Prm_str")) {
	p3Height = 41;
  }
  var addTrackH = oneBaseH + p3Height;
*/
  var addTrackH = 0;
  if (phenotypeFlg  && storage.getItem("_GWAS")=="on") {
	gwasH = 81;
	var gwasTop = 110 + Objects.TrackH + addTrackH;

	// GWAS top dividing line
	pngContext.beginPath();
	pngContext.moveTo(leftOffset, gwasTop);
	pngContext.lineTo(pngCanvas.width, gwasTop);
	pngContext.strokeStyle="#c3c3c3";
	pngContext.lineWidth="1";
	pngContext.stroke();

	// GWAS
	pngContext.drawImage(cvs13, leftOffset, gwasTop);	// GWAS title
        pngContext.drawImage(cvs12, Objects.titleWidth+innerOffset, gwasTop);	// GWAS plot
  }

  var accListTop = 110 + Objects.TrackH + addTrackH + gwasH;

  // Accession list top dividing line
  pngContext.beginPath();
  pngContext.moveTo(leftOffset, accListTop);
  pngContext.lineTo(pngCanvas.width, accListTop);
  pngContext.strokeStyle="#c3c3c3";
  pngContext.lineWidth="1";
  pngContext.stroke();

  // Accession list(DEPTH/SNP/SnpEff)
  var thread=4;
  var jqXHRList = [];
  var datas = [];
  var results = [];
  var dst = "";
  var dstdata = "";
  var acLen = new Array();
  var acPos = new Array();
  acLen[0]=0;
  acPos[0]=1;
  var len = parseInt(Objects.db.length);
  countaAc=parseInt(len/thread);
  mod = (len)%thread;
  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 prm_Gene = ""; var prm_ExcludeUpDownVar = "";
  if(storage.getItem("_HighlightVariantGene")) {
    prm_Gene = storage.getItem("_HighlightVariantGene");
    if(storage.getItem("_HighlightVariantExclUpDown")) prm_ExcludeUpDownVar = "1";
  }
  if(thread != 1){
    for (var i = 1; i <= thread; i++) {
    	jqXHRList.push($.ajax({
        	url: "./bin/"+_backendSelector("data.php"),
                type: "POST",
		async:false,
                cache: false,
                data: {
                	"prm_Ref":storage.getItem("_Ref"),
                        "prm_width":storage.getItem("_BlockW"),
                        "prm_Zoom":storage.getItem("_Zoom"),
                        "prm_Chr":storage.getItem("_Chr"),
                        "prm_Pos":storage.getItem("_Pos"),
                        "prm_QUAL":storage.getItem("_QUAL"),
                        "prm_DP":storage.getItem("_DP"),
                        "prm_DP4":storage.getItem("_DP4"),
                        "prm_EffGrps":storage.getItem("_EffGrps"),
                        "prm_Block":storage.getItem("_Block"),
                        "prm_Lists":new Object(_NgetList("db",acPos[i],acLen[i])),
                        "prm_ExcludeUpDownVar":prm_ExcludeUpDownVar,
                        "prm_Gene":prm_Gene
                }
        }
        ));
    }
    $.when.apply($, jqXHRList).done(function () {
    	for (var i = 0; i < thread; i++) {
        	var result = arguments[i];
                results = result[0].replace(/(d\d+)/g,'$1dst');
                datas.push(results);
        }
        for (var i = 0; i < datas.length; i++) {
                if (i==0) {
                 	dstdata = datas[i];
                } else {
                        dstdata = dstdata+";"+datas[i];
                }
        }
        dst=dstdata.replace(/^\s+|\s+$/g, "");
	_setData(dst);
	storage.setItem("_exportFlg",1);
	_drawNULLBlock();
  	if ( Objects.Snpblock == "off" ) {
  	  if(Objects.Onebase == "off"){
  	    switch (Objects.Mode) {
        	case "dp":
        	  _drawDPBlock()
        	  $('#snpt').hide("slow");
        	  break;
      		case "dp+s":
        	  _drawDPBlock()
       		  x = (Objects.Zoom != "1b") ? _drawSNPBlock(1) : _drawSNPBlock(3);
        	  $('#snpt').show("slow");
        	  break;
        	case "dp+i":
        	  _drawDPBlock()
        	  x = (Objects.Zoom != "1b") ? _drawINDELBlock(1) : _drawINDELBlock(3);
        	  $("#snpt").show("slow");
        	  break;
        	case "dp+a":
        	  _drawDPBlock()
        	  x = (Objects.Zoom != "1b") ? _drawSNPBlock(2) : _drawSNPBlock(3);
        	  x = (Objects.Zoom != "1b") ? _drawINDELBlock(2) : _drawINDELBlock(3);
        	  $("#snpt").show("slow");
        	  break;
        	case "s":
        	  x = (Objects.Zoom != "1b") ? _drawSNPBlock(0) : _drawSNPBlock(3);
        	  $("#snpt").show("slow");
        	  break;
        	case "i":
        	  x = (Objects.Zoom != "1b") ? _drawINDELBlock(0) : _drawINDELBlock(3);
        	  $('#snpt').show("slow");
        	  break;
        	case "si":
        	  x = (Objects.Zoom != "1b") ? _drawSNPBlock(4) : _drawSNPBlock(3);
        	  x = (Objects.Zoom != "1b") ? _drawINDELBlock(4) : _drawINDELBlock(3);
        	  $("#snpt").show("slow");
        	  break;
      	    }	
    	  }else{
              if(/dp/.test(Objects.Mode)) _drawDPBlock();
              _drawGTVariant();
              if(Objects.Mode == 'dp') {
                  $('#snpt').hide("slow");
              } else {
                 $('#snpt').show("slow");
              }
          }	
        } else {
          if (Objects.Mode == "dp" || Objects.Mode == "dp+s" || Objects.Mode == "dp+i" || Objects.Mode == "dp+a") {
    		_drawDPBlock()
      		_drawSNPEstimationBlock();
      		x = (Objects.Zoom != "1b") ? _drawSNPBlock(1) : _drawSNPBlock(3);
      		$('#snpt').show("slow");
    	  } else{
      		_drawSNPEstimationBlock();
      		x = (Objects.Zoom != "1b") ? _drawSNPBlock(5) : _drawSNPBlock(3);
      		$("#snpt").show("slow");
    	  }
        }

	// Accession list
	_drawRegionHighlightCvs(cvs16);
  	pngContext.drawImage(cvs3, leftOffset, Objects.TrackH+Objects.NavH+gwasH+60);
  	pngContext.drawImage(cvs16, Objects.titleWidth + innerOffset, Objects.TrackH+Objects.NavH+gwasH+60);

	// SNP density top dividing lne
  	pngContext.beginPath();
  	pngContext.moveTo(leftOffset, pngCanvas.height-30);
  	pngContext.lineTo(pngCanvas.width,pngCanvas.height-30);
  	pngContext.strokeStyle="#c3c3c3";
  	pngContext.lineWidth="1";
  	pngContext.stroke();

	// SNP density
	_drawRegionHighlightCvs(cvs18);
  	pngContext.drawImage(cvs17, leftOffset, pngCanvas.height-30);
  	pngContext.drawImage(cvs18, Objects.titleWidth + innerOffset, pngCanvas.height-30);

	// Image output
  	img.src = pngCanvas.toDataURL(type);
  	var pop_win = window.open(
 	                "",
                  "_blank",
                  "width=500,height=500,scrollbars=yes,resizable=yes"
                );
  	pop_win.window.document.open();
  	pop_win.window.document.write(
    	'<html>'
    	+'<head><title>Exporting image</title></head>'
    	+'<body style="margin:0;padding:0;border:0;">'
    	+'<img src="'+img.src+'" width="100%" alt="" />'
    	+'</body>'
    	+'</html>'
  	);	
  	pop_win.window.document.close();
    });
    cvs14.width=1;
    cvs14.height=1;
    ctx14.clearRect(0, 0, cvs14.width, cvs14.height);
    ctx14.fillStyle='rgba(0,0,0,0)';
    ctx14.fillRect(0,0,cvs14.width,cvs14.height);
  }
}

window.requestAnimFrame = (function(callback) {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
  function(callback) {
    window.setTimeout(callback, 1000 / 60);
  };
})();

var myRectangle = {
    x: 0,
    value: true,
};

function _clearAnimate() {
  myRectangle.x=0;
  myRectangle.value=false;
}

function animate(lastTime, myRectangle) {
  if ( myRectangle.value == true ) {
    // update
    var time = (new Date()).getTime();
    var timeDiff = time - lastTime;
    // pixels / second
    var linearSpeed = 200;
    var linearDistEachFrame = linearSpeed * timeDiff / 1000;
    var currentX = myRectangle.x;
    if(currentX < cvs4.width) {
      var newX = currentX - linearDistEachFrame;
      myRectangle.x = newX;
    } else {
      _clearAnimate();
    }
    // clear
    ctx4.clearRect(0, 0, cvs4.width, cvs4.height);
    // draw
    ctx4.putImageData(frameCellwoI, currentX, 0);
    // request new frame
    requestAnimFrame(function() {
      animate(time, myRectangle);
    });
  }
}

/////////////////////////////////////////////// Draw message on canvas
function _drawMessageOnScreen(str,a,b) {
  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);
  var eleCont = document.getElementById("content");
  var fix = eleCont.scrollTop;
  ctx4.putImageData(frameCell, 0, 0);

  if ( str == "left" ) {
    ctx4.fillStyle="rgba(0,0,0,0.3)";
    ctx4.beginPath();
    ctx4.moveTo(0,((visible/8)*3)+fix);
    ctx4.lineTo(cvs4.width/10*9,((visible/8)*3)+fix);
    ctx4.lineTo(cvs4.width/10*9,((visible/8)*2)+fix);
    ctx4.lineTo(cvs4.width,((visible/8)*4)+fix);
    ctx4.lineTo(cvs4.width/10*9,((visible/8)*6)+fix);
    ctx4.lineTo(cvs4.width/10*9,((visible/8)*5)+fix);
    ctx4.lineTo(0,((visible/8)*5)+fix);
    ctx4.closePath();
    ctx4.fill();
    ctx4.strokeStyle="yellow";
    ctx4.lineWidth=5;
    ctx4.strokeRect(0,0,1,cvs4.height);
  } else if ( str == "right" ) {
    ctx4.fillStyle="rgba(0,0,0,0.3)";
    ctx4.beginPath();
    ctx4.moveTo(0,(visible/2)+fix);
    ctx4.lineTo(cvs4.width/10,((visible/8)*2)+fix);
    ctx4.lineTo(cvs4.width/10,((visible/8)*3)+fix);
    ctx4.lineTo(cvs4.width,((visible/8)*3)+fix);
    ctx4.lineTo(cvs4.width,((visible/8)*5)+fix);
    ctx4.lineTo(cvs4.width/10,((visible/8)*5)+fix);
    ctx4.lineTo(cvs4.width/10,((visible/8)*6)+fix);
    ctx4.closePath();
    ctx4.fill();
    ctx4.strokeStyle="yellow";
    ctx4.lineWidth=5;
    ctx4.strokeRect(cvs4.width-1,0,1,cvs4.height);
  } else if ( str == "zoomIn" ) {
    var za=parseInt(cvs4.width*_cvtZoom(_cvtZoomDown(Objects.Zoom))/_cvtZoom(Objects.Zoom));
    var zp=(cvs4.width/2)-(za/2);
    ctx4.fillStyle="rgba(0,0,0,0.3)";
    ctx4.fillRect(0,0,zp,cvs4.height);
    ctx4.fillRect(zp+za,0,cvs4.width,cvs4.height);
    ctx4.strokeStyle="yellow";
    ctx4.lineWidth=3;
    ctx4.strokeRect(zp,0,za,cvs4.height);
    ctx4.beginPath();
    ctx4.moveTo(0,(visible/2)+fix);
    ctx4.lineTo(zp/5,((visible/8)*2)+fix);
    ctx4.lineTo(zp/5,((visible/8)*3)+fix);
    ctx4.lineTo(zp,((visible/8)*3)+fix);
    ctx4.lineTo(zp,((visible/8)*5)+fix);
    ctx4.lineTo(zp/5,((visible/8)*5)+fix);
    ctx4.lineTo(zp/5,((visible/8)*6)+fix);
    ctx4.closePath();
    ctx4.fill();
    ctx4.beginPath();
    ctx4.moveTo(zp+za,((visible/8)*3)+fix);
    ctx4.lineTo(cvs4.width-(zp/5),((visible/8)*3)+fix);
    ctx4.lineTo(cvs4.width-(zp/5),((visible/8)*2)+fix);
    ctx4.lineTo(cvs4.width,((visible/8)*4)+fix);
    ctx4.lineTo(cvs4.width-(zp/5),((visible/8)*6)+fix);
    ctx4.lineTo(cvs4.width-(zp/5),((visible/8)*5)+fix);	
    ctx4.lineTo(zp+za,((visible/8)*5)+fix);
    ctx4.closePath();
    ctx4.fill();
  } else if ( str == "zoomInC" ) {
    var za=parseInt(cvs4.width*a/b);//(newbsize/currentbsize_wid)
    var zp=(cvs4.width/2)-(za/2);//(trimd region?)
    ctx4.fillStyle="rgba(0,0,0,0.3)";
    ctx4.fillRect(0,0,zp,cvs4.height);
    ctx4.fillRect(zp+za,0,cvs4.width,cvs4.height);
    ctx4.strokeStyle="yellow";
    ctx4.lineWidth=3;
    ctx4.strokeRect(zp,0,za,cvs4.height);
    ctx4.beginPath();
    ctx4.moveTo(0,(visible/2)+fix);
    ctx4.lineTo(zp/5,((visible/8)*2)+fix);
    ctx4.lineTo(zp/5,((visible/8)*3)+fix);
    ctx4.lineTo(zp,((visible/8)*3)+fix);
    ctx4.lineTo(zp,((visible/8)*5)+fix);
    ctx4.lineTo(zp/5,((visible/8)*5)+fix);
    ctx4.lineTo(zp/5,((visible/8)*6)+fix);
    ctx4.closePath();
    ctx4.fill();
    ctx4.beginPath();
    ctx4.moveTo(zp+za,((visible/8)*3)+fix);
    ctx4.lineTo(cvs4.width-(zp/5),((visible/8)*3)+fix);
    ctx4.lineTo(cvs4.width-(zp/5),((visible/8)*2)+fix);
    ctx4.lineTo(cvs4.width,((visible/8)*4)+fix);
    ctx4.lineTo(cvs4.width-(zp/5),((visible/8)*6)+fix);
    ctx4.lineTo(cvs4.width-(zp/5),((visible/8)*5)+fix);
    ctx4.lineTo(zp+za,((visible/8)*5)+fix);
    ctx4.closePath();
    ctx4.fill();
  } else if ( str == "zoomInPos" ) {
    var za=parseInt(cvs4.width*_cvtZoom(_cvtZoomDown(Objects.Zoom))/_cvtZoom(Objects.Zoom));
    var zp=cvs4.width*a/cvs4.width-(za/2);
    ctx4.fillStyle="rgba(0,0,0,0.3)";
    ctx4.fillRect(0,0,zp,cvs4.height);
    ctx4.fillRect(zp+za,0,cvs4.width,cvs4.height);
    ctx4.strokeStyle="yellow";
    ctx4.lineWidth=3;
    ctx4.strokeRect(zp,0,za,cvs4.height);
    ctx4.beginPath();
    ctx4.moveTo(0,(visible/2)+fix);
    ctx4.lineTo(zp/5,((visible/8)*2)+fix);
    ctx4.lineTo(zp/5,((visible/8)*3)+fix);
    ctx4.lineTo(zp,((visible/8)*3)+fix);
    ctx4.lineTo(zp,((visible/8)*5)+fix);
    ctx4.lineTo(zp/5,((visible/8)*5)+fix);
    ctx4.lineTo(zp/5,((visible/8)*6)+fix);
    ctx4.closePath();
    ctx4.fill();
    ctx4.beginPath();
    ctx4.moveTo(zp+za,((visible/8)*3)+fix);
    ctx4.lineTo(zp+za+(cvs4.width-zp-za)/5*4,((visible/8)*3)+fix);
    ctx4.lineTo(zp+za+(cvs4.width-zp-za)/5*4,((visible/8)*2)+fix);
    ctx4.lineTo(cvs4.width,((visible/8)*4)+fix);
    ctx4.lineTo(zp+za+(cvs4.width-zp-za)/5*4,((visible/8)*6)+fix);
    ctx4.lineTo(zp+za+(cvs4.width-zp-za)/5*4,((visible/8)*5)+fix);
    ctx4.lineTo(zp+za,((visible/8)*5)+fix);
    ctx4.closePath();
    ctx4.fill();
  }
}

function _getEmptyzoomFilterBoxPos() {
  return {'filter':{}, 'target':{}};
}
var zoomFilterBoxPos = _getEmptyzoomFilterBoxPos();
function _drawZoombar(){
  var htop = $("#top").height();
  $("#zoombar").css('top',htop+30);
  var InfoW = parseInt($("#showPos").width()) + parseInt(8);
  var abspos = parseInt(cvs2.width/2) + parseInt($(".title").width())+ parseInt(10);
  //alert(cvs2.width);
/*
  var titleW = storage.getItem("_TitleW");
  if(parseInt(titleW)+parseInt(o.width)+parseInt(20) > 660) {
  	$("#zoombar").css('left',abspos+'px');
  } else {
	$("#zoombar").css('left','660px');
  }
*/
  var chgchrFlg = storage.getItem("_chrFlg");
  if(chgchrFlg != '1') { //if change width, draw zoombar on half of track width
/*
  	if(o.width > parseInt(cvs2.width)/2 - 20 || abspos > 733) {
  	      $("#zoombar").css('left',abspos+'px');
  	} else {
  	      $("#zoombar").css('left','733px');
  	      //$("#zoombar").css('left','660px');
  	}
*/
	if (abspos > 660) {
		$("#zoombar").css('left',abspos+'px');
	} else {
		$("#zoombar").css('left','660px');
	}
  } else {
	storage.setItem('_chrFlg', '0');
  }

  var elem = document.getElementById('cvs_zbar');
  if (InfoW < 540) {
  	elem.setAttribute("width","540".toString());
  	ctx9.fillStyle="#302833";
  	ctx9.fillRect(0,0,"562",cvs9.height);
  } else {
  	elem.setAttribute("width",InfoW.toString());
	ctx9.fillStyle="#302833";
	ctx9.fillRect(0,0,InfoW,cvs9.height);
  }
/*
  ctx9.fillStyle="#302833";
  ctx9.fillRect(0,0,InfoW,cvs9.height);
*/
  ctx9.stroke();
  ctx9.fillStyle=_setColor().zoombar;
  ctx9.fillRect(384,13,6,18);
  ctx9.fillRect(378,19,18,6);
  ctx9.fillRect(413,19,18,6);
  ctx9.setTransform(1, 0, 0, 1, 0, 0);
  //ctx9.font="10px 'Courier'";
  ctx9.font="10px 'Helvetica'";
  frameZoomb=ctx9.getImageData(0, 0, cvs9.width, cvs9.height);

  var zoom = storage.getItem("_Zoom");
  var crtpos;
  var start=125;
  ctx9.fillStyle=_setColor().zoombar;
  //ctx9.font="14px 'Century'";
  ctx9.font="14px 'Helvetica'";
  ctx9.fillText("Block size :",9,26);
  ctx9.fillStyle="#ff9900";
  ctx9.fillText(zoom,84,26);
  ctx9.fillStyle=_setColor().zoombar;
  ctx9.fillRect(125,25,227,2);
  for(var i=1; i<=46; i++){
    if(i==1 || i==10 || i==19 || i==28 || i==37 || i==46){
      ctx9.fillRect((start+((i-1)*5)),15,2,10);
    } else if (i==5 || i==14 || i==23 || i==32 || i==41){
      ctx9.fillRect((start+((i-1)*5)),15,1,10);
    } else{
      ctx9.fillRect((start+((i-1)*5)),20,1,5);
    }
  }
  //125+368=493
  ctx9.font="10px 'Helvetica'";
  ctx9.fillText("1",123,37);
  ctx9.fillText("10",165,37);
  ctx9.fillText("100",208,37);
  ctx9.fillText("1k",255,37);
  ctx9.fillText("10k",297,37);
  ctx9.fillText("100k",339,37);
  ctx9.fillStyle='#ee7948';
  switch (zoom) {
    case "100k":
      crtpos = 349;
      break;
    case "90k":
      crtpos = 344;
      break;
    case "80k":
      crtpos = 339;
      break;
    case "70k":
      crtpos = 334;
      break;
    case "60k":
      crtpos = 329;
      break;
    case "50k":
      crtpos = 324;
      break;
    case "40k":
      crtpos = 319;
      break;
    case "30k":
      crtpos = 314;
      break;
    case "20k":
      crtpos = 309;
      break;
    case "10k":
      crtpos = 304;
      break;
    case "9k":
      crtpos = 299;
      break;
    case "8k":
      crtpos = 294;
      break;
    case "7k":
      crtpos = 289;
      break;
    case "6k":
      crtpos = 284;
      break;
    case "5k":
      crtpos = 279;
      break;
    case "4k":
      crtpos = 274;
      break;
    case "3k":
      crtpos = 269;
      break;
    case "2k":
      crtpos = 264;
      break;
    case "1k":
      crtpos = 259;
      break;
    case "900b":
      crtpos = 254;
      break;
    case "800b":
      crtpos = 249;
      break;
    case "700b":
      crtpos = 244;
      break;
    case "600b":
      crtpos = 239;
      break;
    case "500b":
      crtpos = 234;
      break;
    case "400b":
      crtpos = 229;
      break;
    case "300b":
      crtpos = 224;
      break;
    case "200b":
      crtpos = 219;
      break;
    case "100b":
      crtpos = 214;
      break;
    case "90b":
      crtpos = 209;
      break;
    case "80b":
      crtpos = 204;
      break;
    case "70b":
      crtpos = 199;
      break;
    case "60b":
      crtpos = 194;
      break;
    case "50b":
      crtpos = 189;
      break;
    case "40b":
      crtpos = 184;
      break;
    case "30b":
      crtpos = 179;
      break;
    case "20b":
      crtpos = 174;
      break;
    case "10b":
      crtpos = 169;
      break;
    case "9b":
      crtpos = 164;
      break;
    case "8b":
      crtpos = 159;
      break;
    case "7b":
      crtpos = 154;
      break;
    case "6b":
      crtpos = 149;
      break;
    case "5b":
      crtpos = 144;
      break;
    case "4b":
      crtpos = 139;
      break;
    case "3b":
      crtpos = 134;
      break;
    case "2b":
      crtpos = 129;
      break;
    case "1b":
      crtpos = 125;
      break;
  }
  ctx9.fillRect(crtpos,10,4,15);//Red line

  // Variant filter
  var VFtop = 16; 
  var VFwidth = 85;
  var VFiconHeight = 13;
  var VFleft = elem.clientWidth - VFwidth - 7;
  var VFclrBgOn = "#ff8844";	// #008844 -> #ff8844
  var VFclrFgOn = "#ffffaa";	// #ddff44 -> #ffffaa
  var VFclrBgOff = "#775533";	// #005500 -> #775533
  var VFclrFgOff = "#bbaa88";	// #00aa00 -> #bbaa99

  ctx9.fillStyle = _setColor().zoombar;
  ctx9.fillText("Variant filter state:", VFleft, 14, VFwidth);

  var snpEffFilterStr = "";
  var snpEffFilterBg = VFclrBgOff;
  var snpEffFilterFg = VFclrFgOff;
  if(isVariantFiltered()) {
    snpEffFilterStr += "Filtering";
    snpEffFilterBg = VFclrBgOn;
    snpEffFilterFg = VFclrFgOn;
  } else {
    snpEffFilterStr += "Default";
  }
  ctx9.fillStyle = snpEffFilterBg;
  ctx9.fillRect(VFleft, VFtop, VFwidth, VFiconHeight);
  ctx9.fillStyle = snpEffFilterFg;
  ctx9.fillText(snpEffFilterStr, VFleft + 2, VFtop + 10, VFwidth - 3);
  zoomFilterBoxPos['filter'] = {'l':VFleft, 't':VFtop, 'w':VFwidth, 'h':VFiconHeight};

  var highlightVariantGene = storage.getItem("_HighlightVariantGene");
  var highlightVariantStr = "";
  snpEffFilterBg = VFclrBgOff;
  snpEffFilterFg = VFclrFgOff;
  if(highlightVariantGene) {
    highlightVariantStr += highlightVariantGene;
    snpEffFilterBg = VFclrBgOn;
    snpEffFilterFg = VFclrFgOn;
  } else {
    highlightVariantStr += "No target";
  }
  ctx9.fillStyle = snpEffFilterBg;
  ctx9.fillRect(VFleft, VFtop + VFiconHeight + 2, VFwidth, VFiconHeight);
  ctx9.fillStyle = snpEffFilterFg;
  ctx9.fillText(highlightVariantStr, VFleft+2, VFtop + VFiconHeight + 12, VFwidth - 3);
  zoomFilterBoxPos['target'] = {'l':VFleft, 't':VFtop + VFiconHeight + 2, 'w':VFwidth, 'h':VFiconHeight};
}

function _drawManagerInd(a){
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  if(_isUndefined(a)){
    $("span[id=snp_max_ind]").css("color",en.snp_max_col);
    $("span[id=snp_min_ind]").css("color",en.snp_min_col);
    $("span[id=indel_max_ind]").css("color",en.indel_max_col);
    $("span[id=indel_min_ind]").css("color",en.indel_min_col);
    $("span[id=depth_max_ind]").css("color",en.depth_max_col);
    $("span[id=depth_min_ind]").css("color",en.depth_min_col);
    $("span[id=cstm_max_ind]").css("color",en.cstm_max_col);
    $("span[id=cstm_min_ind]").css("color",en.cstm_min_col);
  }else{
    $("span[id=snp_max_ind]").css("color",$("#manager_snp_max").val());
    $("span[id=snp_min_ind]").css("color",$("#manager_snp_min").val());
    $("span[id=indel_max_ind]").css("color",$("#manager_indel_max").val());
    $("span[id=indel_min_ind]").css("color",$("#manager_indel_min").val());
    $("span[id=depth_max_ind]").css("color",$("#manager_depth_max").val());
    $("span[id=depth_min_ind]").css("color",$("#manager_depth_min").val());
    $("span[id=cstm_max_ind]").css("color",$("#manager_cstm_max").val());
    $("span[id=cstm_min_ind]").css("color",$("#manager_cstm_min").val());
  }
  _changeColorGradient();
}

function _drawMulticondInd(a){
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  if(_isUndefined(a)){
    $("span[id=cstm_max_ind_para0]").css("color",en.cstm_max_col);
    $("span[id=cstm_min_ind_para0]").css("color",en.cstm_min_col);
    $("span[id=cstm_max_ind_para1]").css("color",en.cstm_max_col_para1);
    $("span[id=cstm_min_ind_para1]").css("color",en.cstm_min_col_para1);
    $("span[id=cstm_max_ind_para2]").css("color",en.cstm_max_col_para2);
    $("span[id=cstm_min_ind_para2]").css("color",en.cstm_min_col_para2);
    $("span[id=cstm_max_ind_para3]").css("color",en.cstm_max_col_para3);
    $("span[id=cstm_min_ind_para3]").css("color",en.cstm_min_col_para3);
  }else{
    $("span[id=cstm_max_ind_para0]").css("color",$("#manager_cstm_max_para0").val());
    $("span[id=cstm_min_ind_para0]").css("color",$("#manager_cstm_min_para0").val());
    $("span[id=cstm_max_ind_para1]").css("color",$("#manager_cstm_max_para1").val());
    $("span[id=cstm_min_ind_para1]").css("color",$("#manager_cstm_min_para1").val());
    $("span[id=cstm_max_ind_para2]").css("color",$("#manager_cstm_max_para2").val());
    $("span[id=cstm_min_ind_para2]").css("color",$("#manager_cstm_min_para2").val());
    $("span[id=cstm_max_ind_para3]").css("color",$("#manager_cstm_max_para3").val());
    $("span[id=cstm_min_ind_para3]").css("color",$("#manager_cstm_min_para3").val());
  }
  _changeCondColorGradient();
  _drawCondPreview();
}


function _drawCondPreview(){
  var cvs12 = $("#cvs_cond_preview")[0];
  var ctx12 = cvs12.getContext("2d");
  cvs12.width=200;
  cvs12.height=100;
  ctx12.fillStyle="#ffffff";
  ctx12.fillRect(0,0,cvs12.width,cvs12.height);
  ctx12.fillStyle="#000000";
  ctx12.strokeRect(0,0,cvs12.width,cvs12.height);
  ctx12.setTransform(1, 0, 0, 1, 0, 0);
  ctx12.font="10px 'Courier'";
  
  var en = new Object(JSON.parse(storage.getItem("_Env")));
  var condArray = storage.getItem("_CrtCondition").split("|");
  var cond = parseInt(condArray[0]);
  var dpmx = _getMaxGraDP();
  var cstm = storage.getItem('_CSTM');
  var offsetCSTM = en.cstm_min-1;
  
  var valid = 0;
  for(var a=0; a<condArray.length; a++){if(condArray[a]!=""){valid++;}}
  //20,10 60*80
  var CondBlockHeight = parseInt(80/valid);
  var drawn = 0;
  for(var b=0; b<condArray.length; b++){
    if(b==0){
      ctx12.fillStyle=en["cstm_max_col"];
    }else{
      ctx12.fillStyle=en["cstm_max_col_para"+b];
    }
    if(condArray[b] != ""){
      if(b > (valid-1)){
        h = 20+parseInt((valid-1)*CondBlockHeight)+((CondBlockHeight-14)/2);
        ctx12.fillRect(20,10+parseInt((valid-1)*CondBlockHeight),60,CondBlockHeight);
      }else{
        h = 20+parseInt(drawn*CondBlockHeight)+((CondBlockHeight-14)/2);
        ctx12.fillRect(20,10+parseInt(drawn*CondBlockHeight),60,CondBlockHeight);
      }
      ctx12.fillStyle="black";
      ctx12.font="14px 'Consolas'";
      ctx12.fillText(Objects.Conditions[condArray[b]].id.substr(0, 10), 100, h);
      drawn++;
    }
  }
}

/*
function _drawPhyloName() {
        var color = _setColor().tracktitle;
        var strname = storage.getItem("_Phenotype");
        var phenoname = "";
        if (strname.length > 23) {
                phenoname = strname.substring(0,23);
                phenoname += "..";
        } else {
                phenoname = strname;
        }
        ctx14.clearRect(0, 0, cvs14.width-20, cvs14.height);
        ctx14.fillStyle = _setColor().tracktitle;
        ctx14.beginPath();
        ctx14.font = "11px 'Helvetica'";
        ctx14.textAlign="right";
        ctx14.beginPath();
        ctx14.fillText(phenoname,cvs14.width-20, 14);
        var offgwas = $("#GWAS_plot").height() + $("#content").height();
        $("#content").css("height",offgwas);
}
*/

function _calcPlot() {
        $.ajax({
                url: "./bin/phenotype_prob.php",
                type: "GET",
                cache: false,
                data: {
                        "prm_Phenotype":storage.getItem("_Phenotype"),
                        "prm_Zoom":storage.getItem("_Zoom"),
                        "prm_Chr":storage.getItem("_Chr"),
                        "prm_Pos":storage.getItem("_Pos"),
                        "prm_Block":storage.getItem("_Block"),
                }
        }).done(function(data){
                if(data != null){
                        var o=new Object(JSON.parse(storage.getItem("_Phenotypes")));
                        for(var i=0;i<o.length;i++){
                                var phenotype_prob_name = o[i].phenotype.replace(/\s+/g, "_");
                                storage.removeItem("_Phenotype_Prob_" + phenotype_prob_name);
                        }
                        n = data.split(";");
                        for (var i = 0; i < n.length; i++) {
                                var a = n[i].split("|");
                                storage.setItem("_Phenotype_Prob_" + a[0], a[1]);
                                storage.setItem("_Min_Phenotype_Prob_" + a[0], a[2]);
                        }
                }
        })
}

function _drawPlot(pos) {
	var phenotype = storage.getItem("_Phenotype");
	var phenotype_prob_name = phenotype.replace(/\s+/g, "_");
	var min_phenotype_prob = storage.getItem("_Min_Phenotype_Prob_" + phenotype_prob_name);
	//var max_y_value = Math.ceil(-Math.LOG10E * Math.log(min_phenotype_prob));
	var max_y_value = Math.ceil(min_phenotype_prob);
	plotHeight = parseInt(cvs13.height);
	yWidth = parseInt(cvs13.width);
	ctx13.clearRect(0, 0, yWidth, plotHeight);
	//ctx13.fillStyle = _setColor().bgcolor;
	ctx13.fillStyle = "#dcdcdc";
	ctx13.fillRect(0, 0, yWidth, plotHeight);
	ctx19.fillStyle = "#dcdcdc";
        ctx19.fillRect(0, 0, yWidth, plotHeight);
	//max_y_value=parseInt("1");
	var yvalFlg;
	if (max_y_value > 4 && max_y_value < 12) {
		max_y_value = Math.ceil(max_y_value/2);
		yvalFlg = 1;
	} else if (max_y_value >= 12) {
		yvalFlg = Math.ceil(max_y_value/6);
		max_y_value = 6;
	}
/*
	if (max_y_value > 4 ) {
                max_y_value = Math.ceil(max_y_value/2);
                yvalFlg = 1;
	}
*/
	for(var i = 0; i <= max_y_value; i++){
		if (yvalFlg === 1) {
			ynum = i*2;
		} else if (yvalFlg > 1) {
			ynum = i*yvalFlg;
		} else {
			ynum = i;
		}
		ctx13.beginPath();
		var scale_y_value = plotHeight - ((plotHeight - 20) / max_y_value * i) -5;
	    	ctx13.moveTo(yWidth - 5, scale_y_value);
	    	ctx13.lineTo(yWidth , scale_y_value);
	    	ctx13.lineWidth = 0.2;
	    	ctx13.fillStyle = _setColor().tracktitle;
	    	ctx13.font = "12px 'Arial'";
	    	//ctx13.stroke();
		if (ynum < 10) {
	    		ctx13.fillText(ynum, yWidth - 12, scale_y_value);
		} else {
			ctx13.fillText(ynum, yWidth - 18, scale_y_value);
		}
	    	ctx13.fillText("-", yWidth-5, scale_y_value+3);
	}
	ctx13.fillStyle = _setColor().tracktitle;
	ctx13.font = "12px 'Helvetica'";
        ctx13.textAlign="right";
	titleW = storage.getItem("_TitleW");
	if (titleW > 140) {
		ctx13.fillText("GWAS manhattan plot",cvs13.width-40,10);
		var strname = storage.getItem("_Phenotype");
		var phenoname = "";
		if (strname.length > 19) {
			phenoname = strname.substring(0,19);
			phenoname += ".."; 
		} else {
			phenoname = strname;
		}
		ctx13.fillText(phenoname,cvs13.width-40, 25);
	} else if (titleW == 140) {
                ctx13.fillText("GWAS",cvs13.width-40,10);
                ctx13.fillText("manhattan plot",cvs13.width-40,25);
                var strname = storage.getItem("_Phenotype");
                var phenoname = "";
                if (strname.length > 16) {
                        phenoname = strname.substring(0,16);
                        phenoname += "..";
                } else {
                        phenoname = strname;
                }
                ctx13.fillText(phenoname,cvs13.width-40, 40);
        } else if (titleW == 120) {
                ctx13.fillText("GWAS",cvs13.width-40,10);
                ctx13.fillText("manhattan plot",cvs13.width-40,25);
                var strname = storage.getItem("_Phenotype");
                var phenoname = "";
                if (strname.length > 13) {
                        phenoname = strname.substring(0,12);
                        phenoname += "..";
                } else {
                        phenoname = strname;
                }
                ctx13.fillText(phenoname,cvs13.width-40, 40);
        } else if (titleW == 100) {
                ctx13.fillText("GWAS",cvs13.width-40,10);
                ctx13.fillText("manhattan",cvs13.width-40,25);
                ctx13.fillText("plot",cvs13.width-40,40);
                var strname = storage.getItem("_Phenotype");
                var phenoname = "";
                if (strname.length > 9) {
                        phenoname = strname.substring(0,9);
                        phenoname += "..";
                } else {
                        phenoname = strname;
                }
                ctx13.fillText(phenoname,cvs13.width-40, 55);
        }
	ctx13.rotate(-Math.PI / 2);
	ctx13.font = "12px 'Arial'";
	ctx13.fillText("-log", -(plotHeight / 2), yWidth - 25);
	//ctx13.fillText("-log", -(plotHeight / 2), yWidth - 45);
	var textWidth1 = ctx13.measureText("-log");
	ctx13.textBaseline = "middle";
	ctx13.fillText("10", -(plotHeight / 2 - textWidth1.width + 5), yWidth - 25);
	var textWidth2 = ctx13.measureText("10");
	ctx13.textBaseline = "alphabetic";
	ctx13.fillText("(P)", -(plotHeight / 2 - textWidth1.width - textWidth2.width), yWidth - 25);
	ctx13.rotate(Math.PI / 2);
	//ctx12.clearRect(0, 0, Objects.canvasWidth, plotHeight);
	ctx12.clearRect(0, 0, Objects.canvasWidth, plotHeight);
	//ctx12.clearRect(0, 0, 1035, plotHeight);
	//ctx12.fillStyle = "white";
	ctx12.fillStyle = "#F7F7F9";
	//ctx12.fillRect(0, 0, Objects.canvasWidth, plotHeight);
	//ctx12.fillRect(0, 0, 1035, 120);
	ctx12.fillRect(0, 0, Objects.canvasWidth, 80);
	var rowHeight = 40;
	if(storage.getItem("_TrackID") == "on"){
		rowHeight = 80;
	}

	//var o = new Object(JSON.parse(storage.getItem("_Phenotype_Prob_" + phenotype_prob_name)));
	//_calcPlot();
	var o = new Object(JSON.parse(storage.getItem("_Phenotype_Prob_" + phenotype_prob_name)));
	//ctx12.fillStyle = "black";
	for (var i = 0, oLen=o.length; i < oLen; i++){
		if ( pos === undefined) {
			ctx12.fillStyle = "gray";
		} else {
			if (o[i].pos === pos) {
				ctx12.fillStyle = "red";
			} else {
				ctx12.fillStyle = "gray";
			}
		}
		var b = parseInt((o[i].pos-Objects.Pos)/_cvtZoom(Objects.Zoom));
		var e=(b+Objects.Pos)*_cvtZoom(Objects.Zoom);
		var s=e-_cvtZoom(Objects.Zoom)+1;
		var ppos;
		if(_cvtZoom(Objects.Zoom)===1) {
			ppos=(b+0.5/_cvtZoom(Objects.Zoom))*10*storage.getItem("_BlockW")/10;
		} else {
			ppos=(b+(o[i].pos-s)/_cvtZoom(Objects.Zoom))*10*storage.getItem("_BlockW")/10;
		}
		if (yvalFlg === 1) {
			hpos = plotHeight - ((o[i].prob) * (plotHeight - 20) / max_y_value/2 + 10);
		} else if (yvalFlg > 1) {
			hpos = plotHeight - ((o[i].prob) * (plotHeight - 20) / max_y_value/yvalFlg + 10);
		} else {
			hpos = plotHeight - ((o[i].prob) * (plotHeight - 20) / max_y_value + 10);
		}
		ctx12.beginPath();
		//ctx12.arc(o[i].dot_pos * Objects.canvasWidth + 5 , plotHeight + Math.LOG10E * Math.log(o[i].prob) * (plotHeight - 10) / max_y_value + 15, Objects.BlockW / 4, 0, Math.PI * 2, false);
		ctx12.arc(ppos , hpos, Objects.BlockW / 4, 0, Math.PI * 2, false);
		ctx12.closePath();
		ctx12.fill();
	}
        _drawRegionHighlightCvs(cvs12);

  	// Capture tracks without rules
 	framePlot=ctx12.getImageData(0, 0, cvs12.width, cvs12.height);
 	framePlot1=ctx12.getImageData(0, 0, cvs12.width, cvs12.height);
	_drawRulesforPlot();
}

function _drawRulesforPlot() {
        var m = parseInt(Objects.Block / (40 / 4));
        for(var i = 0; i < m+1; i++){
            if (i==0 || i==m) {
                ctx12.beginPath();
                ctx12.moveTo(Objects.canvasWidth/ m * i, 0);
                ctx12.lineTo(Objects.canvasWidth/ m * i, 80);
                ctx12.lineWidth = 6;
                ctx12.strokeStyle = "rgba(" + [208,208,208,0.5] + ")";
                ctx12.stroke();
            } else {
                ctx12.beginPath();
                ctx12.moveTo(Objects.canvasWidth/ m * i, 0);
                ctx12.lineTo(Objects.canvasWidth/ m * i, 80);
                ctx12.lineWidth = 0.2;
                //ctx1.strokeStyle = "black";
                ctx12.strokeStyle = "rgba(" + [26,26,26,0.5] + ")";
                ctx12.stroke();
            }
	}
}


function _moveVarpos(variant) {
	var info = variant.split("|");
	var chr = info[0];
	var pos = info[1];
        storage.setItem('_Chr', chr);
	storage.setItem('_Zoom','10k');
	s_from = pos - 50*_cvtZoom(storage.getItem('_Zoom'));
        if(s_from < 1) s_from = 1;
	s_to = s_from + 100*_cvtZoom(storage.getItem('_Zoom')) - 1;
	var chrObj = _getChr(Objects.Chr);
	if(s_to > chrObj.size) s_to = chrObj.size;
	storage.setItem('_Tpos',pos);

//	_zoomFromGffWindow(chr+" "+s_from+"|"+s_from+"|"+s_to+"|"+chr);
	_execSearch(chr+" "+s_from+"|"+s_from+"|"+s_to+"|"+chr, false);
	_windowGffClose();

        $('#prm_position_chr').val(chr);
	setRegionHighlight({"chr":chr, "st":pos, "en":pos});
	_drawPlot(pos);
}
function _closeErr() {
	//$("#cvs_clserr").click(function() {
		cvs14.width=1;
		cvs14.height=1;
        	cvs15.width=1;
        	cvs15.height=1;
        	ctx14.clearRect(0, 0, cvs14.width, cvs14.height);
        	ctx14.fillStyle='rgba(0,0,0,0)';
        	ctx14.fillRect(0,0,cvs14.width,cvs14.height);
        	ctx15.clearRect(0, 0, cvs15.width, cvs15.height);
        	ctx15.fillStyle='rgba(0,0,0,0)';
        	ctx15.fillRect(0,0,cvs15.width,cvs15.height);
	//});
}
