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

//var storage = localStorage;

var cvs0;
var ctx0;
var cvs1;
var ctx1;
var cvs2;
var ctx2;
var cvs3;
var ctx3;
var cvs4;
var ctx4;
var cvs5;
var ctx5;
var cvs6;
var ctx6;
var cvs7;
var ctx7;
var cvs8;
var ctx8;
var cvs9;
var ctx9;
var cvs10;
var ctx10;
var cvs11;
var ctx11;
var cvs12;
var ctx12;
var cvs13;
var ctx13;
var cvs14;
var ctx14;
var cvs15;
var ctx15;
var cvs16;
var ctx16;
var cvs17;
var ctx17;
var cvs18;
var ctx18;
var cvs19;
var ctx19;

var frameCell;
var frameCellwoI;
var frameTitle;
var frameNav;
var frameChr;
var frameTrack;
var frameTrackwR;
var frameSNP;
var frameZoomb;
var framePlot;
var ONSEARCH = false;
var RELOAD = false;
var PROGRESSTIMER;
var BUSYDETECTTIMER;
var Objects=new Object();
var timerArray = new Array();
var drawBlastStr = '';
var drawlPrmStr = '';
var drawrPrmStr = '';
var drawTargetStr = '';
var primer3ArrayForBLASTRight='';
var primer3ArrayForBLASTLeft='';
var minPos = new Array();
//var winFront = new Array();
var maxDialogZindex = 1000;
var lastClickDialogName = '';

// use phenotype browser or not
var phenotypeStr = _getphenotypeFlg();
var phenotypeFlg = "";
if (phenotypeStr == "false") {
	phenotypeFlg = false;
} else if (phenotypeStr == "true") {
	phenotypeFlg = true;
}
//var phenotypeFlg = false;

var DEF_QUAL = 20;
var DEF_DP = 2;
var DEF_DP4 = 2;
var DAMMY_KEYWORD = 'the target';
var VERSION = '2.1.1';

// for Event Listener
var VIEWSTART=0;
var VIEWLEN=0;
var SCRTIMER;
var FROMSCROLL;

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

	cvs16 = document.getElementById("blkcvs");
  	ctx16 = cvs16.getContext('2d');
        cvs17 = document.getElementById("dentitlecvs");
        ctx17 = cvs17.getContext('2d');
        cvs18 = document.getElementById("dencvs");
        ctx18 = cvs18.getContext('2d');
        cvs19 = document.getElementById("phenotitlecvs");
        ctx19 = cvs19.getContext('2d');

        // Clear localStorage when url is sub directory on same domain
        var crntUrl = location.href.split("?");
        RELOAD = true;
        _showLoadingDialog();
        _showLoading();
        _initCache();
        _externalParser();

	initSelect2();	// for select2.js

        _execCanvas();
        RELOAD = false;
        // When first time
        if ( storage.getItem('_Count') == "1" ) {storage.setItem('_Count',"2");}
        $("#tasuke").css("background-color",_setColor().bgcolor);
	if(!phenotypeFlg) {
        	$("#GWAS_plot").css('display','none');
        	$("#show_phenotype").css('display','none');
        	$("#select_phenotype").css('display','none');
		$("#menu .GWAS").css('display','none');
		$("#menu .GWAS_dlg").css('display','none');
	} else if (phenotypeFlg) {
                $("#GWAS_plot").css('display','block');
                $("#show_phenotype").css('display','block');
                $("#select_phenotype").css('display','block');
                $("#menu .GWAS").css('display','block');
                $("#menu .GWAS_dlg").css('display','block');
	}

	// Check if using a serial table
	var en = new Object(JSON.parse(storage.getItem("_Env")));
	if(en.autoDetectSerialTable == 0 && isUsingSerialTable()) {
		alert("Message for web page administrator:\nSerial table is used because of the large number of reference seqs registered. Please change conf/config.php as follow:\n\$autoDetectSerialTable = 1;");
	}
}
function isUsingSerialTable() {
	var isUsing = false;
        $.ajax({
                url: "./bin/"+_backendSelector("isUsingSerialTable.php"),
                type: "POST",
                async:false,
                cache: false,
                success: function(data) {
                        if(data === "1") isUsing = true;
                }
        });
        return isUsing;
}
function initSelect2() {
        // init Select2
        // Add search form to Chr selection pull-down by select2 library
        $('.js-example-basic-single').select2({
//              matcher: function(params, data) {
//                      return matchStart(params, data);
//              },
                dropdownAutoWidth: true,
                width: 'auto'
        });
        // GWAS dialog: If you change chr pulldown, it will not be able to scroll dialog. So set it individually.
        $("#pheno_chr").select2({
                dropdownAutoWidth: true,
                width: 'auto',
                dropdownParent: $('#pheno_chr_parent')
        });
        $('#pheno_chr').on('select2:open', function (e) {
          const evt = "scroll.select2";
          $(e.target).parents().off(evt);
          $(window).off(evt);
        });

        // TSV export dialog: Since select2 of modal dialog cannot inputed in search form, set it individually.
        $("#prm_csv_chr").select2({
                dropdownAutoWidth: true,
                width: 'auto',
                dropdownParent: $('#prm_csv_chr_parent')
        });

	$("#prm_rp3_chr").select2({
		dropdownAutoWidth: true,
		width: 'auto',
		dropdownParent: $('#prm_rp3_chr_parent')
	});

	$("#prm_p3_chr").select2({
		dropdownAutoWidth: true,
		width: 'auto',
		dropdownParent: $('#prm_p3_chr_parent')
	});
}

///////////////////////////////////////////////////////////
//Initialize webStorage
///////////////////////////////////////////////////////////
function _initCache() {
        if(_isEmpty(storage.getItem("_Url"))){
                var crntUrl = location.href.split("?");
                storage.setItem("_Url",crntUrl[0].replace("index.html",""));
        }
        if(_isEmpty(storage.getItem("_Ref"))){
                storage.setItem("_Ref","Reference");
        }
        if(_isEmpty(storage.getItem("_Zoom"))){
                storage.setItem("_Zoom","1k");
        }
        if(_isEmpty(storage.getItem("_Pos"))){
                storage.setItem("_Pos","1");
        }
        if(_isEmpty(storage.getItem("_Mode"))){
                storage.setItem("_Mode","s");
                storage.setItem("_sFlg","1");
                storage.setItem("_iFlg","0");
                storage.setItem("_dpFlg","0");
        }
        if(_isEmpty(storage.getItem("_Eff"))){
                storage.setItem("_Eff","off");
        }
	if(phenotypeFlg) {
                storage.setItem("_GWAS","on");
	} 
        if(_isEmpty(storage.getItem("_Snpblock"))){
                storage.setItem("_Snpblock","off");
        }
        if(_isEmpty(storage.getItem("_QUAL"))){
		storage.setItem("_QUAL", String(DEF_QUAL));
//                storage.setItem("_QUAL","20");
        }
        if(_isEmpty(storage.getItem("_DP"))){
		storage.setItem("_DP", String(DEF_DP));
//                storage.setItem("_DP","2");
        }
        if(_isEmpty(storage.getItem("_DP4"))){
		storage.setItem("_DP4", DEF_DP4);
//                storage.setItem("_DP4","2");
        }
	if(_isEmpty(storage.getItem("_EffGrps"))){
		storage.setItem("_EffGrps", JSON.stringify(_getEffNoFilterArray()));	// Order does not make sense
	}
        if(_isEmpty(storage.getItem("_titleFlg")) && _isEmpty(storage.getItem("_Name")) && _isEmpty(storage.getItem("_NameSub"))){
                storage.setItem("_titleFlg","1");
        }
	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;
		if(Objects.Name != "") {
        		storage.setItem("_Name",title);
		} else {
			storage.setItem("_Name","id");
		}
                if(Objects.NameSub != "") {
                        storage.setItem("_NameSub",subtitle);
                } else {
                        storage.setItem("_NameSub","subvariety");
                }
        	//storage.setItem("_NameSub",subtitle);
        	storage.setItem("_titleFlg","0");
  	} 

        if(_isEmpty(storage.getItem("_BlockW"))){
                storage.setItem("_BlockW","10");
        }
        if(_isEmpty(storage.getItem("_BlockH"))){
                storage.setItem("_BlockH","12");
        }
        if(_isEmpty(storage.getItem("_Block"))){
                storage.setItem("_Block","100");
        }
        if(_isEmpty(storage.getItem("_Indicator"))){
                storage.setItem("_Indicator","on");
        }
        if(_isEmpty(storage.getItem("_Amino"))){
                storage.setItem("_Amino","on");
        }
        if(_isEmpty(storage.getItem("_DirRef"))){
                storage.setItem("_DirRef","+");
        }
        if(_isEmpty(storage.getItem("_Null"))){
                storage.setItem("_Null","true");
        }
        if(_isEmpty(storage.getItem("_Keyword"))){
                storage.setItem("_Keyword","");
        }
	if(_isEmpty(storage.getItem("_HighlightVariantGene"))){
		storage.setItem("_HighlightVariantGene","");
	}
	if(_isEmpty(storage.getItem("_HighlightVariantExclUpDown"))){
		storage.setItem("_HighlightVariantExclUpDown","");
	}
        if(_isEmpty(storage.getItem("_History"))){
                storage.setItem("_History","[]");
        }
        if(_isEmpty(storage.getItem("_Color"))){
                storage.setItem("_Color","0");
        }
        if(_isEmpty(storage.getItem("_Count"))){
                storage.setItem("_Count","1");
        }
        if(_isEmpty(storage.getItem("_ListsDeleted"))){
                storage.setItem("_ListsDeleted","[]");
        }
        if(_isEmpty(storage.getItem("_Env"))){
                _execEnv();
        }
/*
        if(_isEmpty(storage.getItem("_titleFlg"))){
                storage.setItem("_titleFlg","1");
        }
*/
        var en=new Object(JSON.parse(storage.getItem("_Env")));

        if(_isEmpty(storage.getItem("_TitleW"))) {
            storage.setItem("_TitleW", getTitleWidth()); 
/*
            if(!_isEmpty(en.accession_cvs_width)){
                storage.setItem("_TitleW", parseInt(en.accession_cvs_width));
            } else if(storage.getItem("_Name") == "id"){
                storage.setItem("_TitleW","180");
            } else if (storage.getItem("_Name") == "name"){
                storage.setItem("_TitleW","220");
            }
*/
        }
        var prewidth = 160;
        var width=storage.getItem("_TitleW");
        contentW = getContentWidth();
//        contentW = $("#content").width() + (width - prewidth);
        $("#track").css('width',contentW);
        $("#GWAS_plot").css('width',contentW);
        $("#content").css('width',contentW);
        $("#content2").css('width',contentW);
        titlew = parseInt(storage.getItem("_TitleW"))+parseInt(3);
        titlew2 = parseInt(storage.getItem("_TitleW"))+parseInt(1);
        $(".title").css('width',parseInt(titlew));
        $(".title2").css('width',parseInt(titlew));
        //$(".title2").css('width',parseInt(titlew2));

        if(_isEmpty(storage.getItem("_Update"))){
                var str = _checkUpdate();
                storage.setItem("_Update", str);
        }else{
                var str = _checkUpdate();
                if(storage.getItem("_Update")!=str){
                        _dlg_reset_confirm();
                }
        }
        if(_isEmpty(storage.getItem("_Lists"))){
                _execLists();
        }
        if(_isEmpty(storage.getItem("_CrtCondition"))){
                storage.setItem("_CrtCondition", "0|||");
        }
        if(_isEmpty(storage.getItem("_Chr"))){
                _execChr();
                storage.setItem("_Chr",_getChr().id);
        }
        if(_isEmpty(storage.getItem("_Onebase"))){
                storage.setItem("_Onebase", "off");
        }
        if(_isEmpty(storage.getItem("_CSTM"))){
                if(en.cstm_track=="enabled"){
                        storage.setItem("_CSTM", "off");
                }else{
                        storage.setItem("_CSTM", "disabled");
                }
        }
        if(_isEmpty(storage.getItem("_TrackID"))){
                storage.setItem("_TrackID","off");
        }
        if(_isEmpty(storage.getItem("_ColorCode")) || _isEmpty(storage.getItem("_GrpCol"))){
                storage.setItem("_ColorCode","off");
                _setTitleColor();
        }
        if(!_isEmpty(en.color_acc_group)){
                if(en.color_acc_group=="enabled"){
                        storage.setItem("_ColorCode", "on");
                }else{
                        storage.setItem("_ColorCode", "off");
                }
        }
/*
        if(_isEmpty(storage.getItem("_TitleW"))){
                if(_isEmpty(en.accession_cvs_width)){
                        storage.setItem("_TitleW", parseInt(160));
                }else{
                        storage.setItem("_TitleW", parseInt(en.accession_cvs_width));
                }
        }
*/
        if(_isEmpty(storage.getItem("_Conditions"))){
                storage.setItem("_Conditions", "[{\"\id\":\"\"}]");
        }
        if(phenotypeFlg && _isEmpty(storage.getItem("_Phenotype"))){
                _execPhenotype();
                var phenotype = _getPhenotype();
                storage.setItem("_Phenotype", phenotype);
                $("#plot_img").attr("src", "images/plot/plot_" + phenotype + ".png");
        }
	if(_isEmpty(storage.getItem("_Phenostr"))) {
		storage.setItem("_Phenostr","heading-date");
	}
        if(_isEmpty(storage.getItem("_blstHistFlg"))) {
                storage.setItem("_blstHistFlg",0);
        }
        if(_isEmpty(storage.getItem("_existDst"))) {
                storage.setItem("_existDst",0);
        }
        //storage.setItem("_exportFlg",0);

	// Enable the following to turn off highlights on reload
//	storage.setItem("_RegHighlights", "[]");
}

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

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

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

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

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

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

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

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

///////////////////////////////////////////////////////////
//Ajax: Search ID
//1K zoom will setted
///////////////////////////////////////////////////////////
function _execSearch(keyword, addOffset) {
	var target=keyword.split("|");
	var cnt=0;
	for(var i in target){cnt++;}
	if(cnt>4){
		var leftPos = target[1];
		var rightPos = target[2];
		if(addOffset) {
			var offset = parseInt((target[2] - target[1] + 1) * 0.05);
			leftPos = parseInt(target[1]) - offset;
			rightPos = parseInt(target[2]) + offset;
			if(leftPos<1) leftPos = 1;
		}
		_changeAutoPosZoom(target[3], leftPos, rightPos);
		storage.setItem("_Keyword", target[0]);
/*
		if(target[0] && target[0] != DAMMY_KEYWORD) {
			if($('#cb_highlight_keyword_variant').prop('checked')) {
				storage.setItem("_HighlightVariantGene", target[0]);
				if($('#cb_hlvar_kw_exclude_updown').prop('checked')) {
					storage.setItem("_HighlightVariantExclUpDown", "1");
				} else {
					storage.setItem("_HighlightVariantExclUpDown", "");
				}
			} else {
				storage.setItem("_HighlightVariantGene", "");
				storage.setItem("_HighlightVariantExclUpDown", "");
			}
		}
*/
		if (target[0] == "all") {
			target[0] = "Target region";
		}
		// ここで設定したハイライトは、このあとで_moveVarposを経由する場合(GWAS機能など)上書きされるので注意
		setRegionHighlight({"chr":target[3], "st":target[1], "en":target[2]});	// Region Highlight
//                addRegionHighlight({"chr":target[3], "st":target[1], "en":target[2]});	// Region Highlight

		_changeChromosomeSearch(target[0]);
	}
}
function _changeAutoPosZoom(chr, st, en) {
        var block = storage.getItem("_Block");

	var len = en - st + 1;
//	var blks = Math.round(len / block);	
//	if(blks<1) blks = 1;
	var blks = Math.ceil(len / block);	// Block bp len
	var blksL = String(blks).length - 1;	// 10^n
	var zoomsize = Math.ceil(blks/Math.pow(10,blksL)) * Math.pow(10,blksL);
//	var zoomsize = Math.round(blks/Math.pow(10,blksL)) * Math.pow(10,blksL);
	var optblks;
	if (zoomsize > 900) {
		optblks = Math.ceil(zoomsize/1000) + "k";
	} else {
		optblks = parseInt(zoomsize) + "b";
	}
	// Centering
	var dispLen = block * zoomsize;	// =bp len
	if(len < dispLen) {
		var stPos = st - parseInt((dispLen - len)/2);
		if(stPos<1) stPos = 1;
		p=_checkPos_Chr(stPos,optblks,chr);
	} else {
		p=_checkPos_Chr(st,optblks,chr);
	}
	storage.setItem("_Chr", chr);
	storage.setItem("_Zoom", optblks);
	storage.setItem("_Pos", p);
}

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

///////////////////////////////////////////////////////////
//Ajax: get environment settings
///////////////////////////////////////////////////////////
function _getphenotypeFlg() {
        var phenotypeFlg="";
        $.ajax({
                url: "./bin/"+_backendSelector("getPhenoFlg.php"),
                cache: false,
                async: false,
                success: function(data) {
                        phenotypeFlg=data;
                }
        });
        return phenotypeFlg;
}
/*
function _getNumThread() {
        var threadnum="";
        $.ajax({
                url: "./bin/"+_backendSelector("getNumThread.php"),
                cache: false,
                async: false,
                success: function(data) {
                        threadnum=data;
                }
        });
        return threadnum;
}
*/
function _getTitle() {
        var titleary=[];
        $.ajax({
                url: "./bin/"+_backendSelector("getTitle.php"),
                cache: false,
                async: false,
                success: function(data) {
                        titleary=data;
                }
        });
        return titleary;
}

function _getp3Path() {
        var primer3Path="";
        $.ajax({
                url: "./bin/"+_backendSelector("getp3Path.php"),
                cache: false,
                async: false,
                success: function(data) {
                        primer3Path=data;
                }
        });
        return primer3Path;
}
////replace LF and CR for Search
function _delLFCR(string){
	string = string.replace( /\r\n/g , "\n" );	
	string = string.replace( /^(\n+)|(\n+)$/g , "" );
	return string
}
function _getPhenolist() {
	$.ajax({
                url: "./bin/"+_backendSelector("getPhenolist.php"),
                cache: false,
                async: false,
                success: function(data) {
                        storage.setItem("_Phenolist", data);
		}
	});
}
function _getPheno($phenoname) {
        $.ajax({
                url: "./bin/"+_backendSelector("getPheno.php"),
                cache: false,
		type:'POST',
                async: false,
		data: {
			"phenoname":$phenoname
		},
                success: function(data) {
                        storage.setItem("_Phenoexp", data);
                }
        });
}
///////////////////////////////////////////////////////////
//Ajax: Get track&depth&variant and drawing
///////////////////////////////////////////////////////////
function _execCanvas(p,b,s) {
	var thread = JSON.parse(storage.getItem('_Env')).threadnum;	// 0origin, so the actual number is thread+1(track(=1) + datas)
        if(!thread) thread = 4;
	var acLen = new Array();
	var acPos = new Array();
	var isScroll=false;
	var countaAc = 0;
	var mod = 0;
	var invisDatas="";
	acLen[0]=0;
	acPos[0]=1;
	if(SCRTIMER && FROMSCROLL){
		isScroll=true;
		clearTimeout(SCRTIMER);
	}
	FROMSCROLL=false;

	// Depth&Variants
	if (_isEmpty(p)) {
		p=storage.getItem("_Pos"); 
		b=storage.getItem("_Block"); 
	}
	baseobj=new Object(_getList("db"));

	var trc = new Object(JSON.parse(storage.getItem("_Tracks")));
	var blksH = storage.getItem("_BlockH");
	var cvsTrackH = (57+((4*blksH)*trc.length));
	if(cvsTrackH <= 57){cvsTrackH=78;}

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

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

	if(upperArray.length!=0 || lowerArray.length!=0){invisDatas = ";";}
	for(var i=0, upperArrayLen=upperArray.length; i<upperArrayLen; i++){
		var num=0;
		if(_getCompressedData(upperArray[i]).indexOf("{\"dp\":\"x\"}") == -1 && isScroll){
			//pass
		}else{
			invisDatas += upperArray[i]+"|["+times("{\"dp\":\"x\",\"rdp\":\"x\"},",b).slice(0,-1)+"];";
		}
	}
	if(lowerArray.length==0){invisDatas=invisDatas.slice(0,-1);}
	for(var i=0, lowerArrayLen=lowerArray.length; i<lowerArrayLen; i++){
		var num=0;
		if(_getCompressedData(lowerArray[i]).indexOf("{\"dp\":\"x\"}")  == -1 && isScroll){
		}else{
			invisDatas += lowerArray[i]+"|["+times("{\"dp\":\"x\",\"rdp\":\"x\"},",b).slice(0,-1)+"];";
		}
	}
	if(lowerArray.length!=0){invisDatas=invisDatas.slice(0,-1);}
	isScroll=false;
	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){
		var jqXHRList = [];
		_drawProgress(100,1);
		jqXHRList.push($.ajax({
			url: "./bin/"+_backendSelector("track.php"),
			type: "POST",
			cache: false,
			data: {
				"prm_Zoom":storage.getItem("_Zoom"),
				"prm_Chr":storage.getItem("_Chr"),
				"prm_Pos":storage.getItem("_Pos"),
				"prm_Block":storage.getItem("_Block"),
				"prm_Tracks":new Object(_getTrack("list"))
			}
		}
		));
		for (var i = 1; i <= thread; i++) {
			jqXHRList.push($.ajax({ 
				url: "./bin/"+_backendSelector("data.php"),
				type: "POST",
				cache: false,
				data: {
					"prm_Ref":storage.getItem("_Ref"),
					"prm_width":storage.getItem("_BlockW"),
					"prm_Zoom":storage.getItem("_Zoom"),
					"prm_Chr":storage.getItem("_Chr"),
					"prm_Pos":p,
					"prm_QUAL":storage.getItem("_QUAL"),
					"prm_DP":storage.getItem("_DP"),
					"prm_DP4":storage.getItem("_DP4"),
					"prm_EffGrps":storage.getItem("_EffGrps"),
					"prm_Block":b,
					"prm_Lists":new Object(_NgetList("db",acPos[i],acLen[i])),
					"prm_ExcludeUpDownVar":prm_ExcludeUpDownVar,
					"prm_Gene":prm_Gene,
				}
			}
			));
		}
		$.when.apply($, jqXHRList).done(function () {
			var datas = [];
			var statuses = [];
			var jqXHRResultList = [];
			var trdatas = [];
			var trstatuses = [];
			var trjqXHRResultList = [];
			var trresult = arguments[0];
			trdatas.push(trresult[0]);
			trstatuses.push(trresult[1]);
			trjqXHRResultList.push(trresult[3]);
			var n=trdatas[0].split("|");
			var dvdata="";
			for (var i=0, trackLen=_getTrack("list").length; i<trackLen; i++){
				n[i] = n[i].replace(/---/g,"\|");
				storage.setItem("_Track_"+i, n[i]);
			}
			if ( storage.getItem("_Zoom") == '1b' ) {
				storage.setItem("_FASTA", n[n.length-1]);
			}
			for (var i = 1; i<=thread; i++) {
				var result = arguments[i];
				datas.push(result[0]);
				statuses.push(result[1]);
				jqXHRResultList.push(result[3]);
			}
			for (var i = 0, argsLen=arguments.length; i < argsLen-1; i++) {
				if(i==0){
					dvdata=datas[i];
				}else{
					dvdata=dvdata+";"+datas[i];
				}
			}
			dvdata = dvdata + invisDatas;
//			dvdata += invisDatas;

			for(var x=0; x<timerArray.length; x++){	clearInterval(timerArray.shift());} // animation
			var d=dvdata.replace(/^\s+|\s+$/g, "");
			if (_isEmpty(s)) {
				_setData(d);
			} else {
				_setData_p(d,s,b);
			}
                        if(phenotypeFlg){
                        	$.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, oLen=o.length; i<oLen; i++){
//                                                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, nLen=n.length; i < nLen; i++) {
//                                                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]);
                                                }
                                        }
                                        _drawCanvas();
                                        DATAPFLAG=false;
                                        storage.setItem("_ListsTgt","");
                                        clearTimeout(PROGRESSTIMER);
                                        setTimeout("_drawProgress('100')",100);
                                        setTimeout(_closeLoadingDialog,500);
                                });
                        } else {
                        	_drawCanvas();
                                DATAPFLAG=false;
                                storage.setItem("_ListsTgt","");
                                clearTimeout(PROGRESSTIMER);
                                setTimeout("_drawProgress('100')",100);
                                setTimeout(_closeLoadingDialog,500);
                        }
//jqXHRList.push($.ajax({
//	url: "./bin/"+_backendSelector("test.php"),
//	type: "POST",
//	cache: false
//}));
		});
	}else{
		_drawProgress(100,1);
		$.ajax({
			url: "./bin/"+_backendSelector("track.php"),
			type: "POST",
			cache: false,
			async: false,
			data: {
				"prm_Zoom":storage.getItem("_Zoom"),
				"prm_Chr":storage.getItem("_Chr"),
				"prm_Pos":storage.getItem("_Pos"),
				"prm_Block":storage.getItem("_Block"),
				"prm_Tracks":new Object(_getTrack("list"))
			},
			success: function(datas) {
				var n=datas.split("|");
				for (var i=0, trackLen=_getTrack("list").length; i<trackLen; i++){
//				for (i=0; i<_getTrack("list").length;i++){
					n[i] = n[i].replace(/---/g,"\|");
					storage.setItem("_Track_"+i, n[i]);
				}
				if ( storage.getItem("_Zoom") == '1b' ) {
					storage.setItem("_FASTA", n[n.length-1]);
				}
			}
		});
		if(phenotypeFlg){
			$.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"),
				},
				success: function(datas) {
					var n = datas.split(";");
					for (var i = 0, nLen=n.length; i < nLen; i++) {
//					for (var i = 0; i < n.length; i++) {
						var a = n[i].split("|");
						storage.setItem("_Phenotype_Prob_" + a[0], a[1]);
					}
				}
			});
		}
		$.ajax({
			url: "./bin/"+_backendSelector("data.php"),
			type: "POST",
			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":p,
				"prm_QUAL":storage.getItem("_QUAL"),
				"prm_DP":storage.getItem("_DP"),
				"prm_DP4":storage.getItem("_DP4"),
				"prm_Block":b,
				"prm_Lists":new Object(_getList("db")),
				"prm_Gene":prm_Gene
			},
			success: function(datas) {
				var d=datas.replace(/^\s+|\s+$/g, "");
				if (_isEmpty(s)) {
					_setData(d);
				} else {
					_setData_p(d,s,b);
				}
				for(var x=0; x<timerArray.length; x++){	clearInterval(timerArray.shift());} // animation
                                _drawCanvas();
				DATAPFLAG=false;
				storage.setItem("_ListsTgt","");
				clearTimeout(PROGRESSTIMER);
				setTimeout("_drawProgress('100')",100);
				setTimeout(_closeLoadingDialog,500);
			}
		});
	}
	clearTimeout(BUSYDETECTTIMER);
}

/////////////////////////////////////////////// Output messages and reload Canvas
function _reloadCanvas(msg) {
	_showLoading();
	_messageOnScreen(msg);
	FROMSCROLL=false;
	_execCanvas();
}

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

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

function _sessionBlastStart(){
        var runBlastRes = document.getElementById("result");
        var runBlastHist = document.getElementById("run_blast_hist");
	if(storage.getItem("_blastTable") !== undefined) {
        	runBlastHist.innerHTML=storage.getItem("_blastTable");
	}
        runBlastRes.innerHTML="";
}

///////////////////////////////////////////////////////////
//Exporting/importing Accession list
///////////////////////////////////////////////////////////
function _downloadAccList(){
	var l = new Object(JSON.parse(storage.getItem('_Lists')));
	var str = "";
	var Time = new Date();
	var timePrint = Time.getFullYear()+"_"+(Time.getMonth()+1)+"_"+Time.getDate();
	var fileName="AccessionList_"+timePrint+".txt";

	for (var i=0;i<l.length;i++){
		if ( Objects.Name == "id" ) {
			str += l[i].id;
		} else {
			str += l[i].name;
		}
		if(i != (l.length-1)){str += "\n";}
	}
	_download(str,fileName);
}

var extAccList = new Array();
function _validateAccList(files){
	var elm = document.getElementById("list_upfile_msg");
	var lists = new Object(JSON.parse(storage.getItem('_Lists-origin')));
	var limit = 10000000;
	var accArray = new Array();
	var reader = new FileReader();
	document.getElementById("prm_list_up").disabled = true;

	if(!_isUndefined(files[0])){
		if(files[0].type != "text/plain"){
			elm.innerHTML="<font color='red'>Invalid file</font>"
				files[0].value = '';
			return;
		}
		if(files[0].size > limit){
			elm.innerHTML="<font color='red'>Too large!</font>"
				files[0].value = '';
			return;
		}

		reader.readAsText(files[0],"utf-8");
		reader.onload = function(ev){
			var accKeys = new Array();
			var validated = new Array();
                        var reg = /\r\n/;
                        if (reg.test(reader.result)) {
                                accArray = reader.result.split("\r\n");
                        } else {
                                accArray = reader.result.split("\n");
                        }
			//accArray = reader.result.split("\n");
			for (var i=0;i<lists.length;i++){
				if ( Objects.Name == "id" ) {
					accKeys[lists[i].id]=1;
				} else {
					accKeys[lists[i].name]=1;
				}
			}
			for (var a=0;a<accArray.length;a++){
				if (accArray[a] in accKeys) {
					validated.push(accArray[a]);
				}
			}
			extAccList = validated;
			document.getElementById("prm_list_up").disabled = false;
		}
	}
}

function _uploadAccList(){
	var elm = document.getElementById("list_upfile_msg");
	var lists = new Object(JSON.parse(storage.getItem('_Lists-origin')));
	var ret = "[";
	var deleted = "[";
	var numdel = 0;
	var keys = new Array();

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

///////////////////////////////////////////////////////////
//Phylogenetic tree
///////////////////////////////////////////////////////////
function _runPhylogen(){
	var idlstDoc = document.getElementById("idlst");
	var qrylst = "";
	for (var i=0;i<idlstDoc.length;i++) {
		var select = idlstDoc[i].value;
		var selectarr = select.split("|");
		qrylst += selectarr[0];
		if(i<idlstDoc.length-1) {
			qrylst += ","
		}
	}
	var chr = document.getElementById("prm_phy_chr");
	var st = document.getElementById("prm_phy_s");
	var ed = document.getElementById("prm_phy_e");
	var numthread = JSON.parse(storage.getItem('_Env')).threadnum;
//	var numthread = _getNumThread();
	var ajaxloader = document.getElementById("phy_ajaxloader");
	var res = document.getElementById("phy_result");
	//var id = document.getElementById("prm_phy_objid").value;
	var name=storage.getItem("_Name");

	///check whether ID exists///
	var isExistID = 1;
	var idnum = "";
	var idflag = 1;
	if(document.getElementById("prm_phy_cri").value == 1) {
		var id = document.getElementById("prm_phy_objid").value;
		if(/\;|\||\&|\`|\(|\)|\<|\>|\*|\?|\{|\}|\[|\]|\!/.test(id)){
			var elem = document.getElementById("phy_result");
                        elem.innerHTML = "<font style=\"font-size:18px;color:red;\">Error : Invalid value in ID!</font>";
		} else {
			result = _checkID(id);
			if(result == "Error") {
				idflag = 0;
			}
		}
	}
	if(idflag == 0) {
	    var elem = document.getElementById("phy_result");
            elem.innerHTML = "<font style=\"font-size:18px;color:red;\">Error : Invalid value in ID!</font>";
	} else {
		var cds = 0;
		if(document.getElementById("prm_phy_gene").checked){cds = document.getElementById("prm_phy_gene").value;}
		ajaxloader.innerHTML="<img src=\"./images/loader.gif\" alt=\"Running...\" style=\"\" />Running...";
		res.innerHTML="";
		$.ajax({
			url: "./bin/"+_backendSelector("dnadist.php"),
			type: "POST",
			cache: false,
				data: {
				"qry_list":qrylst,
				"prm_phy_chr":document.getElementById("prm_phy_chr").value,
				"prm_phy_s":document.getElementById("prm_phy_s").value,
				"prm_phy_e":document.getElementById("prm_phy_e").value,
				"prm_phy_qual":document.getElementById("prm_phy_qual").value,
				"prm_phy_dp":document.getElementById("prm_phy_dp").value,
				"prm_phy_list":document.getElementById("prm_phy_list").value,
				"prm_phy_cri":document.getElementById("prm_phy_cri").value,
				"prm_phy_gene":cds,
				"prm_phy_name":name,
				"prm_numthread":numthread,
				"prm_phy_objid":document.getElementById("prm_phy_objid").value,
				"prm_phy_grp":Objects.NameSub,
				//"option":option
			},	
			success: function(data) {
				ajaxloader.innerHTML = "";
				if(/Error/.test(data)) {
					var elem = document.getElementById("phy_result");
                	               	elem.innerHTML = "<font style=\"font-size:18px;color:red;\">"+data+"</font>";
				} else {
					data = data.replace(/REF/,"Reference");
					var datas = data.split("|");
					if(datas[3]){
						res.innerHTML = _escapeHTML(datas[3]);
						return;
					}
					var Time = new Date();
					var timePrint = Time.getFullYear()+"_"+(Time.getMonth()+1)+"_"+Time.getDate();
					var fileName=_escapeHTML(chr.value)+"_"+st.value+"b-"+ed.value+"b_"+timePrint;
					var pop_win = window.open(
                        				"",
                  				  "_blank",
                  				  "width=600,height=600,scrollbars=yes,resizable=yes"
                				);
					var results = _genPhyResult(data,fileName);
                                        var retString = results.retString;
                                        var phyResult = results.phyResult;
					//var retString,phyResult = _genPhyResult(data,fileName);
					//res.innerHTML = _genPhyResult(data,fileName);
					res.innerHTML = phyResult;
					//showtree('newick','phy_svg');
					pop_win.window.document.open();
					pop_win.window.document.write(
						'<html>'
						+'<head><title>Exporting Phylogenetic Tree</title></head>'
						+'<script src="./js/jquery-2.1.4.min.js" type="text/javascript"></script>'
    						+'<script src="./js/jquery-ui-1.10.4.min.js" type="text/javascript"></script>'
    						+'<script src="./js/format4js.js" type="text/javascript"></script>'
    						+'<script src="./lib/treelib/treelib.js" type="text/javascript"></script>'
    						+'<script src="./lib/SVGPan2/SVGPan.js"></script>'
    						+'<script src="./js/tools.js" type="text/javascript"></script>'
    						+'<script src="./js/init.js" type="text/javascript"></script><script src="./js/dialog.js" type="text/javascript"></script><script src="./js/draw.js" type="text/javascript"></script><script src="./js/event.js" type="text/javascript"></script><script src="./js/jquery.ui.touch-punch.min.js" type="text/javascript"></script>'
						//+'<body onload="showtree(\'newick\',\'phy_svg\');">'
						+'<body onload="showtree(\'newick\',\'phy_svg\');">'
						+ $("#phy_result").html()
						+ '<input id="newick" name="newick" value="'+$("#newick").val()+'" type="hidden">'
						+ '<input id="fasta" name="filename" value="'+$("#fasta").val()+'" type="hidden">'
						+ '<input id="nname" name="nname" value="'+$("#nname").val()+'" type="hidden">'
						+ '<input id="fname" name="fname" value="'+$("#fname").val()+'" type="hidden">'
						+ '<input id="filename" name="filename" value="'+fileName+'" type="hidden">'
						+'</body>'
						+'</html>'
					);
					pop_win.window.document.close();
					res.innerHTML = retString;
				}
			},	
			error: function(XMLHttpRequest, textStatus, errorThrown) {
			ajaxloader.innerHTML = XMLHttpRequest.status+" Error";
			}
		});
	}
}

function _checkID(id) {
	$.ajax({
        	url: "./bin/"+_backendSelector("isExistID.php"),
                type: "POST",
		async: false,
                cache: false,
                data: {
                	"id":id,
                },
                success: function(data) {
			if(data == 0) {
				result = "Error";
			} else {
				result = "";
			}
        	}
       	});
	return result;
}
var DLDATA = "";
var DLNAME = "";
function _genPhyResult(data,fileName){
	var retString = "";
	var phyResult = "";
	var selectbox = "";
	var name = storage.getItem("_Name");
	var ret = data.split("|");	// [0]:Acc List(order by tree) [1]:Newick [2]:Fasta [3]:
	var accessions = ret[0].split(",");
	accessions.reverse();
	DLDATA = ret[1];
		DLDATA = DLDATA.replace(/\(([^:\(\)]*)\)/g, '$1');	// Excludes parentheses in the ACC name because it conflicts with the Newick format.
	DLFASTA = ret[2];
	DLNAME = fileName + ".nwk";
	DLFNAME = fileName + ".fasta";
	//boxH = 8 * accessions.length +100;
	boxH = 10 * accessions.length +100;
	for(var i=0; i<accessions.length; i++){
		var idname = accessions[i].split(":");
		var acc_name = idname[0];
		var acc_id = idname[1];
		if(name == "name") {
			selectbox += "<option value="+acc_id+">"+acc_name+"</option>";
		} else if (name == "id") {
			selectbox += "<option value="+acc_id+">"+acc_id+"</option>";
		}
	}
	retString +=  "<hr>"+
	"<div height='100%' width='100%' style='text-align:left;'>"+
	"<font color='#008000'>The analysis has been finished!</font>"+
	"<table><tr>"+
	"<td width='25%' align='left' style='padding-right:20px;'>"+
	"Sorting accessions in main panel by the order of the reconstructed phylogeny."+
	"<div style=\"display:none\">"+
        "<select size='15' id='phy_acc_order' style='width:100%;font-family:Courier;'>"+
        selectbox+
        "</select>"+
	"</div>"+
	"</td></tr>"+
	"<tr><td>"+
	"<button id='phy_sorted' type='submit' onclick='_sortAccByPhylip();'>Apply now</>"+
	"</td></tr></table>";
	phyResult = "<table width='100%'>"+
	"<tr>"+
	"<td width='75%'>"+
	"Style of phyrogram&nbsp"+
	"<select id='style'>"+
	"<option value='phylogram' selected='true'>Rectangular</option>"+
	"<option value='circlephylogram'>Circular</option>"+
	"<option value='cladogram'>Linear</option>"+
	"</select>"+
	"<button onclick=\"showtree('newick','phy_svg')\">Show</button>"+
	"</td>"+
        "</tr>"+
        "<tr>"+
        "<td>"+
        "Downloads:&nbsp;Phylogeny&nbsp;"+
        //"<button type='submit' onClick='_indirDownload(DLDATA,DLNAME);'>newick</>"+
        "<button type='submit' onClick='_dlNewick();'>newick</>"+
        //"<button type='submit' onClick='_indirDownload(DLFASTA,DLFNAME);'>fasta</button>"+
        "<button type='submit' onClick='_dlPic();'>png</button>"+
        "<button type='submit' onClick='_dlSVG();'>SVG</button>"+
        "&nbsp;&nbsp;&nbsp;Sequences&nbsp;"+
        //"<button type='submit' onClick='_indirDownload(DLFASTA,DLFNAME);'>fasta</button>"+
        "<button type='submit' onClick='_dlFasta();'>fasta</button>"+
	"<div id='phy_tree_res' style='height:525;background-color:white; border:1px solid #cccccc;'>"+
	"<svg id='phy_svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' version='1.1' height='525' width='525'>"+
	"<script src='./lib/SVGPan2/SVGPan.js' type='text/javascript'></script>"+
	"<g id='viewport' transform='translate(200,200)'></g>"+
	"</svg>"+
	"</div>"+
        "</td>"+
        "</tr>"+
        "</table>";

	$("#newick").val(DLDATA);
	$("#fasta").val(DLFASTA);
	$("#nname").val(DLNAME);
	$("#fname").val(DLFNAME);

	var returns = new Object();
	returns.retString = retString;
	returns.phyResult = phyResult;

	//return retString,phyResult;
	return returns;
}

function _dlPic() {
	/*var filenames = DLNAME.split('.');
	var ext = filenames.pop();
	var picname = filenames.pop();*/
	var picname = $("#filename").val();
	var width = $("#phy_svg").width();
	var height = $("#phy_svg").height();
	$("body").append("<canvas id='canvas1' class='hidden' width="
                                  + width + " height=" + height +"></canvas>");
	var canvas = $("#canvas1")[0];
	var ctx = canvas.getContext("2d");

	var svg = $("#phy_svg");
	svg.attr("viewBox", "0 0 " + width + " " + height);
	var svgData = new XMLSerializer().serializeToString(svg[0]);
	svg2base64 = btoa(unescape(encodeURIComponent(svgData)));
	var imgsrc = "data:image/svg+xml;charset=utf-8;base64,"+svg2base64;
	var image = new Image();
        image.onload = function(){
            ctx.drawImage( image, 0, 0 );
	    if (window.navigator.msSaveBlob) {
		var dataurl = canvas.toDataURL("image/png");
		var bin = atob(dataurl.split(',')[1]);
		var buffer = new Uint8Array(bin.length);
		for (var i = 0; i < bin.length; i++) {
 		    buffer[i] = bin.charCodeAt(i);
		}
		var blob = new Blob([buffer.buffer], {type:"image/png"});
		window.navigator.msSaveBlob(blob, picname+".png");
		window.navigator.msSaveOrOpenBlob(blob, picname+".png");
		$("#canvas1").remove();
	    } else {
    	    	$("body").append("<a id='image-file' type='application/octet-stream' href='"
            	+ canvas.toDataURL("image/png") + "' download=\'"+picname+".png'></a>");
    	    	$("#image-file")[0].click();
    	    	$("#canvas1").remove();
    	    	$("#image-file").remove();
	    }
	}
	image.src = imgsrc;
}

function _dlSVG() {
	/*
        var filenames = DLNAME.split('.');
        var ext = filenames.pop();
        var picname = filenames.pop();
	*/
	var picname = $("#filename").val();
        var width = $("#phy_svg").width();
        var height = $("#phy_svg").height();

        var svg = $("#phy_svg");
        svg.attr("viewBox", "0 0 " + width + " " + height);
        var svgData = new XMLSerializer().serializeToString(svg[0]);
	var blob = new Blob([svgData], {"type":"image/svg+xml"});
	if (window.navigator.msSaveBlob) { 
        	window.navigator.msSaveBlob(blob, picname+".svg"); 
	 	// msSaveOrOpenBlobの場合はファイルを保存せずに開ける
                window.navigator.msSaveOrOpenBlob(blob, picname+".svg"); 
        } else {
	    var append_word = "<a id=\"download\" href=\"#\" download=\""+picname+".svg\">ダウンロード</a>";
            $("body").append(append_word);
	    document.getElementById("download").href = window.URL.createObjectURL(blob);
            $("#download")[0].click();
            $("#download").remove();
	}
}

function _sortAccByPhylip(){
	// all Accs Map
	var name = storage.getItem("_Name");
	var acc = new Array();
	var o = new Object(JSON.parse(storage.getItem("_Lists")));
	for(var i=0;i<o.length;i++){
		//if(name == "name") {
		//	acc[o[i].name] = o[i];
		//} else {
			acc[o[i].id] = o[i];
		//}
	}

	// show Accs Array
	var elm = document.getElementById("phy_acc_order");
	var sortedAcc = new Array();
	var sortedIds = new Array;
	for (var x=0;x<elm.options.length;x++) {
		if(elm.options[x].value in acc){
			sortedAcc.push(JSON.stringify(acc[elm.options[x].value]));
			sortedIds[elm.options[x].value] = 1;
		}
	}
	var ret = "[";
	ret += sortedAcc.join(",");
	ret += "]";
	storage.setItem("_Lists",ret);

	// hide Accs Array
	var hides = document.getElementById("phy_acc_order");
	var hiddenAcc = new Array();
	var oriAccs =new Object(JSON.parse(storage.getItem('_Lists-origin')));
	for(var i=0;i<oriAccs.length;i++){
		if(!(oriAccs[i].id in sortedIds)) {
			hiddenAcc.push(JSON.stringify(oriAccs[i]));
		}
	}
	var retHidden = "[";
	retHidden += hiddenAcc.join(",");
	retHidden += "]";
	storage.setItem("_ListsDeleted", retHidden);

	_showLoading();
	storage.removeItem("_ListsTgt");
	FROMSCROLL=false;
	_windowGffClose();
	_execCanvas();
}

///////////////////////////////////////////////////////////
//Exporting FASTA
///////////////////////////////////////////////////////////
function _genFasta(){
	var chr = document.getElementById("prm_fa_chr");
	var st = document.getElementById("prm_fa_s");
	var ed = document.getElementById("prm_fa_e");
	var sub = document.getElementById("fa_submit");
	var numthread = JSON.parse(storage.getItem('_Env')).threadnum;
//        var numthread = _getNumThread();
	var ajaxloader = document.getElementById("fa_ajaxloader");

	//ajaxloader.innerHTML="<img src=\"./images/loader.gif\" alt=\"Exporting...\" style=\"\" />Exporting...";
	ajaxloader.innerHTML="<img src=\"./images/loader.gif\" alt=\"Exporting...\" style=\"\" />Exporting...(It may take several minutes)";
	sub.disabled = true;
	$.ajax({
		//url: "./bin/"+_backendSelector("fasta.php"),
		url: "./bin/"+_backendSelector("get_fasta_multi.php"),
		type: "POST",
		cache: false,
		data: {
			"prm_fa_chr":chr.value,
			"prm_fa_s":st.value,
			"prm_fa_e":ed.value,
			"prm_fa_flk":"",
			"prm_fa_tgt":document.getElementById("prm_fa_tgt").value,
			"prm_fa_var":"",
			"prm_fa_qual":document.getElementById("prm_fa_qual").value,
			"prm_fa_dp":document.getElementById("prm_fa_dp").value,
			"prm_fa_list":document.getElementById("prm_fa_list").value,
			"prm_fa_name":document.getElementById("prm_fa_name").value,
			"prm_fa_nameS":document.getElementById("prm_fa_nameS").value,
			"prm_fa_ref":document.getElementById("prm_fa_ref").value,
			"prm_fa_width":document.getElementById("prm_fa_width").value,
			"prm_fa_avd":document.getElementById("prm_fa_avd").value,
			"prm_fa_p3prm":"",
                        "prm_fa_DN":"",
                        "prm_fa_DNnum":"",
			"prm_fa_Ns":document.getElementById("prm_fa_Ns").value,
			"prm_type":"a",
			"prm_epcrprms":"",
			"prm_numthread":numthread
		}
	}).fail(function (XMLHttpRequest, textStatus, errorThrown) {
            ajaxloader.innerHTML=XMLHttpRequest.statu+" Error";
	}).done(function (data) {
            ajaxloader.innerHTML="";
            data = data.replace(/Error/g,'');
            var res = JSON.stringify(data);
            res = res.replace(/\\\\n/g,'\n');
            res = res.replace(/\"\[\\\"/g,'');
            res = res.replace(/\\\",\\\"/g,'\n');
            res = res.replace(/\\\"\]\"/g,'\n');
            if (data.match(/<font/) || data.match(/Invalid/)) {
                ajaxloader.innerHTML=data;
             } else {
                //data = data.replace(/Error/g,'');
                var Time = new Date();
                var timePrint = Time.getFullYear()+"_"+(Time.getMonth()+1)+"_"+Time.getDate();
                var fileName=_escapeHTML(chr.value)+"_"+st.value+"b-"+ed.value+"b_"+timePrint+".fasta";
                //_download(data,fileName);
                _download(res,fileName);
             }
	}).always(function() {
            sub.disabled = false;
        });
}

///////////////////////////////////////////////////////////
//Exporting CSV
///////////////////////////////////////////////////////////
function _genCSV(){
	var chr = document.getElementById("prm_csv_chr");
	var st = document.getElementById("prm_csv_s");
	var ed = document.getElementById("prm_csv_e");
	var pos = document.getElementById("choose_pos");
        var id = document.getElementById("choose_id");
        var sub = document.getElementById("csv_submit");
        if(pos.checked) {
                choose_flag = "1";
        } else if (id.checked) {
                choose_flag = "2";
        }
	var ajaxloader = document.getElementById("csv_ajaxloader");
	var idflag = 1;
	if(choose_flag == 2) {
		var kwd = document.getElementsByName("prm_csv_keyword")[0].value;
		var result = _checkID(kwd);
        	if(result == "Error") {
        		idflag = 0;
        	}
	}
	if (isNaN(parseInt(st.value)) || isNaN(parseInt(ed.value))) {
                ajaxloader.innerHTML="Invalid value: Position";
                return;
	} else if (idflag == 0) {
            	ajaxloader.innerHTML = "<font style=\"font-size:18px;color:red;\">Error : Invalid value in ID!</font>";
		return;
        } else {
		ajaxloader.innerHTML="<img src=\"./images/loader.gif\" alt=\"Exporting...(It may take several minutes)\" style=\"\" />Exporting...";
	        sub.disabled = true;
		$.ajax({
			url: "./bin/"+_backendSelector("csv.php"),
			type: "POST",
			cache: false,
			data: {
				"prm_csv_chr":chr.value,
				"prm_csv_s":st.value,
				"prm_csv_e":ed.value,
				"prm_pos_id":document.getElementsByName("prm_pos_id")[0].value,
				"prm_csv_qual":document.getElementById("prm_csv_qual").value,
				"prm_csv_dp":document.getElementById("prm_csv_dp").value,
				"prm_csv_list":document.getElementById("prm_csv_list").value,
				"prm_csv_keyword":document.getElementsByName("prm_csv_keyword")[0].value,
//				"prm_csv_effgrps":JSON.stringify(_getEffGrpArray("expfilter_effgrp")),
				"choose_flag":choose_flag
			}
		}).fail(function (XMLHttpRequest, textStatus, errorThrown) {
			console.log("x");
			ajaxloader.innerHTML=XMLHttpRequest.statu+" Error";
		}).done(function (data) {
			ajaxloader.innerHTML="";
			if (data.match(/Error/)) {
				ajaxloader.innerHTML=data;
			} else {
				//ajaxloader.innerHTML="";
				var Time = new Date();
				var timePrint = Time.getFullYear()+"_"+(Time.getMonth()+1)+"_"+Time.getDate();
				var fileName = "";
				if (choose_flag == "1") {
					fileName=_escapeHTML(chr.value)+"_"+parseInt(st.value)+"b-"+parseInt(ed.value)+"b_"+timePrint+".tsv";
				} else if (choose_flag == "2") {
					fileName=document.getElementsByName("prm_csv_keyword")[0].value+"_"+timePrint+".tsv";
				}
				_download(data,fileName);
			}
		}).always(function () {
			sub.disabled = false;
		});
	}
}

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

	sub.disabled = true;
	$.ajax({
//		url: "./bin/"+_backendSelector("fasta.php.multi"),
		url: "./bin/"+_backendSelector("fasta.php"),
		type: "POST",
		cache: false,
		data: {
			"prm_fa_chr":chrv,
			"prm_fa_s":parseInt(st.value),
			"prm_fa_e":parseInt(ed.value),
			"prm_fa_flk":parseInt(flk.value),
			"prm_fa_tgt":parseInt(tgt.value)+"-"+parseInt(tgte.value),
			"prm_fa_qual":q.value,
			"prm_fa_dp":dp.value,
			"prm_fa_var":variant.value,
			//"prm_fa_list":accession[0],
			"prm_fa_list":_getList("db").toString(),
			"prm_fa_name":storage.getItem("_Name"),
			"prm_fa_nameS":storage.getItem("_NameSub"),
			"prm_fa_ref":"REFERENCE",
			"prm_fa_width":"80",
			"prm_fa_avd":parseInt(avd.value),
			"prm_fa_p3prm":"",
			"prm_fa_Ns":p3Ns,
			//"prm_fa_DN":p3DN,
			"prm_type":"b"
		}
	}).fail(function() {
		ajaxloader.innerHTML=XMLHttpRequest.statu+" Error";
	}).done(function(data) {
		data = data.replace(/Error/g,'');
		res.innerHTML="<hr><br>"+data;
	}).always(function() {
		sub.disabled = false;
	});
}

///////////////////////////////////////////////////////////
// Run BLAST
///////////////////////////////////////////////////////////
function _runBlast(){
  var query = document.getElementById("blast_qryarea").value;
  var evalue = document.getElementById("blast_eval").value;
  var wordSize = document.getElementById("blast_word_size").value;
  var max_target_seqs = document.getElementById("max_target_seqs").value;
  //var max_matches = document.getElementById("max_matches").value;
  var match_scores = document.getElementById("match_scores").value.split(",");
  var match_scr = match_scores[0];
  var mismatch_scr = match_scores[1];
  var gap_costs = document.getElementById("gap_costs").value.split(",");
  var gap_open = gap_costs[0];
  var gap_extend = gap_costs[1];
  //var scoreMatrix = document.getElementById("blast_score_matrix").value;
  var sub = document.getElementById("blast_submit");
  var blastHit = true;
  query = query.replace(/<script>.*<\/script>/,"");
  escQuery = _escapeHTML(query);
  sub.disabled = true;
  $.ajax({
    //url: '../bin/blast.php',
    url: './bin/blast.php',
    type: "POST",
    data: {
        params:{
                blast_qryarea: escQuery,
                blast_eval: evalue,
                blast_word_size: wordSize,
                max_target_seqs: max_target_seqs,
                match_scr: match_scr,
                mismatch_scr: mismatch_scr,
                gap_open: gap_open,
                gap_extend: gap_extend
                //"blast_score_matrix" : scoreMatrix
        }
   }
   })
   .done(function (response) {
//	console.log(response);
        if (response instanceof Array) {
//		var hitsAndOrder = parseBlastXmlByArray(response);
		var hitsAndOrder = parseBlastPairwiseByArray(response);
		var hits = hitsAndOrder[0];
		var sortEval = hitsAndOrder[1];

                var alignSum = "";
                var blastResult = "";
		var blastTable;
                var alignResult="";
                var idCount = 0;
		var queCount = 0;
		var htmlstr = "";
		function ObjArraySort(ary, key, order) {
    			var reverse = 1;
    			if(order && order.toLowerCase() == "desc") 
        			reverse = -1;
    				ary.sort(function(a, b) {
        			if(parseFloat(a[key]) < parseFloat(b[key]))
            				return -1 * reverse;
        			else if(parseFloat(a[key]) == parseFloat(b[key]))
            				return 0;
        			else
            				return 1 * reverse;
    			});
		}
		ObjArraySort(sortEval,'evalue','asc');
		var messageStart = "<table style=\"text-align:center;width:500px;\" border=\"1\">\
                                        <tr>\
                                        <th>query</th>\
                                        <th>chr</th>\
                                        <th>hsp</th>\
                                        <th>qStrand</th>\
                                        <th>qStart</th>\
                                        <th>qEnd</th>\
                                        <th>sStrand</th>\
                                        <th>sStart</th>\
                                        <th>sEnd</th>\
                                        <th>Coverage</th>\
                                        <th>Evalue</th>\
                                        <th>Identity</th>\
                                        <th>Bit score</th>\
					<th> </th>\
                                        </tr><tr>";
		var messageEnd ="</table>";
		var p3qinfo = document.getElementById("p3result").value;
		var p3qinfos = [];
		if(p3qinfo != "undefined") {
			p3qinfos = p3qinfo.split(":");
		}
                for (key in hits) {
			if(key == "qlen") continue;
			queCount++;
			blastResult = "";
                        qname = key;
			for(i in sortEval) {
				if(!sortEval[i]["name"]) continue;	// for IE. (In IE, the contents of Array.prototype.remove are added to sortEval)
				var evals = sortEval[i]["name"].split("---SEv---");
				var quename = evals[0];
				var chr = evals[1];
				var hsp_num = evals[2];
				var bitscr;
                                var eval;
                                var q_from;
                                var q_to;
				var qstrand;
                                var s_from;
                                var s_to;
                                var qSeq;
                                var sSeq;
                                var midline;
                                var alignlen;
				var qcover;
				if(quename == qname) {
					idCount++;
                                        for (key4 in (hits[qname][chr][hsp_num])) {
                                                if (key4 == 'bitscr') {
                                                        bitscr = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'eval') {
                                                        eval = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'qfrom') {
                                                        q_from = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'qto') {
                                                        q_to = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'qstrand') {
                                                        q_strand = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'sfrom') {
                                                        s_from = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'sto') {
                                                        s_to = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'sstrand') {
                                                        s_strand = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'alignlen') {
                                                        alignlen = hits[qname][chr][hsp_num][key4];
                                                        if(typeof alignlen == 'string') alignlen=alignlen.trim();
                                                } else if (key4 == 'identity') {
                                                        identity = hits[qname][chr][hsp_num][key4];
                                                        if(typeof identity == 'string') identity=identity.trim();
                                                } else if (key4 == 'gaps') {
                                                        gaps = hits[qname][chr][hsp_num][key4];
                                                        if(typeof gaps == 'string') gaps=gaps.trim();
                                                } else if (key4 == 'qseq') {
                                                        qSeq = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'sseq') {
                                                        sSeq = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'midline') {
                                                        midline = hits[qname][chr][hsp_num][key4];
                                                } else if (key4 == 'qcover') {
							qcover = hits[qname][chr][hsp_num][key4];
						}
                                        }
                                        var ident =Math.round(identity/alignlen*100);
                                        var gaprate = Math.round(gaps/alignlen*100);
					var p3result = document.getElementById("p3result").value;

					var blstSt = s_from;
					var blstEn = s_to;
					if(s_from > s_to) {
						blstSt = s_to;
						blstEn = s_from;
					} 
					var blstTrack = ['all', blstSt, blstEn, chr].join('---TRK---');
					var blstButtonHtml  = "<button style=\"padding:0px;margin:-1px;\" onclick=\"_callDrawBLAST(\'"+ blstTrack + "\')\">Jump</button>";

					var trStyle = "";
					if(p3result != "undefined") {
						var p3results = p3result.split(":");
						var left = p3results[0];
						var leftinfo = left.split("---BLS---");
						var right = p3results[1];
						var rightinfo = right.split("---BLS---");
						if (leftinfo[0] == qname && leftinfo[1] == s_from && leftinfo[2] == s_to && leftinfo[3] == chr) {
							trStyle = "style=\"background-color:#ff6699;\"";
						} else if ( rightinfo[0] == qname && rightinfo[1] == s_to && rightinfo[2] == s_from && rightinfo[3] == chr) {
							trStyle = "style=\"background-color:#0099ff;\"";
						}
					} 
					blastResult = blastResult + "<tr " + trStyle + "><td align=\"center\">"+"<a href=#"+idCount+">"+_escapeHTML(qname)+"</td>"+"<td align=\"center\">"+_escapeHTML(chr)+"</td>"+"<td align=\"center\">"+_escapeHTML(hsp_num)+"</td>"+"<td align=\"center\">"+_escapeHTML(q_strand)+"</td>"+"<td align=\"center\">"+_escapeHTML(q_from)+"</td>"+"<td align=\"center\">"+_escapeHTML(q_to)+"</td>"+"<td align=\"center\">"+_escapeHTML(s_strand)+"</td>"+"<td align=\"center\">"+_escapeHTML(s_from)+"</td>"+"<td align=\"center\">"+_escapeHTML(s_to)+"</td>"+"<td align=\"center\">"+Math.round(qcover)+"%"+"</td>"+"<td align=\"center\">"+_escapeHTML(eval)+"</td>"+"<td align=\"center\">"+_escapeHTML(ident.toString(10))+"%</td>"+"<td align=\"center\">"+_escapeHTML(bitscr)+"</td><td>" + blstButtonHtml + "</td></tr>";
 
                                        alignResult="<div id="+idCount+">Query  : "+_escapeHTML(qname)+"<br>Subject: "+_escapeHTML(chr)+
						"<div style=\"border-top: 1px solid silver; border-bottom: 1px solid silver;\">" +
						"<table><tbody>" +
						"<tr><th align=\"center\">hsp    </th><th align=\"center\">bitscore    </th><th align=\"center\">expect    </th><th align=\"center\">identity    </th><th align=\"center\">gaps    </th><th align=\"center\">Strand    </th></tr>" +
						"<tr><td align=\"center\">"+_escapeHTML(hsp_num)+"</td><td align=\"center\">"+_escapeHTML(bitscr)+"</td><td align=\"center\">"+_escapeHTML(eval)+"</td><td align=\"center\">"+_escapeHTML(identity)+"/"+_escapeHTML(alignlen)+"("+ident+"%)"+"</td><td align=\"center\">"+_escapeHTML(gaps)+"/"+_escapeHTML(alignlen)+"("+gaprate+"%)"+"<td align=\"center\">"+_escapeHTML(q_strand)+"/"+_escapeHTML(s_strand)+"</td></tr>" +
						"</tbody></table></div>";
                                        var rownum = Math.ceil(qSeq.length / 60);
                                        var qSeqs = {};
                                        var midlines = {};
                                        var sSeqs = {};
                                        var qgaps = 0;
                                        var sgaps = 0;
                                        for (var i=0;i<rownum;i++) {
                                                var qpart = qSeq.substr(60*i,60);
                                                var spart = sSeq.substr(60*i,60);
                                                var midpart = midline.substr(60*i,60);
                                                var qstart = parseInt(q_from) + 60*i - qgaps;
                                                qgaps = qgaps + qpart.split('-').length-1;
                                                var qend = (qstart + 59) - qgaps;
                                                if(qend > q_to) {
                                                        qend = q_to
                                                }
                                                var sstart;
                                                if (s_from < s_to) {
                                                        sstart = parseInt(s_from) + 60*i - sgaps;
                                                        sgaps = sgaps + spart.split('-').length-1;
                                                        var send = (sstart + 59) - sgaps;
                                                        if(send > s_to) {
                                                                send = s_to
                                                        }
                                                } else if (s_from > s_to) {
                                                        sstart = parseInt(s_from) - 60*i + sgaps;
                                                        sgaps = sgaps + spart.split('-').length-1;
                                                        var send = (sstart - 59) + sgaps;
                                                        if(send < s_to) {
                                                                send = s_to
                                                        }
                                                }

                                                sstart = sstart.toString(10);
                                                qstart = qstart.toString(10);
                                                send = send.toString(10);
                                                qend = qend.toString(10);
                                                var midspace="";
                                                if(sstart.length > qstart.length) {
                                                        for (var j=0;j<sstart.length;j++) {
                                                                midspace += " ";
                                                        }
                                                        lngthdiff = sstart.length - qstart.length;
                                                        for (var j=0;j<lngthdiff;j++) {
                                                                qstart += " ";
                                                        }
                                                } else if(sstart.length < qstart.length) {
                                                        for ( var j=0;j<qstart.length;j++) {
                                                                midspace += " ";
                                                        }
                                                        lngthdiff = qstart.length - sstart.length;
                                                        for (var j=0;j<lngthdiff;j++) {
                                                                sstart += " ";
                                                        }
                                                }
                                                alignResult=alignResult+"<div><pre>Query  "+qstart+"  "+qpart+"  "+qend+"<br>";
                                                alignResult=alignResult+"       "+midspace+"  "+midpart+"<br>";
                                                alignResult=alignResult+"Sbjct  "+sstart+"  "+spart+"  "+send+"<br></pre></div>";
                                        }
                                        alignSum = alignSum+alignResult+"</div><br><br>";
                                }
                        }
			if(blastResult !== "") {
				if ( blastTable === undefined) {
                        		blastTable= "<font size=\"4\"><b>Query "+queCount+":"+qname+"</b></font><br>"+messageStart+blastResult+messageEnd;
				} else {
                        		blastTable= blastTable + "<font size=\"4\"><b>Query "+queCount+":"+qname+"</b></font><br>"+messageStart+blastResult+messageEnd;
				}
			}
		}
		var alignStart="<br><font size=\"4\"><b>Alignment</b></font><br><br>";
		blastTable = blastTable +alignStart+alignSum;
		var runBlastRes = document.getElementById("result");
        	var runBlastHist = document.getElementById("run_blast_hist");
                $('#result').html(blastTable);
		storage.setItem("_blastTable",blastTable);
                runBlastHist.innerHTML="<hr><div align=\"center\"><p><strong>Previous result was overwritten with latest one.</align></strong></p></div>";

		storage.setItem("_runBlast",1);
		storage.setItem("_blstHistFlg",1);
        } else {
                 errMsg="<font size=\"4\" color=\"red\"><b>"+response+"</b></font><br><br>";
                 $('#result').html(errMsg);
        }
        collapseBlastDialog(false);
   })
   .fail(function () {
        $('#result').val('失敗');
   }).always(function() {
        sub.disabled = false;
   });
}
function collapseBlastDialog(toCollapse) {
        if(toCollapse) {
                // Make the dialog smaller only if all content is collapsed.
                if(!$('#result').html() && $("#blst_opt").hasClass("close") && $('#blst_hist').hasClass("close")) {
                        $(".blast_window").css('max-height', '372px');
                        $(".blast_content").css('max-height', '329px');

                        $(".blast_window").css('max-height', '372px');
                        $(".blast_content").css('max-height', '329px');
                }
        } else {
                var defDialogHeight = 1240;
		var dialogHeight = defDialogHeight;
		if(parseInt($(".blast_window").css('top')) + dialogHeight - 1 > parseInt($("#tasuke").css('height'))) {
			dialogHeight = parseInt($("#tasuke").height()) - parseInt($(".blast_window").css('top')) + 1;
		}
                $(".blast_window").css('height', dialogHeight + 'px');
                $(".blast_content").css('height', (dialogHeight - 43) + 'px');

                $(".blast_window").css('max-height', defDialogHeight + 'px');
                $(".blast_content").css('max-height', (defDialogHeight - 43) +'px');
        }
}

///////////////////////////////////////////////////////////
//Run Primer3 (Supports v2.3.x)
///////////////////////////////////////////////////////////
function _runPrimer3(){
        var chr = document.getElementById("prm_rp3_chr").value;
        var flk = document.getElementById("prm_rp3_flk").value;
        var st = document.getElementById("prm_rp3_s").value;
        var ed = document.getElementById("prm_rp3_e").value;
        var tgt = document.getElementById("prm_rp3_tgt").value;
        var dp = document.getElementById("prm_rp3_dp").value;
        var q = document.getElementById("prm_rp3_qual").value;
        var variant = document.getElementById("prm_rp3_var").value;
        var tgte = document.getElementById("prm_rp3_tgt_e").value;
        var avd = document.getElementById("prm_rp3_avd").value;
        var prdmi = document.getElementById("prm_rp3_prdmi").value;
        var prdmx = document.getElementById("prm_rp3_prdmx").value;
        var sizeopt = document.getElementById("prm_rp3_sizopt").value;
        var sizmax = document.getElementById("prm_rp3_sizmax").value;
        var sizmin = document.getElementById("prm_rp3_sizmin").value;
        var tmopt = document.getElementById("prm_rp3_tmopt").value;
        var tmmx = document.getElementById("prm_rp3_tmmx").value;
        var tmmi = document.getElementById("prm_rp3_tmmi").value;
        var tmdif = document.getElementById("prm_rp3_tmdif").value;
        var lowmsk = document.getElementById("prm_rp3_lowmsk").value;
        //var p3Ns = document.getElementById("prm_rp3_Ns").value;
	//var form1 = document.forms.prm_rp3_Ns;
        //var p3Ns = form1.Ns_selection.value;
        var p3Ns = $("input[name='Ns_selection']:checked").val();
        //var form2 = document.forms.prm_rp3_DN;
        //var p3DN = form2.DN_selection.value;
        var p3DN = $("input[name='DN_selection']:checked").val();
	var p3DNnum = document.getElementById("prm_NA_num").value;
        var runP3Res = document.getElementById("run_p3_res");
        var runP3Hist = document.getElementById("run_p3_hist");
	var sub = document.getElementById("rp3_submit");
        var chrv = chr;
        var tgtv = parseInt(tgt);
        var tgtev = parseInt(tgte);

        //var doMFE = parseInt(document.forms.prm_epcr_onoff.epcr_selection.value);
        var doMFE = parseInt($("input[name='epcr_selection']:checked").val());
        epcr_prdmi = document.getElementById("prm_epcr_prdmi").value;
        epcr_prdmx = document.getElementById("prm_epcr_prdmx").value;
        epcr_tmmx = document.getElementById("prm_epcr_tmmx").value;
        epcr_tmmi = document.getElementById("prm_epcr_tmmi").value;
        epcr_monoconc = document.getElementById("prm_epcr_KCl").value;
        epcr_divaconc = document.getElementById("prm_epcr_MgCl2").value;
        epcr_dNTP = document.getElementById("prm_epcr_dNTP").value;
        epcr_anneal = document.getElementById("prm_epcr_annealing").value;
        var fileName = "";
        var p3Params = prdmi+","+prdmx+","+sizeopt+","+sizmax+","+sizmin+","
                        +tmopt+","+tmmx+","+tmmi+","+tmdif+","+lowmsk;
        var epcrParams = doMFE+","+epcr_prdmi+","+epcr_prdmx+","+epcr_tmmx+","+epcr_tmmi
                        +","+epcr_monoconc+","+epcr_divaconc+","+epcr_dNTP+","+epcr_anneal;
        var resTblStr = "<hr><table class=\"fontCourierNew\" style=\"margin-left:150px;\" cellspacing=\"0\"  width=\"60%\"><tr><td>";
        var resTblEnd = "</td></tr></table>";
	runP3Res.innerHTML = resTblStr+"<img src=\"./images/loader.gif\" alt=\"Running...\" style=\"\" />Running Primer3."+resTblEnd;
//        runP3Res.innerHTML = resTblStr+"<img src=\"./images/loader.gif\" alt=\"Running...\" style=\"\" />Running Primer3, you can close this dialog."+resTblEnd;
	sub.disabled = true;
	$.ajax({
//		url: "./bin/"+_backendSelector("fasta.php.multi"),
		url: "./bin/"+_backendSelector("fasta.php"),
		type: "POST",
		cache: false,
		data: {
                        	"prm_fa_chr":chrv,
                        	"prm_fa_s":parseInt(st),
                        	"prm_fa_e":parseInt(ed),
                        	"prm_fa_flk":parseInt(flk),
                        	"prm_fa_tgt":parseInt(tgt)+"-"+parseInt(tgte),
                        	"prm_fa_qual":q,
                        	"prm_fa_dp":dp,
                        	"prm_fa_var":variant,
                        	"prm_fa_list":_getList("db").toString(),
                        	"prm_fa_name":storage.getItem("_Name"),
                        	"prm_fa_nameS":storage.getItem("_NameSub"),
                        	"prm_fa_ref":"REFERENCE",
                        	"prm_fa_width":"80",
                        	"prm_fa_avd":parseInt(avd),
                        	"prm_fa_p3prm":p3Params,
                        	"prm_fa_Ns":p3Ns,
                        	"prm_fa_DN":p3DN,
                        	"prm_fa_DNnum":p3DNnum,
                        	"prm_type":"c",
                        	"prm_epcrprms":epcrParams
		}
	}).done(function(data) {
                        if (data.match(/^PRIMER/)) {
				if(p3DN == 2) {
					var resTblStr = "<hr><table class=\"fontCourierNew\" style=\"margin-left:150px;\" cellspacing=\"0\"  width=\"60%\"><tr><td>";
                                	var resTblEnd = "</td></tr></table>";
					runP3Res.innerHTML=resTblStr+"<img src=\"./images/loader.gif\" alt=\"Running...\" style=\"\" />Running Primer3."+resTblEnd;
//                                runP3Res.innerHTML=resTblStr+"<img src=\"./images/loader.gif\" alt=\"Running...\" style=\"\" />Running Primer3, you can close this dialog."+resTblEnd;
				}
                                data = data;
                                var rtn = "";
                                var resTblStr = "<table class=\"fontCourierNew\" style=\"margin-left:75px;\" cellspacing=\"0\"  width=\"80%\"><tr><td>";
                                var rtnTblStr = "<table class=\"fontCourierNew\" width=\"585px\"style=\"margin-left:60px;\" cellspacing=\"0\" border=\"1\" ><tr><td>";
                                var resTblEnd = "</td></tr></table>";
                                var rtnTblEnd = "</td></tr></table><br>";
                                        var resCont = "You can download the result from this button ->\
                                        <button type=\"submit\" name=\"prm_rp3_submit\" onclick=\"_getP3Result();\">Download</button>";
                                var array = [];
//                                var MFEresult = "";
                                var lNsseqs = [];
                                var rNsseqs = [];
				if(p3DN == 2) {
                                       var array=data.split("---SPLIT---");
					if(!(array[0].match(/NO PRIMERS FOUND/))) {
                                        	var rtnP3Array = array[1].split("--split--");
                                        	var lPrmList = rtnP3Array[1].split("-");
                                        	var rPrmList = rtnP3Array[2].split("-");
                                        	var lPrm = lPrmList[0].split(":");
                                        	var rPrm = rPrmList[0].split(":");
                                        	var rtnSeqArray = rtnP3Array[0].split("");
                                        	var t = lPrmList.length;
                                        	var prmCand="";
                                        	for(var i=0; i<t; i++){
                                                	var eachLPrm = lPrmList[i].split(":");
                                                	var eachRPrm = rPrmList[i].split(":");
							// !!! PRIMER_FIRST_BASE_INDEX=0(default) !!!
                                                	lprm_from=parseInt(tgt)-parseInt(flk)+parseInt(eachLPrm[0]);
                                                	lprm_to = parseInt(lprm_from)+parseInt(eachLPrm[1])-1;
                                                	rprm_to = parseInt(tgt)-parseInt(flk)+parseInt(eachRPrm[0]);
                                                	rprm_from = parseInt(rprm_to)-parseInt(eachRPrm[1])+1;
                                                	resultNs = _checkNs(lprm_from,lprm_to,rprm_from,rprm_to,chrv);
                                                	resultNspos = resultNs.split("|");
                                                	lNspos = resultNspos[0];
                                                	rNspos = resultNspos[1];
                                                	var lNsseq = "";
                                                	var rNsseq = "";
                                                	leftp3=_escapeHTML(eachLPrm[2]);
                                                	rightp3=_escapeHTML(eachRPrm[2]);
                                                	for ($j=0;$j<leftp3.length;$j++) {
                                                	        pos = lprm_from + $j;
                                                	        if(lNspos.match(pos)) {
                                                                	lNsseq = lNsseq + "<font color=\"orange\">"+leftp3[$j]+"</font>";
                                                        	} else {	
                                                                	lNsseq = lNsseq + leftp3[$j];
                                                        	}	
                                                	}
                                                	lNsseqs[i] = lNsseq;
                                                	for ($j=0;$j<rightp3.length;$j++) {
                                                        	pos = rprm_from + $j;
                                                        	if(rNspos.match(pos)) {
                                                        	        rNsseq = rNsseq + "<font color=\"orange\">"+rightp3[$j]+"</font>";
                                                        	} else {
                                                                	rNsseq = rNsseq + rightp3[$j];
                                                        	}
                                                	}
							rNsseqs[i] = rNsseq;
                                        	}
					}
                                }
				if(doMFE==1) {
					var twodata = data.split("---MFESPLIT---");
					array=twodata[0].split("---SPLIT---");
					var MFEResObj = parseMFEprimerResult(data);
					var rtn = _p3Table(data,chrv,tgt,tgte,flk,runP3Res,p3DN,lNsseqs,rNsseqs, MFEResObj);
				} else {
					array=data.split("---SPLIT---");
					var rtn = _p3Table(data,chrv,tgt,tgte,flk,runP3Res,p3DN,lNsseqs,rNsseqs, null);
				}
/*
                                if(doMFE==1) {
                                        twodata = data.split("---MFESPLIT---");
                                        array=twodata[0].split("---SPLIT---");
                                        MFEresult = twodata[1].replace(/---QUERY---/g,"\n").replace(/---MFERES---/g,"\n");
                                        var rtn = _MFETable(data,chrv,tgt,tgte,flk,runP3Res,p3DN,lNsseqs,rNsseqs);
                                } else if (doMFE==0) {
                                        array=data.split("---SPLIT---");
                                        var rtn = _p3Table(data,chrv,tgt,tgte,flk,runP3Res,p3DN,lNsseqs,rNsseqs);
                                }
*/
                                var rtnArray = rtn.split("--RTNSPLIT--");
                                var prmCand = rtnArray[0];
                                var rtnSeqArray = rtnArray[1].split("");
                                var lPrmRtn = rtnArray[2];
                                var lPrm = lPrmRtn.split("--lPrm--");
                                var rPrmRtn = rtnArray[3];
                                var rPrm = rPrmRtn.split("--rPrm--");
                                var message = rtnArray[4];
                                var fileName = rtnArray[5];
                                var tableFunc = rtnArray[6];
                                var y = rtnSeqArray.length;
                                var strCount = 0;
                                var strRealCount = 0;
                                var pointer = 0;
                                var tag = "false";
                                for(var x=0; x<y; x++){
                                        strRealCount++;
                                        if(rtnSeqArray[x].match(/</)){
                                                tag = "true";
                                        }
                                        if(tag == "true"){
                                                if(rtnSeqArray[x].match(/>/)){
                                                        tag = "false";
                                                }
                                        }
                                        else{
                                                if(rtnSeqArray[x].match(/[ATGCNWSMKRYBDHVatgcnwsmkrybdhv]/)){
                                                        strCount++;
                                                        pointer=0;
                                                        if(rtnSeqArray[x+1]=="<" && rtnSeqArray[x+2]=="/"){pointer=7;}//</font> +7
                                                        if(strCount == lPrm[0]){
                                                                rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"<font color='#ff6699'>";
                                                        }else if(strCount == parseInt(lPrm[0])+parseInt(lPrm[1])){
                                                                rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"</font>";
                                                        }
                                                        else if(strCount == parseInt(rPrm[0])-parseInt(rPrm[1])+1){
                                                                rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"<font color='#0099ff'>";
                                                        }
                                                        else if(strCount == parseInt(rPrm[0])+1){
                                                                rtnSeqArray[x+pointer]=rtnSeqArray[x+pointer]+"</font>";
                                                        }
                                                }else{
                                                        console.log("Unexpected char");
                                                }
                                        }
                                }
                                var rtnP3 = rtnTblStr+"<span id=\"resSeq\"><!--:-->"+rtnSeqArray.join("")+"<!--:--></span>"+rtnTblEnd;
                                //runP3Res.innerHTML="<hr>"+resTblStr+message+prmCand+resTblEnd+rtnP3+resTblStr+resCont+resTblEnd;
                                runP3Res.innerHTML="<hr>"+resTblStr+message+prmCand+resTblEnd+rtnP3+resTblStr+resCont+resTblEnd;
                                if(doMFE==0) {
                                        _storeP3Res(fileName+"---SPLIT---"+array[0]+"---SPLIT---"+"<hr>"+resTblStr+message+prmCand+resTblEnd+""+rtnP3+""+resTblStr+resCont+resTblEnd);
                                } else {
					var twodata = data.split("---MFESPLIT---");
					var MFEresult = twodata[1].replace(/---QUERY---/g,"\n").replace(/---MFERES---/g,"\n");
                                        _storeP3Res(fileName+"---SPLIT---"+"Primer3Result\n\n"+array[0]+"------------------------------\n\nMFEprimerResult\n\n"+MFEresult+"---SPLIT---"+"<hr>"+resTblStr+message+prmCand+resTblEnd+""+rtnP3+""+resTblStr+resCont+resTblEnd);
                                }
                                runP3Hist.innerHTML="<hr><div align=\"center\"><p><strong>Previous result was overwritten with latest one.</align></strong></p></div>";
                        } else {
                                errMsg="<font size=\"4\" color=\"red\"><b>"+data+"</b></font><br><br>";
                                runP3Res.innerHTML=errMsg;
                        }
        }).fail(function() {
		ajaxloader.innerHTML=XMLHttpRequest.statu+" Error";
	}).always(function() {
		sub.disabled = false;
	});
}

///////////////////////////////////////////////////////////
// create Primer3 result
///////////////////////////////////////////////////////////
function _p3Table(data,chrv,tgt,tgte,flk,runP3Res,p3DN,lNsseq,rNsseq, MFEResult) {
        var date = new Date();
        var array=data.split("---SPLIT---");
        var resTblStr = "<table class=\"fontCourierNew\" style=\"margin-left:75px;\" cellspacing=\"0\"  width=\"80%\"><tr><td>";
        var resTblEnd = "</td></tr></table>";
        var fileName=chrv+"_"+parseInt(tgt)+"-"+parseInt(tgte)+"_"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
        var target = fileName.split("_");
	var message = "<font style=\"font-size:18px\"><b>Result</b></font><br><strong>Your request: "+_escapeHTML(target[0])+" "+_escapeHTML(target[1])+"</strong><br><font color='#008000'>Primer designing has been finished!</font>";
        var message = "<font style=\"font-size:18px\"><b>Result</b></font><br><strong>Your request: "+_escapeHTML(target[0])+" "+_escapeHTML(target[1])+"</strong><br><font color='#008000'>Primer designing has been finished!</font>";
	if(MFEResult != null) message = message + "<br><font color=red>the results PPC value is under 0 is predicted with the same query pairs(left-left or right-right).</font>";
	if (p3DN == 2) {
		message = message + "<br><font color=orange>the strings colored orange explain the position with DEPTH is NA.</font><br><br>";
	} else {
		message = message + "<br><br>";
	}
        var resCont = "You can download the result from this button ->\
                  <button type=\"submit\" name=\"prm_rp3_submit\" onclick=\"_getP3Result();\">Download</button>";
        runP3Res.innerHTML="";
        if(array[0].match(/^Error/)){
                runP3Res.innerHTML=array[0]+"<br>";
                return;
        }
        if(array[1]=="Cookies"){resCont="Cookies Required: Cookies are not enabled on your browser.";}
        var rtnP3Array = array[1].split("--split--");
        var rtnTblStr = "<table class=\"fontCourierNew\" width=\"585px\"style=\"margin-left:60px;\" cellspacing=\"0\" border=\"1\" ><tr><td>";
        var rtnTblEnd = "</td></tr></table><br>";
        var lPrmList = rtnP3Array[1].split("-");
        var rPrmList = rtnP3Array[2].split("-");
        var lPrm = lPrmList[0].split(":");
        var rPrm = rPrmList[0].split(":");
        var rtnSeqArray = rtnP3Array[0].split("");
        var t = lPrmList.length;
        var prmCand="";
        var mfepParams = ['amp', 'lseq', 'rseq', 'hitchr', 'start', 'end', 'len', 'ltm', 'rtm', 'ppc', 'gc'];
        for(var i=0; i<t; i++){
                var eachLPrm = lPrmList[i].split(":");
                var eachRPrm = rPrmList[i].split(":");
                if(!eachLPrm[0]){
                        prmCand="<strong>NO PRIMERS FOUND</strong><br>";
                        break;
                }
		// !!! PRIMER_FIRST_BASE_INDEX=0(default) !!!
                lprm_from=parseInt(tgt)-parseInt(flk)+parseInt(eachLPrm[0]);
                lprm_to = lprm_from + parseInt(eachLPrm[1]) - 1;
		rprm_to = parseInt(tgt)-parseInt(flk)+parseInt(eachRPrm[0]);
		rprm_from = rprm_to - parseInt(eachRPrm[1]) + 1;
//                lprm_from=parseInt(tgt)-parseInt(flk)+parseInt(eachLPrm[0]);
//                lprm_to = parseInt(lprm_from)+parseInt(eachLPrm[1])-1;
//                rprm_to = parseInt(tgt)-parseInt(flk)+parseInt(eachRPrm[0]);
//                rprm_from = parseInt(rprm_to)-parseInt(eachRPrm[1])+1;
                s_from = parseInt(lprm_from);
                s_to = parseInt(rprm_to);
		var p3_track="all---TRK---"+s_from+"---TRK---"+s_to+"---TRK---"+chrv+"---SPL---lPrm---TRK---"+lprm_from+"---TRK---"+lprm_to+"---TRK---"+chrv+"---SPL---rPrm---TRK---"+rprm_from+"---TRK---"+rprm_to+"---TRK---"+chrv+"---SPL---target---TRK---"+tgt+"---TRK---"+tgte+"---TRK---"+chrv;
                p3blast="left---BLS---"+lprm_from+"---BLS---"+lprm_to+"---BLS---"+chrv+":Right---BLS---"+rprm_from+"---BLS---"+rprm_to+"---BLS---"+chrv;
                primer3ArrayForBLASTLeft = "left\n"+_escapeHTML(eachLPrm[2]);
                primer3ArrayForBLASTRight = "Right\n"+_escapeHTML(eachRPrm[2]);

		var leftSeq = "";
		var rightSeq = "";
		var isEssRes = false;
		if(p3DN==2) {
			leftSeq = lNsseq[i];
			rightSeq = rNsseq[i];
			if(lNsseq[i] != "" && rNsseq[i] != "") isEssRes = true;
		} else {
			leftSeq = _escapeHTML(eachLPrm[2]);
			rightSeq = _escapeHTML(eachRPrm[2]);
			isEssRes = true;
		}
		if(isEssRes) {
			var radioVal = [_escapeHTML(eachLPrm[0]), _escapeHTML(eachLPrm[1]), _escapeHTML(eachRPrm[0]), _escapeHTML(eachRPrm[1]), i].join(':');
			var checked = '';
			if(i==0) checked = 'checked';
			var prmCand = prmCand + "<input type=\"radio\" name=\"chPrimer\" value=\"" + radioVal +"\" " + checked + " onclick=\"_switchP3Result();\" />" +
				"&nbsp;Left:&nbsp;" + leftSeq +"&nbsp;&nbsp;&nbsp;Right:&nbsp;" + rightSeq + "&nbsp;&nbsp;" + 
				"<input type=\"button\" value=\"BLAST\" class=\"blast\" onclick=\"_dialog_blast(\'"+_escapeHTML(eachLPrm[2])+"\',\'"+_escapeHTML(eachRPrm[2])+"\',\'"+_escapeHTML(p3blast)+"\')\">&nbsp;&nbsp;" +
				"<button onclick=\"_callDrawBLAST(\'"+p3_track+"\')\">Jump</button>";

			// Add MFEprimer Result
			var primer3ArrayForBLASTLeft = ">left\n"+_escapeHTML(eachLPrm[2]);
			var primer3ArrayForBLASTRight = ">right\n"+_escapeHTML(eachRPrm[2]);
			var primerpair = primer3ArrayForBLASTLeft+"\n"+primer3ArrayForBLASTRight;
			if(MFEResult != null && primerpair in MFEResult) {
				var table = "<table align=\"center\" border=\"1\" width=\"840px\">"+
					"<tr><th>AmpID</th>"+
					"<th>Left Seq</th>"+
					"<th>Right Seq</th>"+
					"<th>Hit chr</th>"+
					"<th>Start</th>"+
					"<th>End</th>"+
					"<th>Length</th>"+
					"<th>Left Tm</th>"+
					"<th>Right Tm</th>"+
					"<th>PPC</th>"+
					"<th>GCcontent</th>"+
					"<th></th>"+
					"</tr><tr>";
				var hit = 0;
				var psets = MFEResult[primerpair];
				for(var j=0, psetsLen=psets.length; j<psetsLen; j++) {
					hit++;
					var obj = MFEResult[primerpair][j];
					table = table + "<tr>";
//					for(var v of ['amp', 'lseq', 'rseq', 'hitchr', 'start', 'end', 'len', 'ltm', 'rtm', 'ppc', 'gc']) {
					for(var k=0,mfepParamsLen=mfepParams.length; k<mfepParamsLen; k++) {
						var v = mfepParams[k];
						table = table + "<td align=center>" + obj[v]+ "</td>";
					}
					var mfe_p3_track="all---TRK---" + obj['start'] + "---TRK---" + obj['end'] + "---TRK---" + obj['hitchr'] +  
						"---SPL---lPrm---TRK---" + parseInt(obj['start']) + "---TRK---" + (parseInt(obj['start']) + obj['lseqm'].length - 1) + "---TRK---" + obj['hitchr'] + 
						"---SPL---rPrm---TRK---" + (parseInt(obj['end']) - obj['rseqm'].length + 1) + "---TRK---" + obj['end'] + "---TRK---" + obj['hitchr'] + 
						"---SPL---target---TRK---" + (parseInt(obj['start']) + obj['lseqm'].length) + "---TRK---" + (parseInt(obj['end']) - obj['rseqm'].length) + "---TRK---" + obj['hitchr'];
					table = table + "<td><button style=\"padding:0px;margin:-1px;\" onclick=\"_callDrawBLAST(\'" + mfe_p3_track + "\')\">Jump</button></td>";
					table = table + "</tr>";
				}
				table = table+"</table><br>";
				prmCand = prmCand + "&nbsp;<br><span><div style=\"display: inline-block\" ><span id=\"cond_multi_triangle\" class=\"ui-icon ui-icon-triangle-1-e\" onClick=\"_slideePCRTable(" + i + ")\"></span></div>" +
					"<span onClick=\"_slideePCRTable(" + i + ")\">estimated amplified products&nbsp;:&nbsp;" + hit  + "</span><br>" + 
					"<div id=\"epcrTable" + i + "\" style=\"display:none\">" + table + "</div></span>";
//				prmCand = prmCand + "&nbsp;<br><span><div style=\"display: inline-block\" ><span id=\"cond_multi_triangle\" class=\"ui-icon ui-icon-triangle-1-e\"></span></div><span onClick=\"_slideePCRTable(" + i + ")\">estimated amplified products&nbsp;:&nbsp;" + hit  + "</span><br>" + "<div id=\"epcrTable" + i + "\" style=\"display:none\">" + table + "</div></span>";
			} else {
				prmCand = prmCand+"<br>";
			}
		}

        	if(prmCand != "") {
                	var lPrmRtn = lPrm[0]+"--lPrm--"+lPrm[1]+"--lPrm--"+lPrm[2];
                	var rPrmRtn = rPrm[0]+"--rPrm--"+rPrm[1]+"--rPrm--"+rPrm[2];
        	}
	}
        var rtn = prmCand+"--RTNSPLIT--"+rtnP3Array[0]+"--RTNSPLIT--"+lPrmRtn+"--RTNSPLIT--"+rPrmRtn+"--RTNSPLIT--"+message+"--RTNSPLIT--"+fileName;
        return(rtn);
}

///////////////////////////////////////////////////////////
// parse MFEprimer result
///////////////////////////////////////////////////////////
function parseMFEprimerResult(data) {
	var revConvTable = {A:'T', T:'A', G:'C', C:'G', a:'t', t:'a', g:'c', c:'g'};
	function revSeq(seq) {
		var rightRevArray = seq.split("").reverse();
		for(var k=0,rightRevArrayLen=rightRevArray.length; k<rightRevArrayLen; k++) {
			var base = rightRevArray[k];
			rightRevArray[k] = revConvTable[base];
		}
		return rightRevArray.join('');
	}

	var twodata = data.split("---MFESPLIT---");
	var mfedata = twodata[1].split("---MFERES---");

	var result = {};
	var m = mfedata.length-1;
	for (var i=0;i<m;i++) {
		var mfeque = mfedata[i].split("---QUERY---");
		var primerpair = mfeque[0];

		result[primerpair] = [];
		MFEresult=mfeque[1].split("\n");
		lenres = MFEresult.length;
		for (var j=0;j<lenres;j++) {
			if(MFEresult[j].match(/^AmpID/)) continue;

			MFEinfo = MFEresult[j].split("\t");
			if(MFEinfo.length > 14) MFEinfo.splice(4, MFEinfo.length - 14); //Tab is used in Fasta header, so delete it

			var mferesPat = /^([atgc]*)([ATCG].*[ATCG])[a-z]+([ATCG].*[ATCG])([atgc]*)$/;
			var productArray = [];
			if(mferesPat.test(MFEinfo[13])) productArray = MFEinfo[13].match(mferesPat);    // (agg)(ATtCGaGCG)cgatgnca...taycgtacg(CGTCaGCTaC)(gctt);

			var leftDisp = productArray[1] + productArray[2];
			var leftMatch = productArray[2];
			var rightDisp = revSeq(productArray[3] + productArray[4]);
			var rightMatch = revSeq(productArray[3]);
/*
			var leftArray = MFEinfo[13].match(/^([atgc]*)([ATCG]+?)[atgc]/);
			var rightArray = MFEinfo[13].match(/[atgc]([ATCG]+)([atgc]*)$/);
			var leftDisp = leftArray[1] + leftArray[2];
			var leftMatch = leftArray[2];
			var rightDisp = revSeq(rightArray[1] + rightArray[2]);
			var rightMatch = revSeq(rightArray[1]);
*/
			var onerowHash = {
				amp:	MFEinfo[0],
				hitchr:	MFEinfo[3],
				ppc:	MFEinfo[4],
				len:	MFEinfo[5],
				gc:	MFEinfo[6],
				ltm:	MFEinfo[7],
				rtm:	MFEinfo[8],
				start:	MFEinfo[11],
				end:	MFEinfo[12],
				lseq:	leftDisp,
				rseq:	rightDisp,
				lseqm:	leftMatch,
				rseqm:	rightMatch
			};
			result[primerpair].push(onerowHash);
		}
	}
	return result;
}

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



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

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

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

function _indirDownload(data,name){
	_download(data,name);
}

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

function _dlNewick() {
        var content = $("#newick").val();
        var name = $("#nname").val();
        dlTarget=new Blob([content],{type:"text/plain"});
        var a = document.createElement("a");
        a.download = name;
        a.href = window.URL.createObjectURL(dlTarget);
        e = document.createEvent('MouseEvent');
        e.initEvent("click",true,true);
        a.dispatchEvent(e);
}
///////////////////////////////////////////////////////////
//Double click for zoom in
///////////////////////////////////////////////////////////
function _execDblClick(x) {
	if(_cvtZoom(Objects.Zoom)>1){
		var t=parseInt(x/Objects.BlockW);
		if (t==0) t=1;
		var b=(parseInt(Objects.Pos)+t)*_cvtZoom(Objects.Zoom);
		var p=_checkPos(parseInt(b/_cvtZoom(_cvtZoomDown(Objects.Zoom)))-(Objects.Block/2)+1,_cvtZoomDown(Objects.Zoom));
		storage.setItem("_Pos", new String(p));
		storage.setItem("_Zoom", _cvtZoomDown(Objects.Zoom));
		_showLoading();
		_drawMessageOnScreen("zoomInPos",x);
		_messageOnScreen("Zoom in "+Objects.Zoom+" to "+_cvtZoomDown(Objects.Zoom)+" per block");
		FROMSCROLL=false;
		_execCanvas();
	} else {
		_messageOnScreen("Minimum zoom scale");
	}
	// Unlink cell information
	if($("#dialog_infocell").hasClass("ui-dialog-content")){
		$("#dialog_infocell").dialog("close");
	}
}

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

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

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

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

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

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

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

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

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

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

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

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

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

	cvs6.width=Objects.canvasWidth;
	cvs6.height=20;
	ctx6.fillStyle=_setColor().bgcolor;
	ctx6.fillRect(0,0,cvs6.width,cvs6.height);
	ctx6.setTransform(1, 0, 0, 1, 0, 0);
	ctx6.font="11px 'Courier'";
	
	if(phenotypeFlg){
		cvs12.width=Objects.canvasWidth;
		//cvs12.width="1000";
		//cvs12.height="120";
		cvs12.height="80";
		ctx12.fillStyle="#ffffff";
		ctx12.fillRect(0,0,cvs12.width,cvs12.height);
		ctx12.setTransform(1, 0, 0, 1, 0, 0);
		ctx12.font="10px 'Courier'";
	
		//cvs13.width=Objects.titleWidth +11;
		cvs13.width=Objects.titleWidth + 3;
		//cvs13.height="120";
		cvs13.height="80";
		ctx13.fillRect(0,0,cvs13.width,cvs13.height);
		ctx13.setTransform(1, 0, 0, 1, 0, 0);
		ctx13.font="11px 'Courier'";
		cvs19.width=Objects.titleWidth +11;
                cvs19.height="80";
                ctx19.fillRect(0,0,cvs13.width,cvs13.height);
                ctx19.setTransform(1, 0, 0, 1, 0, 0);
                ctx19.font="11px 'Courier'";

	}
	cvs14.width=1;
        cvs14.height=1;
        cvs15.width=1;
        cvs15.height=1;

        cvs16.width=cvs4.width;
        cvs16.height=cvs4.height;
        ctx16.fillStyle="#fff";
        ctx16.fillRect(0,0,cvs16.width,cvs16.height);

        cvs17.width=Objects.titleWidth+2;
        cvs17.height=20;
        //ctx5.fillStyle=_setColor().bgcolor;
        ctx17.fillStyle="#dcdcdc";
        ctx17.fillRect(0,0,cvs17.width,cvs17.height);
        ctx17.setTransform(1, 0, 0, 1, 0, 0);
        ctx17.font="12px 'Courier'";

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


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

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

//	pre-drawing:required
	
	cvs9.width=Objects.canvasWidth;
	cvs9.height=75;
	//ctx9.fillStyle=_setColor().bgcolor;
	ctx9.fillStyle="#302833";
	ctx9.fillRect(0,0,cvs9.width,cvs9.height);
	ctx9.strokeStyle="#302833";
	ctx9.lineWidth=30;
	ctx9.beginPath();
	ctx9.moveTo(3,49);
	ctx9.lineTo(591,49);
	ctx9.stroke();
	ctx9.closePath();
	ctx9.lineWidth=23;
	ctx9.beginPath();
	ctx9.lineCap = "round";
	ctx9.moveTo(14,55);
	ctx9.lineTo(580,55);
	ctx9.stroke();
	ctx9.closePath();
	ctx9.beginPath();
	ctx9.lineCap = "round";
	ctx9.moveTo(14,45);
	ctx9.lineTo(580,45);
	ctx9.stroke();
	ctx9.closePath();
	ctx9.shadowOffsetX = 0;
	ctx9.shadowOffsetY = 0;
	ctx9.shadowBlur = 0;
/*
	ctx9.strokeStyle="#999999";
	ctx9.lineWidth=3;
	ctx9.beginPath();
	ctx9.arc(384, 19, 9, 0, Math.PI*2, false);
	ctx9.stroke();
	ctx9.beginPath();
	ctx9.arc(419, 19, 9, 0, Math.PI*2, false)
	ctx9.stroke();
	ctx9.lineWidth=4;
	ctx9.beginPath();
	ctx9.moveTo(392,26);
	ctx9.lineTo(405,37);
	ctx9.closePath();
	ctx9.stroke();
	ctx9.beginPath();
	ctx9.moveTo(425,26);
	ctx9.lineTo(438,37);
	ctx9.closePath();
*/
	
	ctx9.stroke();
	ctx9.fillStyle=_setColor().zoombar;
	ctx9.fillRect(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'";
	frameZoomb=ctx9.getImageData(0, 0, cvs9.width, cvs9.height);
	var elementcell = document.getElementById("cellinf"); 
	elementcell.style.top = '1px'; 
	elementcell.style.left = '1px';

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

	cvs11.width=Objects.titleWidth;
	cvs11.height=parseInt(Objects.NavH/3);
	//ctx11.fillStyle=_setColor().bgcolor;
	ctx11.fillStyle="#dcdcdc";
	ctx11.fillRect(0,0,cvs11.width, cvs11.height);
	ctx11.setTransform(1, 0, 0, 1, 0, 0);
	ctx11.font="16px 'Courier'";

	// Set to main canvas height
	var offset=20;
	var divHeight=window.innerHeight-$('#content').offset().top-$('#content2').height()-$('#bottom').height()-offset;
	if ( Objects.canvasHeight < divHeight ) {
		divHeight=Objects.canvasHeight+16;
	}
	$('#content').css("height", divHeight);

	// Changing height during resize
	$(window).bind("resize", resizeWindow);
	function resizeWindow( e ) {
		divHeight=$(window).height()-$('#content').offset().top-$('#content2').height()-$('#bottom').height()-offset;
		if ( Objects.canvasHeight < divHeight ) {
			divHeight=Objects.canvasHeight+10;
		} 
	$('#content').css("height", divHeight);
	}
}

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

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

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

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

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

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

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

/////////////////////////////////////////////// Change display mode
function _changeMode(str){
	if ( Objects.Snpblock == "off" ) {
		var mode = storage.getItem("_Mode"); //get drawing mode
		if (str == "s") {
			if (storage.getItem("_sFlg") == "1") { // if already selected
        			if(mode.match(/dp/)) { //if with depth
					if(mode.match(/a/)) { //if with snp and indel
						mode = mode.replace('a','is'); // a to is
                                		mode = mode.replace('s',''); //remove s -> dp+i
                        		} else {
                                		mode = mode.replace('+s',''); //remove s -> dp
                        		} 
				} else { //if not depth
					mode = mode.replace('s','');
				}
				storage.setItem("_sFlg","0"); //set off-snpFlg
			} else if (storage.getItem("_sFlg") == "0") { //if not selected
        			if(mode.match(/dp/)) { //if with depth
					if(mode.match(/i/)) { //if with indel
						mode = mode.replace(/i/,''); //dp +
						mode = mode+'a'; // dp+a(indel+snp)
					} else {
						mode = mode+'+s'; //with snp(dp+s)
					}
				} else {
					mode = 's'+mode; // a to si
				}
				storage.setItem("_sFlg","1"); //set off-snpFlg
			}
			storage.setItem("_Mode", mode);
		}
		else if (str == "i") {
                        if (storage.getItem("_iFlg") == "1") { // if already selected
                                if(mode.match(/dp/)) { //if with depth
                                        if(mode.match(/a/)) { //if with snp and indel
                                                mode = mode.replace('a','is'); // a to is
                                                mode = mode.replace('i',''); //remove s -> dp+i
                                        } else {
                                                mode = mode.replace('+i',''); //remove s -> dp
                                        }
                                } else { //if not depth
                                        mode = mode.replace('i','');
                                }
                                storage.setItem("_iFlg","0"); //set off-snpFlg
                        } else if (storage.getItem("_iFlg") == "0") { //if not selected
                                if(mode.match(/dp/)) { //if with depth
                                        if(mode.match(/s/)) { //if with indel
                                                mode = mode.replace(/s/,''); //dp +
                                                mode = mode+'a'; // dp+a(indel+snp)
                                        } else {
                                                mode = mode+'+i'; //with snp(dp+s)
                                        }
                                } else {
                                        mode = mode+'i'; // a to si
                                }
                                storage.setItem("_iFlg","1"); //set off-snpFlg
                        }
                        storage.setItem("_Mode", mode);
		}
		else if (str == "dp") {
                        if (storage.getItem("_dpFlg") == "1") { // if already selected
                                mode = mode.replace('dp',''); // remove dp+
                                mode = mode.replace('+',''); // remove dp+
                        	if(mode == "a") { // with snp and indel
                                        mode = mode.replace('a','si'); // a -> si
                                }
                                storage.setItem("_dpFlg","0"); //set off-snpFlg
                        } else if (storage.getItem("_dpFlg") == "0") { //if not selected
                        	if(mode == "si") { //if with snp and indel
                                	mode = mode.replace('si','a');
                                } 
				if (mode == "") {
					mode = 'dp';
				} else {
					mode = 'dp+'+mode;
				}
                                storage.setItem("_dpFlg","1"); //set off-snpFlg
                        }
                        storage.setItem("_Mode", mode);
		}
		_drawCanvas();
	} else {
		_messageOnScreen("Mode is fixed reason why 'Snpblock' is on.");
	}
}

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

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

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

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

	var chrs = new Object(JSON.parse(storage.getItem("_Chrs")));
	var minChrSwitchToSearchForm = parseInt(JSON.parse(storage.getItem("_Env")).min_chr_switch_to_search_form);
	if(minChrSwitchToSearchForm > chrs.length) return;

	_dialog_changechr();
}
*/

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

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

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

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

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

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

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

/////////////////////////////////////////////// Message on screen
function _messageOnScreen(str){
	ctx4.textAlign="left";
	ctx4.fillStyle="#ffffff";
	if(cvs4.height < 37){
		ctx4.fillRect(((cvs4.width-350)/2),1,350,11);
		ctx4.strokeStyle="#b0c4de";
		ctx4.lineWidth=2;
		ctx4.strokeRect(((cvs4.width-350)/2),1,350,11);
		ctx4.font="Bold 8px 'Century'";
		ctx4.fillStyle="#000000";
		ctx4.fillText(str,((cvs4.width-350)/2)+20,1+9);
	}else if(cvs4.height < 74){
		ctx4.fillRect(((cvs4.width-350)/2),cvs4.height/6,350,35);
		ctx4.strokeStyle="#b0c4de";
		ctx4.lineWidth=5;
		ctx4.strokeRect(((cvs4.width-350)/2),cvs4.height/6,350,35);
		ctx4.font="Bold 13px 'Century'";
		ctx4.fillStyle="#000000";
		ctx4.fillText(str,((cvs4.width-350)/2)+20,cvs4.height/6+20);
	}else{
		var errstrs = str.split("<br>");
		cvs14.width = 640;
		cvs14.height=20 + 25*errstrs.length;
		ctx14.fillStyle = "#ffffff";
		ctx14.fillRect(0,0,cvs14.width,cvs14.height);
		ctx14.strokeStyle="#b0c4de";
		ctx14.lineWidth=7;
		ctx14.strokeRect(0,0,cvs14.width,cvs14.height);
                ctx14.font="Bold 20px 'Arial'";
		if (errstrs.length > 1) {
                	ctx14.fillStyle="red";
		} else {
			if (str.match(/Invalid/)) {
				ctx14.fillStyle="red";
			} else {
                		ctx14.fillStyle="black";
			}
		}
                ctx14.textAlign="center";
		
		for (var i=0;i<errstrs.length;i++) {
			var errstr = errstrs[i];
			if (errstrs.length == 1) {
				ctx14.fillText(errstr,cvs14.width*0.5,cvs14.height*0.6-22*i);
			} else if (errstrs.length == 2) {
				
				ctx14.fillText(errstr,cvs14.width*0.5,cvs14.height*0.8-6-22*i);
			} else if (errstrs.length == 3) {
				ctx14.fillText(errstr,cvs14.width*0.5,cvs14.height*0.8-22*i);
			}
		}
                cvs15.width = 20;
                cvs15.height=20;
		ctx15.fillStyle = "gray";
		ctx15.fillRect(cvs14.width-23,3,cvs15.width,cvs15.height);
		ctx15.fillStyle="white";
		ctx15.font="Bold 20px 'Arial'";
		ctx15.fillText("x",cvs14.width-13,18)
	}
}

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

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

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

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

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

/////////////////////////////////////////////// Change color gradient from color manager
function _changeColorGradient(){
	var en=new Object(JSON.parse(storage.getItem("_Env")));
	var colorObjects=["#manager_snp_max","#manager_snp_min","#manager_indel_max","#manager_indel_min","#manager_depth_max","#manager_depth_min","#manager_cstm_max","#manager_cstm_min"];
	for(var i=0; i<colorObjects.length; i++){
		var array = colorObjects[i].split("_");
		en[array[1]+"_"+array[2]+"_col"]=$(colorObjects[i]).val();
	}
	storage.setItem("_Env",JSON.stringify(en));
	grad_DP = gra_hexcolor(en.depth_min_col,en.depth_max_col);
	grad_S = gra_hexcolor(en.snp_min_col,en.snp_max_col);
	grad_INDEL = gra_hexcolor(en.indel_min_col,en.indel_max_col);
	grad_CSTM_array[0] = gra_hexcolor(en.cstm_min_col,en.cstm_max_col);
	_drawCanvas();
}

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

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

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

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

////////////////////////////////////////////////Check confliction of feature ID on tracks.
function _trackConflict(){
	var to=new Object(JSON.parse(storage.getItem("_Tracks")));
	var track2Index = {};
	for ( var j=0, toLen=to.length; j<toLen; j++) {
		track2Index[to[j].track] = j;
	}

	var ta=_getTrack("view");
	var ret=false;
	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 ) {
				var j = track2Index[to[i].track];
				var prevRow = new Array(0,0,0,0,0);
				var prevEnd=0;
				var o=new Object(JSON.parse(storage.getItem("_Track_"+j)));
				for (var k=0, oLen=o.length; k<oLen; k++){
                                        if(parseInt(o[k].pos) < prevRow[o[k].h] && prevRow[o[k].h] != 0 && o[k].id != ""){
                                            ret=true;
                                            break;
                                        }
                                        prevRow[o[k].h] = parseInt(o[k].pos) + 100;
/*
					var end=(parseInt(o[k].rs)*Objects.BlockW)+100;
					if(((o[k].rs*Objects.BlockW) < prevRow[o[k].h]) && prevRow[o[k].h] != 0 && o[k].id != ""){
						ret=true;
					}
					prevRow[o[k].h]=end;
*/
				}
				if(ret) break;
//			}
//		}
	}
	return ret;
}

/////////////////////////////////////////////// escape HTML
function _escapeHTML(str) {
	if(typeof str != 'string') str = String(str);
	if(str == null) {
		return "";
	} else {
		return str.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
	}
}

/////////////////////////////////////////////// 
function _getVisibleArea(mode){
	var ONDIALOG=false;
/*
	if ($('#dialog_csv').is(":visible")) ONDIALOG=true;
	if ($('#dialog_fa').is(":visible")) ONDIALOG=true;
	if ($('#dialog_p3').is(":visible")) ONDIALOG=true;
	if ($('#dialog_track').is(":visible")) ONDIALOG=true;
	if ($('#dialog_reset').is(":visible")) ONDIALOG=true;
*/
	if(!ONDIALOG){
		var visibleArea = getContentVisibleArea();
		var skipTop = visibleArea.top;
		var visibleCont = visibleArea.count;
/*
		var eleCont = document.getElementById("content");
		var boundsCont = eleCont.getBoundingClientRect(); 
		var contTop = boundsCont.top;
		var eleCont2 = document.getElementById("content2");
		var boundsCont2 = eleCont2.getBoundingClientRect(); 
		var cont2Top = boundsCont2.top;
		var visible = cont2Top-contTop+parseInt(Objects.BlockH*1.5);
		var accStr = eleCont.scrollTop;
		var skipTop = parseInt(accStr/Objects.BlockH);// considering value=0
		var visibleCont = parseInt(visible/Objects.BlockH);//top +1 bottom +1
		var baseobj=new Object(_getList("db"));

		if(isNaN(skipTop)){skipTop = 1;}
		if(isNaN(visibleCont)){
			if(visibleCont > baseobj.length){
				visibleCont=baseobj.length-1;
			}else{
				visibleCont = parseInt(cont2Top/storage.getItem("_BlockH"));
			}
		}else{
			if(visibleCont > baseobj.length){
				visibleCont=baseobj.length-1;
			}else{
				visibleCont=visibleCont-1;
			}
		}
		if(skipTop==0){skipTop=1;}
*/
		VIEWSTART=skipTop;
		VIEWLEN=visibleCont;
		var str="";
		var array = new Array;
		array=_NgetList("db",skipTop,visibleCont+1,"_Lists")
		for(var i=0, arrayLen=array.length; i < arrayLen; i++){
			str = str + array[i];
			if(i != visibleCont){
				str = str + ",";
			}
		}
		storage.setItem("_ListsTgt", str);
	}
}

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

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

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

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

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

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

	for(var i=0, prmLen=prm.length; i<prmLen; i++){
		var keyVal = prm[i].split("=");
		object[keyVal[0]]=keyVal[1];
	}

	// Accessions
	if(!_isUndefined(object["acc"])){
		storage.setItem("_Ext_accessions", object["acc"]);
		_execLists();
	}

	//Position
	if(!_isUndefined(object["chr"]) && !_isUndefined(object["st"]) && !_isUndefined(object["en"])){
                if (!_isEmpty(storage.getItem("_Block"))){windowSize=storage.getItem("_Block");}
                storage.setItem("_Block", windowSize);

		_changeAutoPosZoom(object["chr"], object["st"], object["en"]);
		if(!_isUndefined(object["id"])){storage.setItem("_Keyword", object["id"]);}

		setRegionHighlight({"chr":object["chr"], "st":object["st"], "en":object["en"]});	// Region Highlight
//		addRegionHighlight({"chr":object["chr"], "st":object["st"], "en":object["en"]});	// Region Highlight
	}
	location.replace('./');
}

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

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

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

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

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

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

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


function _callDrawBLAST(str){
	var p3StrSplit = str.split("---SPL---");
	var len = p3StrSplit.length;
  	var allary = p3StrSplit[0].split("---TRK---");
  	var start = allary[1];
  	var end = allary[2];
        var chr = allary[3];
	if(!_validateChr(chr)) {
		_messageOnScreen("Invalid:this chromosomeis not registered!!");
		return;
	}
	var p3Zoom = p3StrSplit[0].replace(/---TRK---/g,"|");
	_zoomFromGffWindow(p3Zoom);

  	var blocksize = _cvtZoom(storage.getItem("_Zoom"));
  	var StartBlock=(start/blocksize)-(storage.getItem("_Pos"))+1;
  	var EndBlock=(end/blocksize)-(storage.getItem("_Pos"))+1;
  	if(StartBlock<=EndBlock){EndBlock++;}
  	rangestart = (storage.getItem("_Pos")-1) * blocksize + 1;
  	rangeend = rangestart + blocksize*100-1;
	var type = '';
	for(var i=0, arrLen=p3StrSplit.length; i<arrLen; i++) {
		if(p3StrSplit[i].match(/^lPrm\W/i) || p3StrSplit[i].match(/^rPrm\W/i)) {
			type = 'primer3';
		}
	}
	if(type == 'primer3') {
		_addPrimer3Track(str);
	} else {
		_addBlastTrack(str);
	}
}
function _validateChr(chr) {
	var validated = false;
	try {
		var chrs = JSON.parse(storage.getItem('_Chrs'));
		for(var i=0, chrsLen=chrs.length; i<chrsLen; i++) {
			if(chrs[i].id == chr) {
				validated = true;
				break;
			}
		}
	} catch(e) { }
	return validated;
}

function _addPrimer3Track(str){
  if(str) {
	var prm_Zoom = storage.getItem("_Zoom");	// '1k' '100b' etc
	var prm_Chr = storage.getItem("_Chr");
	var prm_Pos = parseInt(storage.getItem("_Pos"));
	var prm_Block = parseInt(storage.getItem("_Block"));

	var numZoom = _cvtZoom(prm_Zoom);
	var db_range_start = prm_Pos * numZoom - numZoom;
	var db_range_end = (prm_Pos + prm_Block) * numZoom;
	var prm_Tracks = str.split('---SPL---');

	var start;
	var end;
	var secstart;
	var secend;
	var idsArr = [];
	var arrStr = "";
        for(var i=0, tracksLen=prm_Tracks.length; i<tracksLen; i++) {
		var prminfos = prm_Tracks[i].split('---TRK---');
		if(prminfos[0] === "all") {
			start = parseInt(prminfos[1]);
			end = parseInt(prminfos[2]);
			var rtnArr = [];
			var rs = (start / numZoom) - prm_Pos;
			var re = (end / numZoom) - prm_Pos;
			var p1 = (start / numZoom) - prm_Pos;
			var p;
			if (end % numZoom){
				p = parseInt(end / numZoom) - prm_Pos + 1;
			} else {
				p = parseInt(end / numZoom) - prm_Pos;
			}
			if (prm_Zoom !== "1b") { 
				rs++; re++; p1++; p++;
			}
			var a1 = 0;
			var a2 = 0;
			var a3 = 0;
			var h;
			if ( p1 > a1 || a1 == null ) {
				h=1;
				a1=p;
			} else if (p1 > a2 || a2 == null ) {
				h=2;
				a2=p;
			} else if ( p1 > a3 || a3 == null ) {
				h=3;
				a3=p;
			} else {
				h=4;
			}
			arrStr = "[{\"id\":\"Primer3 Result\",\"name\":\"Primer3 Result\",\"pos\":\"" + start + "\",\"length\":\"" + (end-start+1) + "\",\"strand\":\"\",\"s\":\"" + p1 + "\",\"e\":\"" + p + "\",\"h\":\"" + h + "\",\"rs\":\"" + rs + "\",\"re\":\"" + re + "\",\"ln\":\"\"";
		} else {
			secstart = parseInt(prminfos[1]);
			secend = parseInt(prminfos[2]);
			var s = (secstart - start) / (end - start + 1) * 100;
			var l = (secend - secstart + 1) / (end - start + 1) * 100;
			idsArr.push(prminfos[0] + "-" + s + "-" + l);
		}
	}
	var data = arrStr + ",\"t\":\"" + idsArr.join(";") + "\"}]";

	var trcs = new Object(JSON.parse(storage.getItem("_Tracks")));
//	var str1 = "{\"track\":\"Primer3 Result\",\"p\":\"1\",\"h\":\"4\",\"c\":\"#0099ff\",\"s\":\"1\",\"t\":\"general\"}";
	var existRes = false;
	for (var a=0, trcslen=trcs.length; a<trcslen; a++){
		if(trcs[a].track == "Primer3 Result") {
			existRes = true;
			break;
		}
	}
	if(!existRes) trcs.push( new Object({track:"Primer3 Result", p:"1", h:"4", c:"#0099ff", s:"1", t:"general"}) );

	storage.setItem("_Tracks", JSON.stringify(trcs));
	storage.setItem("_Track_prm", data);
	storage.setItem("_Prm_str", str);
/*
    $.ajax({
	url: "./bin/"+_backendSelector("drawPrimer3.php"),
	type: "GET",
	cache: false,
	data: {
		"prm_Zoom":storage.getItem("_Zoom"),
		"prm_Chr":storage.getItem("_Chr"),
		"prm_Pos":storage.getItem("_Pos"),
		"prm_Block":storage.getItem("_Block"),
		"prm_Track": str
	},
	success: function(data) {
		var ret1="";
    		var str1="";
    		var register=1;
    		var trc = new Object(JSON.parse(storage.getItem("_Tracks")));
        	str1="{\"track\":\"Primer3 Result\",\"p\":\"1\",\"h\":\"4\",\"c\":\"#0099ff\",\"s\":\"1\",\"t\":\"general\"}";

    		var ret1="[";
    		for (var a=0;a<trc.length;a++){
      			if(trc[a].track=="Primer3 Result"){register=0;}
      			if(register == 1) {
        			ret1 += JSON.stringify(trc[a])+",";
        			if(a==trc.length-1){ret1+=str1;}
      			}
    		}
    		ret1+="]";
    		if(register==1){storage.setItem("_Tracks",ret1);}
    		storage.setItem("_Track_prm",data);
    		storage.setItem("_Prm_str",str);	
	}
    });
*/
  }
}
function _addBlastTrack(str){
  if(str) {
        var prm_Zoom = storage.getItem("_Zoom");        // '1k' '100b' etc
        var prm_Chr = storage.getItem("_Chr");
        var prm_Pos = parseInt(storage.getItem("_Pos"));
        var prm_Block = parseInt(storage.getItem("_Block"));

        var numZoom = _cvtZoom(prm_Zoom);
        var db_range_start = prm_Pos * numZoom - numZoom;
        var db_range_end = (prm_Pos + prm_Block) * numZoom;
	var blst_Tracks = str.split('---SPL---');

	var idsArr = [];
        for(var i=0, tracksLen=blst_Tracks.length; i<tracksLen; i++) {
		var blstinfos = blst_Tracks[i].split('---TRK---');
                        var start = parseInt(blstinfos[1]);
                        var end = parseInt(blstinfos[2]);
                        var rs = (start / numZoom) - prm_Pos;
                        var re = (end / numZoom) - prm_Pos;
                        var p1 = (start / numZoom) - prm_Pos;
                        var p;
                        if (end % numZoom){
                                p = parseInt(end / numZoom) - prm_Pos + 1;
                        } else {
                                p = parseInt(end / numZoom) - prm_Pos;
                        }
                        if (prm_Zoom != "1b") {
                                rs++; re++; p1++; p++;
                        }

                        var a1 = 0;
                        var a2 = 0;
                        var a3 = 0;
                        var h;
                        if ( p1 > a1 || a1 == null ) {
                                h=1;
                                a1=p;
                        } else if (p1 > a2 || a2 == null ) {
                                h=2;
                                a2=p;
                        } else if ( p1 > a3 || a3 == null ) {
                                h=3;
                                a3=p;
                        } else {
                                h=4;
                        }

                        idsArr.push(
				"{\"id\":\"Blast Result\",\"name\":\"Blast Result\",\"pos\":\"" + start + "\",\"length\":\"" + (end-start+1) + "\",\"strand\":\"\",\"s\":\"" + p1 + "\",\"e\":\"" + p + "\",\"h\":\"" + h + "\",\"rs\":\"" + rs + "\",\"re\":\"" + re + "\",\"ln\":\"\",\"t\":\"hsp-0-100\"}"
			);
        }
        var data =  "[" + idsArr.join(",") + "]";

        var trcs = new Object(JSON.parse(storage.getItem("_Tracks")));
//      var str1 = "{\"track\":\"Primer3 Result\",\"p\":\"1\",\"h\":\"4\",\"c\":\"#0099ff\",\"s\":\"1\",\"t\":\"general\"}";
        var existRes = false;
        for (var a=0, trcslen=trcs.length; a<trcslen; a++){
                if(trcs[a].track == "Blast Result") {
                        existRes = true;
                        break;
                }
        }
        if(!existRes) trcs.push( new Object({track:"Blast Result", p:"1", h:"4", c:"#0000ff", s:"2", t:"general"}));

        storage.setItem("_Tracks", JSON.stringify(trcs));
        storage.setItem("_Track_blst",data);
        storage.setItem("_Blst_str",str);
    }
}
function _execPhenotype() {
	$.ajax({
		url: "./bin/phenotype.php",
		cache: false,
		async: false,
		success: function(data) {
			storage.setItem("_Phenotypes", data);
		}
	});
}

function _getPhenotype(id) {
	var o=new Object(JSON.parse(storage.getItem("_Phenotypes")));
	if(!o || !(o instanceof Array) || o.length==0) return "";
	if (!(_isEmpty(id))) {
		return o[id].phenotype;
	}

	return o[0].phenotype;
}

function _getPhenotypeExpressions() {
	var a=new Array();
	var o=new Object(JSON.parse(storage.getItem("_PhenotypeExpressions")));
	for(var i=0;i<o.length;i++){
		if(!a[o[i].id]){
			a[o[i].id]=new Array();
		}
		if(o[i].expression == 1){
			a[o[i].id][o[i].phenotype] = true;
		}else{
			a[o[i].id][o[i].phenotype] = false;
		}
	}
	return a;
}

function _getPhenotypePapers(id, phenotype) {
	var a=new Array();
	var o=new Object(JSON.parse(storage.getItem("_PhenotypePapers")));
	for(var i=0;i<o.length;i++){
		if(o[i].id == id && o[i].phenotype == phenotype){
			a = o[i].paper;
			break;
		}
	}

	return a;
}

function _getTotalChrsSize(){
	var o = new Object(JSON.parse(storage.getItem("_Chrs")));
	var totalChrsSize = 0;
	for(var i=0;i<o.length;i++){
		totalChrsSize += parseInt(o[i].size);
	}

	return totalChrsSize;
}

function _getChrBeginPosOnAll(){
	var a = new Object();
	var o = new Object(JSON.parse(storage.getItem("_Chrs")));
	var size = 1;
	for(var i=0;i<o.length;i++){
		a[o[i].id] = size;
		size += parseInt(o[i].size);
	}

	return a;
}

function _showGWAS() {
        if(phenotypeFlg) {
                if(storage.getItem("_GWAS") == "on") {
			var color = _setColor().tracktitle;
                	$("#GWAS_plot").css('display','none');
                	$("#show_phenotype").css('display','inline');
			$("#track").css('border-bottom','1px #c3c3c3 solid');
			storage.setItem("_GWAS","off");
/*
			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);
*/
		} else if(storage.getItem("_GWAS") == "off") {
			$("#GWAS_plot").css('display','inline');
                	$("#show_phenotype").css('display','none');
			$("#track").css('border-bottom','');
			storage.setItem("_GWAS","on");
			/*
			$("#show_phenotype").empty();
			ctx14.clearRect(0, 0, cvs14.width-20, cvs14.height);
			var ongwas = $("#content").height() - $("#GWAS_plot").height();
			$("#content").css("height",ongwas);
			*/
		}
	}
	_setMenu();
}
function getRegionHighlightArray() {
  var array = [];
  var regHighlights = storage.getItem("_RegHighlights");        // ex. [{"st":20000,"en":21000,"chr":"chr01"},{"st":110000,"en":120000,"chr":"chr01"}]
  if(regHighlights != null &&  regHighlights != '') {
    try {
      var ary = JSON.parse(regHighlights);
      if(ary instanceof Array) array = ary;
    } catch(e) { }
  }
  return array;
}
function setRegionHighlightArray(array) {
  if( !(array instanceof Array) ) {
    storage.setItem("_RegHighlights", "[]");
    return;
  }
  try {
    var str = JSON.stringify(array);
    storage.setItem("_RegHighlights", str);
  } catch(e) { }
  // To reflect on Canvas, execute _drawCanvas () separately.
}
function setRegionHighlight(ref) {
  setRegionHighlightArray([ref]);
}
function addRegionHighlight(ref) {
  if("chr" in ref && "st" in ref && !isNaN(ref["st"]) && "en" in ref && !isNaN(ref["en"])) {
    var st = ref["st"];
    var en = ref["en"];
    var array = getRegionHighlightArray();
    array.push(ref);
    setRegionHighlightArray(array);
  }
  // To reflect on Canvas, execute _drawCanvas () separately.
}
function clearRegionHighlight() {
  setRegionHighlightArray(new Array());
  storage.setItem("_Keyword", "");
//  storage.setItem("_HighlightVariantGene", "");
//  storage.setItem("_HighlightVariantExclUpDown","");
  // To reflect on Canvas, execute _drawCanvas () separately.
}
function changeDialogZindex(className) {
	if(className == lastClickDialogName) return;
	lastClickDialogName = className;

        maxDialogZindex++;
        $(className).css('z-index', maxDialogZindex);
}
// for JQuery dialog only
function setClickEventToDialog(dialog, className) {
	dialog.on('mousedown',function(e1){
		changeDialogZindex(className);
	}).parent().find('.ui-dialog-titlebar').on('mousedown',function(e1){
		changeDialogZindex(className);
	});
}

////////////////////////////////////////////////////////
// Set menu bar
////////////////////////////////////////////////////////
function _setMenu(){
  // Set chromosome on main page
  var o=new Object(JSON.parse(storage.getItem("_Chrs")));
  var en=new Object(JSON.parse(storage.getItem("_Env")));
  var ld="";
  var mode_name = "";
  for (var i=0;i<o.length;i++){
    ld=ld+"<option value='"+o[i].id+"'>"+en.chromosome_name+o[i].id+"</option>";
  }
  $('#prm_chr').find('option').remove().end().append(ld);
  $('#prm_chr').val(storage.getItem('_Chr'));
  $('#menu .zoom').text("Block size "+storage.getItem('_Zoom'));
  if(!_isUndefined(Objects.Conditions)){
    if(Objects.Conditions.length > 1){
      var condArray = storage.getItem("_CrtCondition").split("|");
      var cond = parseInt(condArray[0]);
      mode_name = en.cstm_name.substr(0, 10)+" : "+Objects.Conditions[cond].id.substr(0, 10);
      //mode_name = $.format("%30s",mode_name);
    }else{
      mode_name = en.cstm_name;
    }
  }else{
    mode_name = en.cstm_name;
  }

  ///Available within 4k///
  $('#menu .one').css("color", "black");

  var onchk = "<i class=\"fa fa-circle\" aria-hidden=\"true\"></i> ";
  var offchk = "<i class=\"fa fa-circle-o\" aria-hidden=\"true\"></i> ";

  if (storage.getItem('_sFlg') == "1"){
    $('#menu .menuLisSnp').empty()
    $('#menu .menuLisSnp').append(onchk+"<i id=\"effbox\" style=\"background-color:#00ffff;width:10px;height:12px;display:inline-block;\"></i>SNP : ON (s)")
    $('#menu .menuLisSnp').css("color", "black");
  } else {
    $('#menu .menuLisSnp').empty()
    $('#menu .menuLisSnp').append(offchk+" <i id=\"effbox\" style=\"background-color:#00ffff;width:10px;height:12px;display:inline-block;\"></i>SNP : OFF (s)")
    $('#menu .menuLisSnp').css("color", "black");
  }
  if (storage.getItem('_iFlg') == "1"){
    $('#menu .menuLisIndel').empty()
    $('#menu .menuLisIndel').append(onchk+" <i id=\"effbox\" style=\"background-color:#A52A2A;width:10px;height:12px;display:inline-block;\"></i>INDEL : ON (i)")
    $('#menu .menuLisIndel').css("color", "black");
  } else {
    $('#menu .menuLisIndel').empty()
    $('#menu .menuLisIndel').append(offchk+" <i id=\"effbox\" style=\"background-color:#A52A2A;width:10px;height:12px;display:inline-block;\"></i>INDEL : OFF (i)")
    $('#menu .menuLisIndel').css("color", "black");
  }
  if (storage.getItem('_dpFlg') == "1"){
    $('#menu .menuLisDP').empty()
    $('#menu .menuLisDP').append(onchk+" <i id=\"effbox\" style=\"background-color:#b2b2b2;width:10px;height:12px;display:inline-block;\"></i>DEPTH : ON (p)")
    $('#menu .menuLisDP').css("color", "black");
  } else {
    $('#menu .menuLisDP').empty()
    $('#menu .menuLisDP').append(offchk+" <i id=\"effbox\" style=\"background-color:#b2b2b2;width:10px;height:12px;display:inline-block;\"></i>DEPTH : OFF (p)")
    $('#menu .menuLisDP').css("color", "black");
  }

  var offEff = "<table CELLSPACING=0 CELLPADDING=0 style=\"border-collapse: collapse;border-spacing: 0;\"><tr><td><i class=\"fa fa-circle-o\" aria-hidden=\"true\"></i>&nbsp;</td><td><table CELLSPACING=0 CELLPADDING=0 style=\"border-collapse: collapse;border-spacing: 0;\"><tr><td><i style=\"background-color:#00BFFF;width:5px;height:6px;display:block;\"></i></td><td><i style=\"background-color:#FFFF00;width:5px;height:6px;display:block;\"></i></td></tr><tr><td><i style=\"background-color:#EE9A00;width:5px;height:6px;display:block;\"></i></td><td><i style=\"background-color:red;width:5px;height:6px;display:block;\"></i></td></tr></table></td><td>SnpEff : OFF (e)</td></tr></table>";
  var onEff = "<table CELLSPACING=0 CELLPADDING=0 style=\"border-collapse: collapse;border-spacing: 0;\"><tr><td><i class=\"fa fa-circle\" aria-hidden=\"true\"></i>&nbsp;</td><td><table CELLSPACING=0 CELLPADDING=0 style=\"border-collapse: collapse;border-spacing: 0;\"><tr><td><i style=\"background-color:#00BFFF;width:5px;height:6px;display:block;\"></i></td><td><i style=\"background-color:#FFFF00;width:5px;height:6px;display:block;\"></i></td></tr><tr><td><i style=\"background-color:#EE9A00;width:5px;height:6px;display:block;\"></i></td><td><i style=\"background-color:red;width:5px;height:6px;display:block;\"></i></td></tr></table></td><td>SnpEff : ON (e)</td></tr></table>";

  if (storage.getItem('_Eff') == "off"){
    if(storage.getItem("_Ref") == "Reference"){
      //$('#menu .eff').text("snpEff : OFF (e)")
      $('#menu .eff').empty();
      //$('#menu .eff').append(offchk+fourblock+"snpEff : OFF (e)")
      $('#menu .eff').append(offEff);
      $('#menu .eff').css("color", "black");
    }else{
      //$('#menu .eff').text("snpEff OFF (e)")
      //$('#menu .eff').css("color", "gray");
      $('#menu .eff').empty();
      //$('#menu .eff').append(offchk+fourblock+"snpEff : OFF (e)")
      $('#menu .eff').append(offEff)
      $('#menu .eff').css("color", "black");
    }
  } else {
    //$('#menu .eff').text("snpEff ON (e)")
    //$('#menu .eff').css("color", "yellow");
    $('#menu .eff').empty();
    //$('#menu .eff').append(onchk+fourblock+"snpEff : ON (e)")
    $('#menu .eff').append(onEff)
    $('#menu .eff').css("color", "black");
  }
  if (storage.getItem('_Snpblock') == "off"){
    //$('#menu .snpblock').text("Snpblock OFF (b)")
    $('#menu .snpblock').empty()
    $('#menu .snpblock').append(offchk+"Snpblock : OFF (b)")
    //$('#menu .snpblock').css("color", "white");
    $('#menu .snpblock').css("color", "black");
  } else {
    //$('#menu .snpblock').text("Snpblock ON (b)")
    $('#menu .snpblock').empty()
    $('#menu .snpblock').append(onchk+"Snpblock : ON (b)")
    //$('#menu .snpblock').css("color", "yellow");
    $('#menu .snpblock').css("color", "black");
  }
  if (storage.getItem('_Null') == "true"){
    //$('#menu .null').text("Highlight DEPTH=NA ON (n)")
    $('#menu .null').empty()
    $('#menu .null').append(onchk+"Highlight DEPTH=NA : ON (n)")
    //$('#menu .null').css("color", "yellow");
    $('#menu .null').css("color", "black");
  } else {
    //$('#menu .null').text("Highlight DEPTH=NA OFF (n)")
    $('#menu .null').empty()
    $('#menu .null').append(offchk+"Highlight DEPTH=NA : OFF (n)")
    //$('#menu .null').css("color", "white");
    $('#menu .null').css("color", "black");
  }
  if (storage.getItem('_Amino') == "off"){
    //$('#menu .amino').text("Amino acids OFF")
    $('#menu .amino').empty()
    $('#menu .amino').append(offchk+"Amino acids : OFF")
    //$('#menu .amino').css("color", "white");
    $('#menu .amino').css("color", "black");
  } else {
    //$('#menu .amino').text("Amino acids ON")
    $('#menu .amino').empty()
    $('#menu .amino').append(onchk+"Amino acids : ON")
    //$('#menu .amino').css("color", "yellow");
    $('#menu .amino').css("color", "black");
  }
  if (storage.getItem('_Indicator') == "off"){
    //$('#menu .indicator').text("Indicator : OFF (d)")
    $('#menu .indicator').empty()
    $('#menu .indicator').append(offchk+"Indicator : OFF (d)")
    //$('#menu .indicator').css("color", "white");
    $('#menu .indicator').css("color", "black");
  } else {
    //$('#menu .indicator').text("Indicator : ON (d)")
    $('#menu .indicator').empty()
    $('#menu .indicator').append(onchk+"Indicator : ON (d)")
    //$('#menu .indicator').css("color", "yellow");
    $('#menu .indicator').css("color", "black");
  }
  if (storage.getItem('_GWAS') == "off"){
    //$('#menu .GWAS').text("Show GWAS : OFF (g)")
    $('#menu .GWAS').empty()
    $('#menu .GWAS').append(offchk+"Show GWAS : OFF (g)")
    //$('#menu .GWAS').css("color", "white");
    $('#menu .GWAS').css("color", "black");
    storage.getItem('_GWAS') == "on"
  } else {
    //$('#menu .GWAS').text("Show GWAS ON (g)")
    $('#menu .GWAS').empty()
    $('#menu .GWAS').append(onchk+"Show GWAS : ON (g)")
    //$('#menu .GWAS').css("color", "yellow");
    $('#menu .GWAS').css("color", "black");
    storage.getItem('_GWAS') == "off"
  }
  if (storage.getItem('_Onebase') == "off"){
    if(storage.getItem("_Ref") == "Reference"){
      //$('#menu .one').text("Frequency mode : ON (f)")
      $('#menu .one').empty()
      //$('#menu .one').append(onchk+"Frequency mode : ON (f)")
      //$('#menu .one').append(offchk+"Absolute Position : OFF (f)")
      $('#menu .one').append(onchk+"Block mode : ON (f)")
      //$('#menu .one').css("color", "yellow");
      //$('#menu .one').css("color", "black");
    }else{
      //$('#menu .one').text("Frequency mode : ON (f)")
      $('#menu .one').empty()
      //$('#menu .one').append(onchk+"Frequency mode : ON (f)")
      //$('#menu .one').append(offchk+"Absolute Position : OFF (f)")
      $('#menu .one').append(onchk+"Block mode : ON (f)")
      //$('#menu .one').css("color", "gray");
    }
  } else {
    if(storage.getItem("_Ref") == "Reference"){
      //$('#menu .one').text("Frequency mode : OFF (f)")
      $('#menu .one').empty()
      //$('#menu .one').append(offchk+"Frequency mode : OFF (f)")
      //$('#menu .one').append(onchk+"Absolute Position : ON (f)")
      $('#menu .one').append(offchk+"Block mode : OFF (f)")
      //$('#menu .one').css("color", "white");
      //$('#menu .one').css("color", "black");
    }else{
      //$('#menu .one').text("Frequency mode : OFF (f)")
      $('#menu .one').empty()
      //$('#menu .one').append(offchk+"Frequency mode : OFF (f)")
      //$('#menu .one').append(onchk+"Absolute Position : ON (f)")
      $('#menu .one').append(offchk+"Block mode : OFF (f)")
      //$('#menu .one').css("color", "gray");
    }
  }
  if (storage.getItem('_CSTM') == "on"){
    $('#menu .cstm').text("View "+en.cstm_name+" : ON (c)");
    $('#menu .cstm').css("color", "yellow");
    if(Objects.Conditions.length > 1){
      $('#menu .condSelect').css("color", "white");
      $("#menu .condSelect").attr({href: "javascript:_dialog_cond()"});
    }else{
      $('#menu .condSelect').css("color", "gray");
      $("#menu .condSelect").attr({href: "javascript:void(0)"});
    }
    $('#menu .color_cstm').text("Color manager");
    //$('#menu .color_cstm').css("color", "white");
    $('#menu .color_cstm').css("color", "black");
  }
  if(_trackConflict()){
    $('#menu .viewObjId').empty();
    $('#menu .viewObjId').append(offchk+"Feature IDs : ON (t)")
    $('#menu .viewObjId').css("color", "#aaaaaa");
  }else if (storage.getItem('_TrackID') == "on"){
    $('#menu .viewObjId').empty();
    $('#menu .viewObjId').append(onchk+"Feature IDs : ON (t)");
    $('#menu .viewObjId').css("color", "black");
  } else {
    $('#menu .viewObjId').empty();
    $('#menu .viewObjId').append(offchk+"Feature IDs : Off (t)");
    $('#menu .viewObjId').css("color", "black");
  }

  var regHighlightsStr = storage.getItem('_RegHighlights');
  if(regHighlightsStr && JSON.parse(regHighlightsStr).length > 0) {
    $('#menu .regHighlight').css("color", "black");
  } else {
    $('#menu .regHighlight').css("color", "#aaaaaa");
    // Link invalidation is done in _dialog_clearHighlight()
  }

  var highlightVariantGene = storage.getItem("_HighlightVariantGene");
  if(highlightVariantGene) {
    $('#menu .variantHighlight').css("color", "black");
  } else {
    $('#menu .variantHighlight').css("color", "#aaaaaa");
    // Link invalidation is done in _dialog_clearVariantHighlight()
  }

  if(isVariantFiltered()) {
    $('#menu .variantFilter').css("color", "black");
  } else {
    $('#menu .variantFilter').css("color", "#aaaaaa");
    // Link invalidation is done in _dialog_clearVariantFilter()
  }
}
function isRegionHighlighted() {
	return (storage.getItem("_RegHighlights") && JSON.parse(storage.getItem("_RegHighlights")).length>0);
}
function isVariantFiltered() {
	return (isFilteredVariantDepth() || isFilteredVariantQual() || isFilteredVariantSnpEff());
}
function isFilteredVariantDepth() {
	var dp = parseInt(storage.getItem("_DP"));
	var dp4 = parseInt(storage.getItem("_DP4"));
        return (dp !== DEF_DP) || (dp4 !== DEF_DP4);
}
function isFilteredVariantQual() {
	var qual = parseInt(storage.getItem("_QUAL"));
        return qual !== DEF_QUAL;
}
function isFilteredVariantSnpEff() {
        var effgrpsStr = storage.getItem("_EffGrps");
        var effgrps = [];
        try {
                if(effgrpsStr) effgrps = JSON.parse(effgrpsStr);
                if(effgrps.length < _getEffNoFilterArray().length) return true;
        } catch (error) {
                console.error(error);
        }
        return false;
}

