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

function _showLoadingDialog(){
	$("#dialog_progress").dialog({
		autoOpen: true,
		modal: true,
		width: 300,
//		dialogClass: 'DialogNoTitle',
		classes: { "ui-dialog": "DialogNoTitle"},
		draggable: true,
		resizable: false
	});
	_drawProgress(0);
	$('.DialogNoTitle > .ui-dialog-titlebar').css("display", "none");
}

function _drawProgress(value,start){
	var str = "";
	var $prog = $('span[id=load_progress_bar]').find('progress');
	if(_isUndefined(start)){
		_updateProgress(value);
//		str = "<progress value='"+value+"' max='100'></progress> <span>"+value+"</span>%";
//		$('span[id=load_progress_bar]').html(str);
	}else{
		var wait = 0;
		var val = start;
		for(var i=start; i<value; i++){
			wait = wait+10;
			PROGRESSTIMER = setTimeout(function(){
				val++;
				_updateProgress(val);
//				str = "<progress value='"+val+"' max='100'></progress> <span>"+val+"</span>%";
//				$('span[id=load_progress_bar]').html(str);
			},10+wait);
			if(i == (value-1)){
				BUSYDETECTTIMER = setTimeout(function(){
					var str = "<p>Although 30 seconds have been passed, the data processing has not finished yet. For resolving this problem, click the 'Reset' button and clear cached data. If the problem persists, contact administrator.</p>";
					str += "<button type=\"submit\" onclick=\"_dlg_reset_confirm();\">Reset</button>";
					str += "<button type=\"submit\" onclick=\"_closeLoadingDialog();\">Close</button>";
					$("#progress_error").html(str);
				},30000);
				//BUSYDETECTTIMER = setTimeout("_loadingError()",10000);
			}
		}
	}
}
var oriProgressStr = null;
var oriProgressError = null;
function _changeProgressStr(str, error) {
	var $p = $('#dialog_progress').find('p');
	if(!oriProgressStr) oriProgressStr = $p[0].innerHTML;
	$p[0].innerHTML = str;

	var elemProgressError = document.getElementById("progress_error");
	if(!oriProgressError) oriProgressError = elemProgressError.innerHTML;
	if(error) elemProgressError.innerHTML = error;
}
function _defProgressStr() {
	if(oriProgressStr) _changeProgressStr(oriProgressStr, oriProgressError);
//	var $p = $('#dialog_progress').find('p');
//	$p[0].innerHTML = oriProgressStr;
}
function _updateProgress(value) {
	if(value > 100) return;

	var $prog = $('span[id=load_progress_bar]').find('progress');
	$prog[0].value = value;	// Child elements are DOM, not jQuery.

	var $span = $('span[id=load_progress_bar]').find('span');
	$span[0].innerHTML = parseInt(value);
}

function _closeLoadingDialog(){
	$("#dialog_progress").dialog('close');
}

function _dialog_cond(){
	var str = "";
	var mode_name = "";
	var en = new Object(JSON.parse(storage.getItem("_Env")));
	var condArray = storage.getItem("_CrtCondition").split("|");
	var cond = parseInt(condArray[0]);

	var dialog = $("#dialog_cstm_cond").dialog({
		autoOpen: true,
		modal: false,
		width: 550,
		draggable: true,
		resizable: true,
//		dialogClass: 'ui-dialog-cstm-cond'
		classes: { "ui-dialog": "ui-dialog-cstm-cond"}
	});
	setClickEventToDialog(dialog, '.ui-dialog-cstm-cond');
	changeDialogZindex(".ui-dialog-cstm-cond");

	//select
	for (var i=0;i<Objects.Conditions.length;i++)str = str+"<option value='"+i+"'>"+_escapeHTML(Objects.Conditions[i].id)+"</option>";
	$('select[name=prm_cond_sel]').find('option').remove().end().append(str);
	$("select[name=prm_cond_sel]").val(cond);
	//state
	_setCondName();
	//slider
	$(function() {
		var select = $( "#prm_cond_sel" );
		var slider = $( "#cond_slider" ).slider({
			min: 0,
			max: Objects.Conditions.length-1,
			value: select[0].selectedIndex ,
			//orientation: "vertical",
			slide: function( event, ui ) {
				select[0].selectedIndex =  ui.value;
				condArray = storage.getItem("_CrtCondition").split("|");
				condArray[0] = parseInt( ui.value);
				storage.setItem("_CrtCondition", condArray.join("|"));
				_setCondName();
				_setCondSelect();
				_drawCanvas();
			}
		});
		$( "#prm_cond_sel" ).change(function() {
			slider.slider( "value", this.selectedIndex );
			condArray = storage.getItem("_CrtCondition").split("|");
			condArray[0] = parseInt(this.selectedIndex);
			storage.setItem("_CrtCondition", condArray.join("|"));
			_setCondName();
			_setCondSelect();
			_drawCanvas();
		});
	});

	//Multiple view
	$("#manager_cstm_max_para0").val(en.cstm_max_col);
	$("#manager_cstm_min_para0").val(en.cstm_min_col);
	$("#manager_cstm_max_para1").val(en.cstm_max_col_para1);
	$("#manager_cstm_min_para1").val(en.cstm_min_col_para1);
	$("#manager_cstm_max_para2").val(en.cstm_max_col_para2);
	$("#manager_cstm_min_para2").val(en.cstm_min_col_para2);
	$("#manager_cstm_max_para3").val(en.cstm_max_col_para3);
	$("#manager_cstm_min_para3").val(en.cstm_min_col_para3);
	str = "<option value=''>None</option>"+str;
	for (var i=0;i<condArray.length;i++){
		$('select[name=cond_select_row'+i+']').find('option').remove().end().append(str);
		$('select[name=cond_select_row'+i+']').val(condArray[i]);
		if(i == 0){
			$("select[name=cond_select_row"+i+"] option[value='']").attr("disabled", "disabled");
		}
		if(i>Objects.Conditions.length-1){
			$('select[name=cond_select_row'+i+']').attr("disabled", "disabled");
		}
	}
	_drawMulticondInd();
	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 b=0; b<colorObjects.length; b++){
		$(colorObjects[b]).ColorPicker({
			onSubmit: function(hsb, hex, rgb, el) {
				$(el).val("#"+hex);
				$(el).ColorPickerHide();
				_drawMulticondInd(1);
			},
			onBeforeShow: function () {
				$(this).ColorPickerSetColor(this.value);
			}
		}).bind('keyup', function(){
			$(this).ColorPickerSetColor(this.value);
		});
	}
	_drawCondPreview();
	/*
  if($("#cond_multi_view").is(":hidden") != true){
    $("#cond_multi_view").hide();
  }
	 */
}

function _showMultiCond(){
	if ($("#cond_multi_view").is(":hidden")) {
		$("#cond_multi_view").slideDown("fast");
		document.getElementById('cond_multi_triangle').className = "ui-icon ui-icon-triangle-1-s";
	} else {
		$("#cond_multi_view").slideUp();
		document.getElementById('cond_multi_triangle').className = "ui-icon ui-icon-triangle-1-e";
	}
}

function _setMultiCond(){
	var condArray = storage.getItem("_CrtCondition").split("|");
	for(var i=0; i<condArray.length; i++){
		var tgt = 'select[name=cond_select_row'+i+']';
		condArray[i] = $(tgt).val();
	}
	storage.setItem("_CrtCondition", condArray.join("|"));
	_setCondSelect();
}

function _setCondSelect(){
	var str = "";
	var condArray = storage.getItem("_CrtCondition").split("|");
	var cond = parseInt(condArray[0]);
	//select
	for (var i=0;i<Objects.Conditions.length;i++)str = str+"<option value='"+i+"'>"+_escapeHTML(Objects.Conditions[i].id)+"</option>";
	$('select[name=prm_cond_sel]').find('option').remove().end().append(str);
	$("select[name=prm_cond_sel]").val("");
	$("select[name=prm_cond_sel]").val(cond);
	str = "<option value=''>None</option>"+str;
	for (var i=0;i<condArray.length;i++){
		$('select[name=cond_select_row'+i+']').find('option').remove().end().append(str);
		$('select[name=cond_select_row'+i+']').val(condArray[i]);
		if(i == 0){
			$("select[name=cond_select_row"+i+"] option[value='']").attr("disabled", "disabled");
		}
		if(i>Objects.Conditions.length-1){
			$('select[name=cond_select_row'+i+']').attr("disabled", "disabled");
		}
	}
	_setCondName();
	_drawCondPreview();
	_drawCanvas();
}


function _setCondName(){
	var en = new Object(JSON.parse(storage.getItem("_Env")));
	var condArray = storage.getItem("_CrtCondition").split("|");
	var cond = parseInt(condArray[0]);
	var mode_name = en.cstm_name.substr(0, 10)+" : "+Objects.Conditions[cond].id.substr(0, 10);
	$("#cond_crt_state").text(mode_name);
}

//////////////////////////////////////////////////////////////////////////////////////
//dialog for phylogenetic analysis

function _createGffWindow(id, pos, end, seq){
	var elementTrack = document.getElementById("cvs_tracks"); 
	var elementcell = document.getElementById("cellinf"); 
	var elementcellDoc = document.getElementById("cellinf_doc"); 
	var bounds = elementTrack.getBoundingClientRect(); 
	var boux = bounds.left;
	var bouy = bounds.top;
	elementcell.style.left = (boux+XY.x1+10)+'px';
	elementcell.style.top = (bouy+XY.y1)+'px'; 
//	elementcellDoc.style.width = (230)+"px";
//	elementcellDoc.style.height = (240)+"px";
        elementcellDoc.style.width = (280)+"px";
        elementcellDoc.style.height = "auto";
	elementcellDoc.style.backgroundColor = 'white';
/*
	if(link!="http://rapdb.dna.affrc.go.jp/viewer/gene_detail/irgsp1?name="+_escapeHTML(id)) {
		link = "about:blank";
	}
*/
	var strForGff = "<div style='color:white;background-color:rgb(60,179,113)'>"+_escapeHTML(id)+"<div class='gffWindowClose' style='float:right'><span class='ui-icon ui-icon-close' onclick='_windowGffClose();'></span></div></div>"+
	"<div style='padding-left:10px;word-break:break-all;'>"+
	"<p><strong>Position</strong><br>"+
	"<span class='gffWindowStr'>"+_escapeHTML(Objects.Chr)+" "+parseInt(pos)+"-"+parseInt(end)+"</span></p>"+
	"<p><strong>Link</strong><br>";

	strForGff += "<span id=\"gffWindowLinkParent\"></span>";
/*
	if(link) {
		strForGff += "<span class='gffWindowItems'><a target='_blank' href='" + link + "'>" + _escapeHTML(id) + "</a></span>";
	} else {
		strForGff += "<span class='gffWindowStr'>" + _escapeHTML(id) + "</span>";
	}
*/
	strForGff += "</p>";

	var targetPos = _escapeHTML(id) + "|" + parseInt(pos) + "|" + parseInt(end) + "|" + _escapeHTML(Objects.Chr);	
	var cb_hlvar_exclude_updown_checked = "";
	if(storage.getItem("_HighlightVariantExclUpDown") === "1") cb_hlvar_exclude_updown_checked = "checked";

	var buttonStyle = "width:118px;";
	strForGff += "<span id='trackDetail'></span>" +
	"<p><strong>Analysis</strong><br>"+
	"<a class='phylo gffWindowItems' onclick=\"_dialog_phy('"+parseInt(pos)+","+parseInt(end)+","+_escapeHTML(id)+"');\">Phylogenetic analysis</a><br>"+
	//"<span class='gffWindowItems' onclick=\"_dialog_p3('d1|"+IDo.pos+"|"+end+"');\">Primer designing<span></p>"+
	"<p><strong>Export</strong><br>"+
	"<span class='gffWindowItems' onclick=\"_dialog_fa('" + parseInt(pos) + "," + parseInt(end) + "," + _escapeHTML(id) + "');\">FASTA</span><br>"+
	"<span class='gffWindowItems' onclick=\"_dialog_csv('"+parseInt(pos) + "," + parseInt(end) + "," +_escapeHTML(id) + "');\">TSV</span></p>"+
	"</div>"+
	"<div style=\"border:solid 1px #AAAAAA;padding:4px;margin:5px;text-align:right;\">" +
	"<label for=\"cb_hlvar_exclude_updown\"><input type=\"checkbox\" id=\"cb_hlvar_exclude_updown\" " + cb_hlvar_exclude_updown_checked + ">Exclude UP/DOWN</label> " +
	"<button onclick=\"_highlightGeneVariant('" + targetPos + "')\" style=\"" + buttonStyle + "\">Highlight variant</button>";

	if(id === storage.getItem("_HighlightVariantGene")) {
		strForGff += "<button onclick=\"_clearHighlightedVariantAndCloseDialog()\" style=\"margin-top:3px;" + buttonStyle + "\">Clear highlight</button>";
	}

	strForGff += "</div>" +
	"<div style='text-align:center;margin-bottom:4px;'>" +
	"<button onclick=\"_zoomFromGffWindow('" + targetPos + "')\">Zoom</button>" +
	"<div>";
	elementcellDoc.innerHTML = strForGff;
	elementcellDoc.style.border = "solid 2px #b0c4de"; 

        $.ajax({
                url: "./bin/targetTrack.php",
                cache: false,
                async: false,
                data: {
                        "prm_Seq": seq
                },
                success: function(data) {
                        if(data != null && data != "") {
                            json = JSON.parse(data);
                            var link = "";
                            var linkId = IDo.ln;
                            if(json.others != "") {
				var othersArray = json.others.split(';');
				var othersMap = {};
				var infoHtml = "";
				var flgDirectDisp = false;
				var flgIndent = false;
/*
				if(othersArray.length === 1) {
					// Plain String
					infoHtml = _escapeHTML(decodeGffAttribute(json.others)) + "<br>";
					flgIndent = true;
					if(json.others.length<110) flgDirectDisp = true;

					var keyVal = othersArray[0].split('=');
					keyVal[0] = decodeGffAttribute(keyVal[0]);
					keyVal[1] = decodeGffAttribute(keyVal[1]);
					othersMap[keyVal[0]] = keyVal[1];
				} else {
*/
					// Table
					flgIndent = false;
					if(othersArray.length<4) flgDirectDisp = true;
					infoHtml += "<table id='gffInfoTable'>";
					for(var i=0,othersArrayLen=othersArray.length; i<othersArrayLen; i++) {
						if(!othersArray[i]) continue;
						var keyVal = othersArray[i].split('=');
						if(keyVal.length == 1) keyVal.unshift("---");
						keyVal[0] = decodeGffAttribute(keyVal[0]);
						keyVal[1] = decodeGffAttribute(keyVal[1]);
						infoHtml += "<tr><th style='width:35%;padding:3px;'>" + _escapeHTML(keyVal[0]) + "</th>" + 
							"<td style='padding:3px;'>" + _escapeHTML(keyVal[1]) + "</td></tr>";
						othersMap[keyVal[0]] = keyVal[1];
					}
					infoHtml += '</table>';
//				}
                                var html = "<p><div style='display: inline-block; _display: inline;'><strong>Information</strong></div><br>";
//				var contentClass = "";
//				if(flgIndent) contentClass += 'gffWindowStr';
				html += infoHtml;

				// Can get table-height after rendering.
                                document.getElementById("trackDetail").innerHTML = html;

				// Set Event for resize of information table;
				var minTableHeight = 80;
				var $infoTable = $("#gffInfoTable");
				var infoTableHeight = $infoTable.height();
				if(infoTableHeight > minTableHeight) {
					// To resize and scroll at the same time, need a double div
					$infoTable.wrap("<div id='gffInfoTableDivChild' style='overflow-y:scroll;'></div>");
					$("#gffInfoTableDivChild").wrap("<div id='gffInfoTableDiv' style='overflow-y:hidden;'></div>");
					$("#gffInfoTableDiv").resizable({
					        "handles":"s",
					        "minHeight":minTableHeight,
					        "maxHeight":infoTableHeight + 5,
						"resize": function(e, ui) {
							$("#gffInfoTableDivChild").height( $(this).height());
						}
					});
					$("#gffInfoTableDiv .ui-resizable-s").css('bottom', '0px');
					$("#gffInfoTableDiv").css('height', minTableHeight + 'px');
					// Make the table wrapper(#gffInfoTableDivChild) the same size as the resizable region and display the scrollbar.
					$("#gffInfoTableDivChild").height( $("#gffInfoTableDiv").height());
				} else {
					// Just put right-space.
					$infoTable.wrap("<div style='padding-right:3px;'></div>");
				}

				if(IDo.track != null) {
					var tracks = new Object(JSON.parse(storage.getItem('_Tracks')));
					var env = new Object(JSON.parse(storage.getItem("_Env")));
					var trackName = tracks[IDo.track].track;
					if(env['external_sites'] && (typeof env['external_sites'])=='object' && Object.keys(env['external_sites']).length>0) {
						var trackMap = env['external_sites'];
						if(trackMap[trackName] && trackMap[trackName].link) {
							var trackSite = trackMap[trackName];
							if(trackSite['tag_gff'] && trackSite['tag_gff'] in othersMap) linkId = othersMap[trackSite['tag_gff']];
							link = _makeLinkUrl(trackSite.link, trackSite.suffix, linkId);
						}
					} else if(env.external_link) {
						if(env['external_link_tag_gff'] && env['external_link_tag_gff'] in othersMap) linkId = othersMap[env['external_link_tag_gff']];
						link = _makeLinkUrl(env.external_link, env.external_link_suffix, linkId);
					}
				}
                            }
                            if(link) {
				document.getElementById("gffWindowLinkParent").innerHTML = "<span class='gffWindowItems'><a target='_blank' href='" +  link + "'>" + _escapeHTML(linkId) + "</a></span>";
                            } else {
				document.getElementById("gffWindowLinkParent").innerHTML = "<span class='gffWindowStr'>" + _escapeHTML(linkId) + "</span>";
                            }
                        }
                }
        });
}
function _makeLinkUrl(link, suffix, id) {
	var url = link + id + suffix;
	return _escapeHTML(url);
}
//////////////////////////////////////////////////////////////////////////////////////
function _clearHighlightedVariantAndCloseDialog() {
	_windowGffClose();
	_clearHighlightedGeneVariant();
}
//dialog for phylogenetic analysis
//var idlst_mode = "sort";
var _dialog_phy_obsSet = false;
function _dialog_phy(str){
	/*
	$("#dialog_phy").dialog({
		autoOpen: true,
		modal: false,
		width: 880,
		maxHeight: window.innerHeight-15,
		draggable: true,
		resizable: true,
                position: {
                        of:'body',
                        at:'top',
                        my:'center'
                }
	});
	*/

	if(!_dialog_phy_obsSet) {
		var resizeObserver = new ResizeObserver(function(entries) {
			var myself = $("#dialog_phy");
			var w = parseInt(myself.innerWidth());
			$("#phy_acc_tabulator").width(w - 105 - 55);
		});
		resizeObserver.observe(document.querySelector('#dialog_phy'));
		_dialog_phy_obsSet = true;
	}

	var phyloflg = '';
	var phylopos = '';
        for(var i=0; i<minPos.length; i++) {
            if(minPos[i] == 'phylo') {
                    phylopos = i;
                    phyloflg = 1;
            }
        }
	if(phyloflg==1) {
        	for(var i=phylopos; i<minPos.length; i++) {
            		if (minPos[i+1] !== undefined) {
                    		minPos[i] = minPos[i+1];
            		} else {
                		minPos.pop();
            		}
            		leftpos = (parseInt(175)*(parseInt(i))+ parseInt(5)*(parseInt(i+1)))+'px';
            		$("."+minPos[i+1]+"_window").css('left',leftpos);
        	}
	}

        var phydlgH = $("#tasuke").height()-20;
        if (phydlgH > 786 ) {
                phydlgH = 785;
        }
        $("#dialog_phy").css('height',phydlgH);
        $(".phylo_content").css('height',phydlgH-43);
	$("#dialog_phy").css('max-height', 927);
	$(".phylo_content").css('max-height', 927-43);
//        $("#dialog_phy").css('max-height', 785);
//        $(".phylo_content").css('max-height', 785-43);
        $("#dialog_phy").css('display','inline-block');

        if($(".under_phy").hasClass('fa-window-restore')){
                $(".under_phy").toggleClass('fa-window-restore fa-window-minimize');
        }

	//var phyWindowW =  $(".phylo_window").attr("width");
        if($("#dialog_phy").hasClass('minimized')){
                $("#dialog_phy").toggleClass('minimized');
                $("#dialog_phy").css('top','0px');
                //$("#dialog_phy").css('position','fixed');
		$("#dialog_phy").css('min-height','42px');
		$("#dialog_phy").css('min-width','268px');
                $(".phylo_content").css('display','inline-block');
                $(".phylo_content").css('background-color','white');
                $("#dialog_phy").css('width','990px');	// <- 900
                $("#phylo_title").css('width','982px');	// <- 892
                $("#phylo_title").css('max-width','982px');	// <= 892
                $("#phylo_title").css('min-width','260px');
                $(".phylo_content").css('width','982px');	// <- 892
                $("#phylo_title").css('top','4px');
                $("#phylo_title").css('left','4px');
                $("#dialog_phy .minimize").css('top','9px');
                $("#dialog_phy .close").css('top','9px');
		document.getElementById("tname").innerHTML = "&nbsp;&nbsp;Phylogenetic tree";
                document.getElementById("tname").style.fontSize = "20px";
        }

	changeDialogZindex(".phylo_window");
/*
        winFront[winFront.length] = 'phylo';
        for (var i = 0; i < winFront.length; i++) {
                $("."+winFront[i]+"_window").css('z-index',1000+i);
        }
*/
	var blk = storage.getItem("_Block");
	var s = parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
	var e = s+(blk*_cvtZoom(Objects.Zoom))-1;

	var highlightRegions;
	try { highlightRegions = JSON.parse(storage.getItem("_RegHighlights")); } catch (e) {}
	if( !(highlightRegions instanceof Array) ) highlightRegions = [];

	var id = "";
	var cri = document.getElementById("prm_phy_cri");
	if(str){
		var params = str.split(",");
		s = parseInt(params[0]);
		e = parseInt(params[1]);
		id = _escapeHTML(params[2]);
		$("#prm_phy_objid").val(id);
		document.getElementById("prm_phy_gene").checked = true;
		cri.options[1].selected = true;
	} else {
		if(highlightRegions.length > 0 && highlightRegions[0].chr == Objects.Chr) {
			s = parseInt(highlightRegions[0].st);
			e = parseInt(highlightRegions[0].en);
		}
		$("#prm_phy_objid").val("");
		document.getElementById("prm_phy_gene").checked = false;
		cri.options[0].selected = true;
	}
	if((e-s) >= 19999){e=s+19999;} 
	$("#prm_phy_s").val(s);
	$("#prm_phy_e").val(e);

	// Set parameters
	var o = new Object(JSON.parse(storage.getItem("_Chrs")));
	var en = new Object(JSON.parse(storage.getItem("_Env")));
	var ld="";
	var sl = document.getElementById("flk_len_phy");
	var res = document.getElementById("phy_result");
	var len = e-s+1;

	for (var i=0; i<o.length; i++) ld = ld+"<option value='"+o[i].id+"'>"+en.chromosome_name+o[i].id+"</option>";
	$('#prm_phy_chr').find('option').remove().end().append(ld);
	$("#prm_phy_chr").val(Objects.Chr);
	$("#prm_phy_qual").val(storage.getItem("_QUAL"));
	$("#prm_phy_dp").val(storage.getItem("_DP"));
	$("#prm_phy_list").val(_getList("db"));

        _appendTitleWOption();
	$('#prm_tw').val(storage.getItem('_TitleW'));
        $('#prm_switch_name').val(storage.getItem('_Name'));
        $('#prm_switch_sub').val(storage.getItem('_NameSub'));

	$("#idlst").resizable({
		"handles":"s",
		"minHeight":100,
		"maxHeight":500,
		"alsoResize":"#tree_qry"
	});
      
	if(isTreeUsing() && storage.getItem('_AccmanagerListType') !== 'standard') {
		setRadioGroupValue("idlst_grp", "tree");
	} else {
		setRadioGroupValue("idlst_grp", "sort");
	}

	// Deselect lists
	$("#idlst").val([]);
	$("#tree_qry").val([]);

	var lists = getListsForSystemTree();
	_dlg_make_phylist(lists);

	if (len > 20000){
		len = 20000;
	}else if (len < 0){
		len = 0;
	}
	sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+parseInt(len)+"&nbsp;bp";
	res.innerHTML = "";
//	_dialog_phy_len();
	_changePosID();
//	_setClickPhenotypePhyloEvent();

	$("#prm_phy_method").val("bin");
	$("#prm_phy_method_s").prop('checked', true);
	$("#prm_phy_method_i").prop('checked', true);
	$("#prm_phy_method_d").prop('checked', true);
	_changePhyMethod();

	if(phyListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		phyListManager.clearHistory();
//		phyListManager.clearSearchHit();
		phyListManager.syncList2SearchSelect2();
		phyListManager.syncBtnMoveRow();
		phyListManager.scrollToTop();
		$('#phy_std_selectCangeViewMode').val("");

		$('#phy_std_AllRows').text(_getAccListObjArray('_Lists-origin').length);
	}

	$(".phylo_content").scrollTop(0);
}

//////////////////////////////////////////////////////////////////////////////////////
//sequence length for phylogenetic analysis
/*
function _param_display_phy(){
	var dp = document.getElementById("prm_phy_dp");
	var q = document.getElementById("prm_phy_qual");
	var qualmsg = document.getElementById("flk_qual_phy");
	var dpmsg = document.getElementById("flk_dp_phy");
	var sub = document.getElementById("phy_submit");
	
	var vdp = dp.value;
	var vq = q.value;
	var flgPass = false;

	if(dp.checkValidity() && q.checkValidity() && vdp>=0 && vq>=0){
		qualmsg.innerHTML = "";
		dpmsg.innerHTML = "";
		sub.disabled = false;
		flgPass = true;
	} else {
		if (!dp.checkValidity() || vdp<0) {
			dpmsg.innerHTML = "<font color=\"#FF0000\">DEPTH value is invalid!</font>";
		} else {
			dpmsg.innerHTML = "";
		}

		if ( !q.checkValidity() || vq<0) {
			qualmsg.innerHTML = "<font color=\"#FF0000\">Quality value is invalid!</font>";
		} else {
			qualmsg.innerHTML = "";
		}
		sub.disabled = true;
	}
	return flgPass;
}
*/
var valgene_cache_phy = {};
function _dialog_phy_len(){
	var s = document.getElementById("prm_phy_s");
	var e = document.getElementById("prm_phy_e");
	var dp = document.getElementById("prm_phy_dp");
	var q = document.getElementById("prm_phy_qual");
	var sub = document.getElementById("phy_submit");
	var sl = document.getElementById("flk_len_phy");
	var idmsg = document.getElementById("phy_id_msg");
	var vdp = dp.value;
	var vq = q.value;
	var len = parseInt(e.value) - parseInt(s.value) + 1;
	var sv =s.value;
	var ev =e.value;
	var phy_method = document.getElementById("prm_phy_method").value;
	var vtype_s = document.getElementById("prm_phy_method_s").checked;
	var vtype_i = document.getElementById("prm_phy_method_i").checked;
	var vtype_d = document.getElementById("prm_phy_method_d").checked;
	idmsg.innerHTML = "";
	var passed = -1;

/*
	var en = JSON.parse(storage.getItem("_Env"));
	var submsg = document.getElementById("phy_sub_msg");
	if(phy_method === 'bin') {
		// Binary distance.
		if(!en['phyTools']['neighbor']) {
			submsg.innerHTML = "Phylip path ";
			sub.disabled = true;
		} else if(!en['phyTools']['makeBinaryDistanceMatrix']){
			sub.disabled = true;
		} else {
			sub.disabled = false;
			passed = -1;
		}
	} else {
		// DNA distance.
	}
*/
	if(passed == -1) {
		if(vtype_s || vtype_i || vtype_d) {
			document.getElementById("flk_prm_phy_method").innerHTML = "";
			sub.disabled = false;
			passed = 0;
		} else {
			document.getElementById("flk_prm_phy_method").innerHTML = "Please select one of the variant types.";
			sub.disabled = true;
		}
	}
	if(passed == 0) {
		if(s.checkValidity() && e.checkValidity() && sv!=0 && ev!=0 && len > 0 && len <= 20000){
			sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+parseInt(len)+"&nbsp;bp";
			sub.disabled = false;
			passed = 1;
		} else {
			if (!s.checkValidity() || !e.checkValidity()) {
				len="<font color=\"#FF0000\">Please input postion!</font>";
				sl.innerHTML = len;
				sub.disabled = true;
			} else if (len > 20000){
				len = 20000;
				e.value=(parseInt(sv)+19999);
				sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+parseInt(len)+"&nbsp;bp";
			} else if (len <= 0){
				//len = 0;
				len="<font color=\"#FF0000\">Please check start-postion and end-postion.</font>";
				//sl.innerHTML = parseInt(len);
				sl.innerHTML = len;
				sub.disabled = true;
			}
		}
	}
        if (passed == 1) {
//		var flgPass = _param_display_phy();
//		if(flgPass) passed = 2; 

                var qualmsg = document.getElementById("flk_qual_phy");
                var dpmsg = document.getElementById("flk_dp_phy");

                if(dp.checkValidity() && q.checkValidity() && vdp>=0 && vq>=0){
                        qualmsg.innerHTML = "";
                        dpmsg.innerHTML = "";
                        sub.disabled = false;
			passed = 2;
                } else {
                        if (!dp.checkValidity() || vdp<0) {
                                dpmsg.innerHTML = "<font color=\"#FF0000\">DEPTH value is invalid!</font>";
                        } else {
				dpmsg.innerHTML = "";
			}

			if ( !q.checkValidity() || vq<0) {
                                qualmsg.innerHTML = "<font color=\"#FF0000\">Quality value is invalid!</font>";
                        } else {
				qualmsg.innerHTML = "";
			}
			sub.disabled = true;
                }
        }
        if (passed == 2) {
                if(document.getElementById("prm_phy_cri").value == 1) {
                        var objidv = document.getElementById("prm_phy_objid").value;
                        if(objidv == "") {
                                idmsg.innerHTML = "<font color=\"#FF0000\">Input a annotaion id for phylogenetic analysis.</font>";
				sub.disabled = true;
                        } else if(objidv.indexOf('<script>') != -1){
                                idmsg.innerHTML = "<font color=\"#FF0000\">Input paramater is invalid.</font>";
				sub.disabled = true;
                        } else {
				// Get gene info by Ajax and set it in form.
				var callback = function(valgene) {
					var cdslen = [];
					var idmsg = document.getElementById("phy_id_msg");
					var sub = document.getElementById("phy_submit");
					if (!valgene['valid']) {
						idmsg.innerHTML = "<font color=\"#FF0000\">This Feature ID is invalid.</font>";
						sub.disabled = true;
						valgene_cache_phy = {};	// Global var
					} else {
						var chr = valgene['chr'];
						var st = valgene['start'];
						var ed = valgene['end'];
						cdslen = valgene['regs'];
						if('cds' in cdslen) {
							$("#prm_phy_gene").prop('disabled', false);
							if ($("#prm_phy_gene").prop("checked")) {
								len = parseInt(cdslen['cds']['len']);
							} else {
								len = parseInt(ed) - parseInt(st) + 1;
							}
						} else {
							$("#prm_phy_gene").prop('disabled', true);
							$("#prm_phy_gene").prop("checked", false);
							len = parseInt(ed) - parseInt(st) + 1;
						}
						$("#prm_phy_chr").val(chr);
						$("#prm_phy_s").val(st);
						$("#prm_phy_e").val(ed);
						idmsg.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+parseInt(len)+"&nbsp;bp";
						sub.disabled = false;
						valgene_cache_phy = valgene;	// Global var
					}

                                };
				if('gene' in valgene_cache_phy && objidv === valgene_cache_phy['gene']) {
					callback(valgene_cache_phy);
				} else {
					_validateGene(objidv, callback);
				}
                        }
                }
        }
}

function _changePosIDCsv() {
	// For export Variant tsv function
	var elmid = document.getElementById("prm_csv_keyword");
	var elmchr = document.getElementById("prm_csv_chr");
	var elms = document.getElementById("prm_csv_s");
	var elme = document.getElementById("prm_csv_e");

	var choosePos = document.getElementById("choose_pos");
	if(choosePos.checked) {
		// Position
		elmchr.disabled = false;
		elms.disabled = false;
		elme.disabled = false;
		elmid.disabled = true;
                elmid.value = "";
	} else {
		//GeneID
		elmchr.disabled = true;
		elms.disabled = true;
		elme.disabled = true;
		elmid.disabled = false;
	}
	_dialog_csv_len();
}
function _changePhyMethod() {
	var sel = document.getElementById("prm_phy_method");
	var divdna = document.getElementById("prm_phy_method_div_dna");
	var divbin = document.getElementById("prm_phy_method_div_bin");

	if(sel.value === 'bin') {
		// Binary distance.
		$("#prm_phy_method_div_dna").hide();
		$("#prm_phy_method_div_bin").show(); 
	} else {
		// DNA distance.
		$("#prm_phy_method_div_dna").show();
		$("#prm_phy_method_div_bin").hide();
	}
}
function _changePhyMethodVType(form) {
/*
	var vs = document.getElementById("prm_phy_method_s").checked;
	var vi = document.getElementById("prm_phy_method_i").checked;
	var vd = document.getElementById("prm_phy_method_d").checked;

	if(!vs && !vi && !vd) {
		document.getElementById("flk_prm_phy_method").innerHTML = "Please select one of the variant types.";
	} else {
		document.getElementById("flk_prm_phy_method").innerHTML = "";
	}
*/
	_dialog_phy_len();
}
function _changePosIDFa() {
	// For export fasta function.
	_changePosIDCore('fa');
	_dialog_fa_len();
}

function _changePosID() {
	// For phylogenetic tree function.
	_changePosIDCore('phy');
	var elmgene = document.getElementById("prm_phy_gene");
	var elmcri = document.getElementById("prm_phy_cri");
	if (elmcri.value == 0) {
		elmgene.checked = false;
	} else {
		elmgene.checked = true;
	}
	_dialog_phy_len();
}

/**
 * type: 'fa' or 'phy'
**/
function _changePosIDCore(type) {
	var elmcri = document.getElementById("prm_" + type + "_cri");
	var elmgene = document.getElementById("prm_" + type + "_gene");
//        if (elmcri.value == 0 && elmgene.checked === true) {
//                elmgene.checked = false;
//        }

        var elmid = document.getElementById("prm_" + type + "_objid");
        var elmchr = document.getElementById("prm_" + type + "_chr");
        var elms = document.getElementById("prm_" + type + "_s");
        var elme = document.getElementById("prm_" + type + "_e");
	var sl = document.getElementById("flk_len_" + type);
	var sub = document.getElementById(type + "_submit");
        if(elmcri.value == 0){
                elmchr.disabled = false;
                elms.disabled = false;
                elme.disabled = false;
                elmid.disabled = true;
                elmgene.disabled = true;
                elmid.value = "";
                $("#" + type + "_id_msg").empty();
        }else{
		elmchr.disabled = true;
		elms.disabled = true;
		elme.disabled = true;
                elmid.disabled = false;
                elmgene.disabled = false;
                if (elmid.value == "") {
			$("#" + type + "_id_msg").append("<font color=\"#FF0000\">Input a gene id.</font>");
//                        $("#" + type + "_id_msg").append("<font color=\"#FF0000\">Input a annotaion id for phylogenetic analysis.</font>");
                }
		sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;" + (parseInt(elme.value) - parseInt(elms.value) + 1) + "&nbsp;bp";
        }
}
//////////////////////////////////////////////////////////////////////////////////////
//  dialog "BLAST" add kasadera
//////////////////////////////////////////////////////////////////////////////////////
function _dialog_blast(primer3ArrayForBLASTLeft,primer3ArrayForBLASTRight,p3_track){
  /*
  $("#dialog_blast").dialog({
    autoOpen: true,
    modal: false,
    width: 850,
    maxHeight: window.innerHeight-15,
    draggable: true,
    resizable: true,
    position: {
    	of:'body',
        at:'top',
        my:'center'
    }
  });
  */
        storage.setItem("_runBlast",0);
        
	var blastpos = '';
	var blastflg = '';
        for(var i=0; i<minPos.length; i++) {
            if(minPos[i] == 'blast') {
                    blastpos = i;
                    blastflg = 1;
            }
        }
	if (blastflg == 1) {
        	for(var i=blastpos; i<minPos.length; i++) {
            		if (minPos[i+1] !== undefined) {
                	    minPos[i] = minPos[i+1];
            		} else {
                	    minPos.pop();
            		}
			leftpos = (parseInt(175)*(parseInt(i))+ parseInt(5)*(parseInt(i+1)))+'px';
            		$("."+minPos[i+1]+"_window").css('left',leftpos);
        	}
	}
	changeDialogZindex(".blast_window");	
/*
	winFront[winFront.length] = 'blast';
	for (var i = 0; i < winFront.length; i++) {
		$("."+winFront[i]+"_window").css('z-index',1000+i);
	}
*/
	$("#blastSetting").slideUp();
        $('#blst_opt.open').toggleClass('open close');
        $('#blst_opt.close').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-e');
        $('#blst_opt.close').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
        $("#blastHistArea").slideUp();
        $('#blst_hist.open').toggleClass('open close');
        $('#blst_hist.close').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-e');
        $('#blst_hist.close').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');

        $(".blast_window").css('height', '372px');
        $(".blast_content").css('height', '329px');
        $(".blast_window").css('max-height', '372px');
        $(".blast_content").css('max-height', '329px');

	$(".blast_window").css('display','inline-block');
	$('#p3result').remove();
        if($(".under_blast").hasClass('fa-window-restore')){
		$(".under_blast").toggleClass('fa-window-restore fa-window-minimize');
        }
        if($("#dialog_blast").hasClass('minimized')){
                $("#dialog_blast").toggleClass('minimized');
                $("#dialog_blast").css('top','0px');
                //$("#dialog_blast").css('position','fixed');
                $(".blast_content").css('display','inline-block');
                $("#dialog_blast").css('width','800px');
		$(".blast_content").css('width','796px');
                $("#blast_title").css('width','788px');
                $("#blast_title").css('max-width','788px');
		$("#dialog_blast").css('min-width','178px');
		$("#dialog_blast").css('min-height','42px');
                $("#blast_title").css('top','4px');
                $("#blast_title").css('left','4px');
                $("#dialog_blast .minimize").css('top','9px');
                $("#dialog_blast .close").css('top','9px');
		document.getElementById("bname").innerHTML = "&nbsp;&nbsp;BLAST";
                document.getElementById("bname").style.fontSize = "20px";
		$("#dialog_blast").css('height','');
        }
	if(primer3ArrayForBLASTLeft === undefined) {
        	blastQryArea="<textarea id=\"blast_qryarea\" cols=60 rows=4></textarea>";
	}else {
        	blastQryArea="<textarea id=\"blast_qryarea\" cols=60 rows=4>"+">left\n"+primer3ArrayForBLASTLeft+"\n"+">Right\n"+primer3ArrayForBLASTRight+"</textarea>";
	}
	$('#blastQry').html(blastQryArea);
	$('#p3result').empty();
	$('#dialog_blast').append("<input type=\"hidden\" id=\"p3result\" value=\""+p3_track+"\">");
	_sessionBlastStart();
};

function _dialog_blast_len(){
        var ws = document.getElementById("blast_word_size");
        var mm = document.getElementById("max_matches");
        var ev = document.getElementById("blast_eval");
        var wsm = document.getElementById("bls_ws_msg");
        var mmm = document.getElementById("bls_mm_msg");
        var evm = document.getElementById("bls_ev_msg");
        var sub = document.getElementById("blast_submit");
        var wsv = ws.value;
        var mmv = mm.value;
        var evv = ev.value;
        var passed = 0;
        if(ws.checkValidity() && mm.checkValidity() && ev.checkValidity() && wsv>=1 && mmv>=0 && evv>0){
                wsm.innerHTML = "";
                mmm.innerHTML = "";
                evm.innerHTML = "";
                sub.disabled = false;
//                sub.innerHTML = "<button type=\"submit\" name=\"blast_submit\" onclick=\"_runBlast();\">Run</button>";
                passed = 1;
        } else {
                if (!ws.checkValidity()) {
                        wsm.innerHTML = "<font color=\"#FF0000\">Please input word size!</font>";
                } else {
			wsm.innerHTML = "";
		}

		if (!mm.checkValidity()) {
                        mmm.innerHTML = "<font color=\"#FF0000\">Please input max matches!</font>";
                } else {
			mmm.innerHTML = "";
		}

		if (!ev.checkValidity() || !isFinite(evv) || evv<0) {
                        evm.innerHTML = "<font color=\"#FF0000\">Please input E-value!</font>";
                } else {
			evm.innerHTML = "";
		}
		sub.disabled = true;
        }
}

//dialog "_dialog_primer3"
function _dialog_p3(str){
	/*
	$("#dialog_p3").dialog({
		autoOpen: true,
		modal: false,
		width: 800,
		maxHeight: window.innerHeight-15,
		draggable: true,
		resizable: true,
		position: {
			of:'body',
			at:'top',
			my:'center'
		}
	});
	*/
	var p3pos = '';
	var p3flg = '';
        for(var i=0; i<minPos.length; i++) {
            if(minPos[i] == 'p3') {
                    p3pos = i;
                    p3flg = 1;
            }
        }
	if(p3flg == 1) {
        	for(var i=p3pos; i<minPos.length; i++) {
            		if (minPos[i+1] !== undefined) {
                	    minPos[i] = minPos[i+1];
            		} else {
                	    minPos.pop();
            		}
            		leftpos = (parseInt(175)*(parseInt(i))+ parseInt(5)*(parseInt(i+1)))+'px';
            		$("."+minPos[i+1]+"_window").css('left',leftpos);
        	}
	}

        $("#dialog_p3").css('height',$("#tasuke").height()-20);
        $(".p3_content").css('height',$("#tasuke").height()-63);

        $("#dialog_p3").css('max-height', "1240px");
        $(".p3_content").css('max-height', "1197px");
//        $(".p3_content").css('max-height',$("#tasuke").height()-60);
//        $("#dialog_p3").css('max-height',$("#tasuke").height()-22);

	$(".p3_window").css('display','inline-block');
        if($(".under_p3").hasClass('fa-window-restore')){
                $(".under_p3").toggleClass('fa-window-restore fa-window-minimize');
        }
	if($("#dialog_p3").hasClass('minimized')){
		$("#dialog_p3").toggleClass('minimized');
        	$("#dialog_p3").css('top','0px');
        	//$("#dialog_p3").css('position','fixed');
        	$(".p3_content").css('display','inline-block');
		$("#dialog_p3").css('width','800px');
		$("#dialog_p3").css('min-height','34px');
		//$("#dialog_p3").css('max-width','800px');
		$("#dialog_p3").css('min-width','286px');
		$(".p3_content").css('width','800px');
		$(".p3_content").css('max-width','800px');
		$(".p3_content").css('min-width','286px');
		$("#p3_title").css('width','792px');
		$("#p3_title").css('max-width','792px');
		$("#p3_title").css('min-width','284px');
		$("#p3_title").css('left','4px');
		$("#p3_title").css('top','4px');
                $("#dialog_p3 .minimize").css('top','7px');
                $("#dialog_p3 .close").css('top','7px');
		document.getElementById("p3name").innerHTML = "&nbsp;&nbsp;Primer designing";
		document.getElementById("p3name").style.fontSize = "20px";
	}
	changeDialogZindex(".p3_window");
/*
        winFront[winFront.length] = 'p3';
        for (var i = 0; i < winFront.length; i++) {
                $("."+winFront[i]+"_window").css('z-index',1000+i);
        }
*/	
        //define target site
	var blk=storage.getItem("_Block");
	var highlightRegions;
	try { highlightRegions = JSON.parse(storage.getItem("_RegHighlights")); } catch (e) {}
	if( !(highlightRegions instanceof Array) ) highlightRegions = [];
	dlgchk = str.split("---BLS---");
	var s = parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
	var e = s+(blk*_cvtZoom(Objects.Zoom))-1;
	if((e-s) >= 99){e=s+99;}
	if(!isNaN(dlgchk[1]) && !isNaN(dlgchk[2])) {
		// Pick primers
		s = parseInt(dlgchk[1]);
		e = parseInt(dlgchk[2]);
	} else if(highlightRegions.length > 0) {
		// Highlight region
		if(highlightRegions[0].chr == Objects.Chr) {
			s = parseInt(highlightRegions[0].st);
			e = parseInt(highlightRegions[0].en);
		}
	}
	$("#prm_rp3_tgt").val(s);
	$("#prm_rp3_tgt_e").val(e);
	$("#prm_p3_tgt").val(s);
	$("#prm_p3_tgt_e").val(e);

	var minProductSize = e - s + 1;
		if(minProductSize < 100) minProductSize = 100;
	var maxProductSize = 500 + minProductSize + 500;
	        if(maxProductSize > 50000) maxProductSize = 50000;

	$("#prm_rp3_prdmi").val(minProductSize);
	$("#prm_rp3_prdmx").val(maxProductSize);
        $("#prm_epcr_prdmi").val(minProductSize);
        $("#prm_epcr_prdmx").val(maxProductSize);

	//for exporting sequence 
	var strarray = str.split("|");
	var variant=strarray[3];
	var q=storage.getItem("_QUAL");
	var dp=storage.getItem("_DP");
	var s = s-500;
	var e = e+500;
	if (s < 1){s=1;}
	$("input[name=prm_p3_var]").val(variant);
	$("input[name=prm_p3_qual]").val(q);
	$("input[name=prm_p3_dp]").val(dp);
	$("input[name=prm_p3_flk]").val(500);
//	$("#prm_p3_flk").val(500);
	$("input[name=prm_p3_s]").val(s);
	$("input[name=prm_p3_e]").val(e);

	// Set chromosome
	var o=new Object(JSON.parse(storage.getItem("_Chrs")));
	var en=new Object(JSON.parse(storage.getItem("_Env")));
	if($('#prm_rp3_chr').find('option').length === 0) {
		for (var i=0;i<o.length;i++) {
			var opt = new Option(en.chromosome_name + o[i].id, o[i].id, false, false);
			$('#prm_rp3_chr').append(opt).trigger('change');

			var opt2 = new Option(en.chromosome_name + o[i].id, o[i].id, false, false);
			$('#prm_p3_chr').append(opt2).trigger('change');
		}
	}
	$('#prm_rp3_chr').val(Objects.Chr).trigger('change');
	$('#prm_p3_chr').val(Objects.Chr).trigger('change');

	//Form & param
	var name=storage.getItem("_Name");
	var nameS=storage.getItem("_NameSub");
	$("#prm_p3_name").val(name);
	$("#prm_p3_nameS").val(nameS);
	$("#prm_p3_ref").val(en.reference_name);
	$('#dialog_p3').tabs();

	//dynamic contents
	var chr = document.getElementById("_Chr");
	var sl = document.getElementById("flk_len");
	var len = 500;
	var flk5=len;
	var flk3=len;
	if((s-len) < 0){flk5=s-(s-len);}
	if((e+len) > parseInt(_last_Chr("1b",chr))){flk3=e-(e+len);}
	sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+parseInt(flk5)+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+parseInt(flk3)+"&nbsp;bp";
	_dialog_p3_len();
	_dialog_rp3_len();
	var res = document.getElementById("p3_query_res");
	res.innerHTML="";
/*
	if($("#p3Setting").is(":hidden") != true){
		$("#p3Setting").hide();
	}
*/
	if($("#p3HistArea").is(":hidden") != true){
		$("#p3HistArea").hide();
	}

	// Set class with history closed
	$("#p3_tri").removeClass("open ui-icon-triangle-1-s").addClass("close ui-icon-triangle-1-e");

	_dialog_rp3_len();

	_sessionStart();
	_helpEvent();
	_helpEvent2();

	$(".p3_content").scrollTop(0);
}
/*
function _initp3Dlg() {
	$("#prm_rp3_flk").val("500");
	$("#prm_p3_flk").val("500");
	$("#prm_rp3_avd").val("0");
	$("#prm_p3_avd").val("0");
	var element = document.getElementById("prm_rp3_Ns");
        var elements = element.Ns_selection;
        elements[0].checked = true;
        _showVarsite(1);
	var element2 = document.getElementById("prm_rp3_DN");
        var elements2 = element2.DN_selection;
        elements2[0].checked = true;
	_hideDPmenu(0);
	$("#prm_NA_ratio").val("0");
	$("#prm_NA_num").val("0");
	$("#prm_rp3_prdmi").val("100");
	$("#prm_rp3_prdmx").val("300");
	$("#prm_rp3_sizopt").val("20");
	$("#prm_rp3_sizmax").val("27");
	$("#prm_rp3_sizmin").val("18");
	$("#prm_rp3_tmopt").val("60");
	$("#prm_rp3_tmmx").val("63");
	$("#prm_rp3_tmmi").val("57");
	$("#prm_rp3_tmdif").val("1");
	var element3 = document.getElementById("prm_epcr_onoff");
        var elements3 = element3.epcr_selection;
        elements3[0].checked = true;
        _hideePCRsite(0);
	$("#prm_epcr_prdmi").val("100");
	$("#prm_epcr_prdmx").val("300");
	$("#prm_epcr_tmmx").val("63");
        $("#prm_epcr_tmmi").val("57");
        $("#prm_epcr_KCl").val("50");
        $("#prm_epcr_MgCl2").val("1.5");
        $("#prm_epcr_dNTP").val("0.6");
        $("#prm_epcr_annealing").val("50");
        $("#prm_rp3_lowmsk").val("0");
	var element4 = document.getElementById("prm_rp3_Ns2");
        var elements4 = element4.Ns2_selection;
        elements4[0].checked = true;
        _showVarsite2(1);
}
*/	

//For run Primer3
function _slideP3Setting(){
	if ($("#p3Setting").is(":hidden")) {
		$("#p3Setting").slideDown("fast");
		$('#p3_set.close').toggleClass('open');
		$('#p3_set.close').removeClass('close');
		$('#p3_set.open').toggleClass('ui-icon-triangle-1-e ui-icon-triangle-1-s');
	} else {
		$("#p3Setting").slideUp();
		$('#p3_set.open').toggleClass('close');
		$('#p3_set.open').removeClass('open');
		$('#p3_set.close').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-e');
	}
}

function _hideVarsite(val){
        if (val==0) {
                $(".varsite").slideUp();
        }
}


function _showVarsite(val){
        if (val==1) {
                $(".varsite").slideDown("fast");
	}
}

function _hideDPmenu(val){
        if (val==0) {
                $(".DPmenu").slideUp();
        }
}


function _showDPmenu(val){
        if (val==1) {
                $(".DPmenu").slideDown("fast");
        }
}

function _hideVarsite2(val){
	if(val==0) {
		$(".varsite2").slideUp();
        }
}

function _hideePCRsite(val){
        if (val==0) {
		$("input[name='epcr_selection']:eq(1)").prop('checked',true);
                $("#epcrSetting").slideUp();
		$('#ePCR_tri.open').toggleClass('close');
                $('#ePCR_tri.open').removeClass('open');
		if ($("#ePCR_tri").hasClass("ui-icon-triangle-1-s")) {
                	$('#ePCR_tri.close').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-e');
		}
        }
}


function _showePCRsite(val){
        if (val==1) {
		$("input[name='epcr_selection']:eq(0)").prop('checked',true);
                $("#epcrSetting").slideDown("fast");
		$('#ePCR_tri.close').toggleClass('open');
                $('#ePCR_tri.close').removeClass('close');
		if ($("#ePCR_tri").hasClass("ui-icon-triangle-1-e")) {
                	$('#ePCR_tri.open').toggleClass('ui-icon-triangle-1-e ui-icon-triangle-1-s');
		}
        }
}

function _showVarsite2(val){
        if (val==1) {
                $(".varsite2").slideDown("fast");
        }
}

function _slideP3History(){
	if ($("#p3HistArea").is(":hidden")) {
		$("#p3HistArea").slideDown("fast");
                $('#p3_tri.close').toggleClass('open');
                $('#p3_tri.close').removeClass('close');
                $('#p3_tri.open').toggleClass('ui-icon-triangle-1-e ui-icon-triangle-1-s');
	} else {
		$("#p3HistArea").slideUp();
                $('#p3_tri.open').toggleClass('close');
                $('#p3_tri.open').removeClass('open');
                $('#p3_tri.close').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-e');
	}
}

function _slideBlastHistory(){
        if ($("#blastHistArea").is(":hidden")) {
                $("#blastHistArea").slideDown("fast");
    		$('#blst_hist.close').toggleClass('open');
    		$('#blst_hist.close').removeClass('close');
    		$('#blst_hist.open').toggleClass('ui-icon-triangle-1-e ui-icon-triangle-1-s');
		if (storage.getItem("_blstHistFlg") == 1 || $("#blst_opt").hasClass("open")) {
			collapseBlastDialog(false);
		}
        } else {
                $("#blastHistArea").slideUp();
                $('#blst_hist.open').toggleClass('close');
                $('#blst_hist.open').removeClass('open');
                $('#blst_hist.close').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-e');
		if (storage.getItem("_runBlast") == 0 && $("#blst_opt").hasClass("close")) {
			collapseBlastDialog(true);
		} else if (storage.getItem("_runBlast") == 1 || $("#blst_opt").hasClass("open")){
			collapseBlastDialog(false);
		}
        }
}
function _slideBlast(){
  if ($("#blastSetting").is(":hidden")) {
    $("#blastSetting").slideDown("fast");
    $('#blst_opt.close').toggleClass('close open');
    $('#blst_opt.open').toggleClass('ui-icon-triangle-1-e ui-icon-triangle-1-s');

    collapseBlastDialog(false);
/*
    $(".blast_window").css('height', ($("#tasuke").height()-20) + 'px');
    $(".blast_content").css('height', ($("#tasuke").height()-63) + 'px');

    $(".blast_window").css('max-height', $("#tasuke").height()-20);
    $(".blast_content").css('max-height', $("#tasuke").height()-63);
    $(window).resize(function() {
        if(!($(".blast_window").hasClass('minimized'))){
                $(".blast_window").css('height', $("#tasuke").height()-20);
                $(".blast_window").css('max-height', $("#tasuke").height()-20);
                $(".blast_content").css('height', $("#tasuke").height()-63);
                $(".blast_content").css('max-height', $("#tasuke").height()-63);
        }
    });
*/
  } else {
    $("#blastSetting").slideUp();
    $('#blst_opt.open').toggleClass('open close');
    $('#blst_opt.close').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-e');
    if (storage.getItem("_runBlast") != 1) {
	collapseBlastDialog(true);
/*
   	$(".blast_window").css('max-height', '382px');
   	$(".blast_content").css('max-height', '339px');
    	$(window).resize(function() {
      		$(".blast_window").css('max-height', '382px');
      		$(".blast_content").css('max-height', '339px');
    	});
*/
    }
  }
}

/*
function _slideePCR(){
  if ($("#epcrSetting").is(":hidden")) {
    $("#epcrSetting").slideDown("fast");
  } else {
    $("#epcrSetting").slideUp();
  }
}
*/

function _slideePCRTable(count) {
  if ($("#epcrTable"+count).is(":hidden")) {
    $("#cond_multi_triangle" + String(count)).removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
    $("#epcrTable"+count).slideDown("fast");
  } else {
    $("#cond_multi_triangle" + String(count)).removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
    $("#epcrTable"+count).slideUp();
  }
}
/*
function _formOnOFF(val){
  if (val==0){
    for(i=0;i<document.epcrSet.elements.length;i++){
      document.epcrSet.elements[i].disabled = "true"; // 入力不可
    }
  } else if (val==1){
    for(i=0;i<document.epcrSet.elements.length;i++){
      document.epcrSet.elements[i].disabled = ""; // 入力可能
    }
  }
}
*/

function _switchCostsFromPorgram() {
	var program = document.getElementById('blast_program').value;
	if(program === 'blastn') {
		var scores = document.getElementById('match_scores');
		scores.selectedIndex = 1;	// "1,-3"
	}
	_switchCosts();
}
function _switchCosts() {
	var scores = document.getElementById('match_scores');
	var program = document.getElementById('blast_program').value;
	var wordSize = document.getElementById('blast_word_size');
	var select = document.getElementById('gap_costs');
	select.textContent = null;

	var score = scores.options[scores.selectedIndex].value;
	var defGapIndex = 0;
        var selectBox = {};
	if(program === 'tblastn') {
		selectBox = {
			'11,2' : 'Existence: 11 Extension: 2',
			'10,2' : 'Existence: 10 Extension: 2',
			'9,2' : 'Existence: 9 Extension: 2',
			'8,2' : 'Existence: 8 Extension: 2',
			'7,2' : 'Existence: 7 Extension: 2',
			'6,2' : 'Existence: 6 Extension: 2',
			'13,1' : 'Existence: 13 Extension: 1',
			'12,1' : 'Existence: 12 Extension: 1',
			'11,1' : 'Existence: 11 Extension: 1',
			'10,1' : 'Existence: 10 Extension: 1',
			'9,1' : 'Existence: 9 Extension: 1',
		};
		defGapIndex = 8;
		scores.disabled = true;
		select.disabled = false;
		wordSizeMax = 7;
	} else if(program === 'tblastx') {
		selectBox = {
			'11,1' : 'Existence: 11 Extension: 1'
		};	// Fixed?
		defGapIndex = 0;
		scores.disabled = true;
		select.disabled = true;
		wordSizeMax = 5;
	} else {
		// blastn
		selectBox = _selectPairs(score);
		defGapIndex = 0;
		scores.disabled = false;
		select.disabled = false;
		wordSizeMax = 11;
	}
	wordSize.value = wordSizeMax;
//	if(wordSize.value > wordSizeMax) wordSize.value = wordSizeMax;
	wordSize.max = wordSizeMax;

        for (var i in selectBox) {
                var option = document.createElement('option');
                option.setAttribute('value',i);
                option.innerHTML = _escapeHTML(selectBox[i]);
                select.appendChild(option);
        }
	select.selectedIndex = defGapIndex;
}

function _selectPairs(scores) {
if(scores == "1,-2") {
                var selectBox = {
                        '5,2' : 'Existence: 5 Extension: 2',
                        '2,2' : 'Existence: 2 Extension: 2',
                        '1,2' : 'Existence: 1 Extension: 2',
                        '0,2' : 'Existence: 0 Extension: 2',
                        '3,1' : 'Existence: 3 Extension: 1',
                        '2,1' : 'Existence: 2 Extension: 1',
                        '1,1' : 'Existence: 1 Extension: 1',
                };
        } else if (scores == "1,-3") {
                var selectBox = {
                        '5,2' : 'Existence: 5 Extension: 2',
                        '2,2' : 'Existence: 2 Extension: 2',
                        '1,2' : 'Existence: 1 Extension: 2',
                        '0,2' : 'Existence: 0 Extension: 2',
                        '2,1' : 'Existence: 2 Extension: 1',
                        '1,1' : 'Existence: 1 Extension: 1',
                };
        } else if (scores == "1,-4") {
                var selectBox = {
                        '5,2' : 'Existence: 5 Extension: 2',
                        '1,2' : 'Existence: 1 Extension: 2',
                        '0,2' : 'Existence: 0 Extension: 2',
                        '2,1' : 'Existence: 2 Extension: 1',
                        '1,1' : 'Existence: 1 Extension: 1',
                };
        } else if (scores == "2,-3") {
                var selectBox = {
                        '4,4' : 'Existence: 4 Extension: 4',
                        '2,4' : 'Existence: 2 Extension: 4',
                        '0,4' : 'Existence: 0 Extension: 4',
                        '3,3' : 'Existence: 3 Extension: 3',
                        '6,2' : 'Existence: 6 Extension: 2',
                        '5,2' : 'Existence: 5 Extension: 2',
                        '4,2' : 'Existence: 4 Extension: 2',
                        '2,2' : 'Existence: 2 Extension: 2',
                };
        } else if (scores == "4,-5") {
                var selectBox = {
                        '12,8' : 'Existence: 12 Extension: 8',
                        '6,5' : 'Existence: 6 Extension: 5',
                        '5,5' : 'Existence: 5 Extension: 5',
                        '4,5' : 'Existence: 4 Extension: 5',
                        '3,5' : 'Existence: 3 Extension: 5',
                };
        } else if (scores == "1,-1") {
                var selectBox = {
                        '5,2' : 'Existence: 5 Extension: 2',
                        '3,2' : 'Existence: 3 Extension: 2',
                        '2,2' : 'Existence: 2 Extension: 2',
                        '1,2' : 'Existence: 1 Extension: 2',
                        '0,2' : 'Existence: 0 Extension: 2',
                        '4,1' : 'Existence: 4 Extension: 1',
                        '3,1' : 'Existence: 3 Extension: 1',
                        '2,1' : 'Existence: 2 Extension: 1',
                };
        }
        return(selectBox);
}

//Validate sequence length for primer template  

function _dialog_p3_len(){
        var sub = document.getElementById("p3_submit");
        var tgterr = document.getElementById("tgt_len_err2");
        var flk = document.getElementById("prm_p3_flk");
        var sl = document.getElementById("flk_len");
        var tgt = document.getElementById("prm_p3_tgt");
        var tgte = document.getElementById("prm_p3_tgt_e");
        var dp = document.getElementById("prm_p3_dp");
        var q = document.getElementById("prm_p3_qual");
        var chr = document.getElementById("prm_p3_chr");
        var avd = document.getElementById("prm_p3_avd");
        var avderr = document.getElementById("avd_err2");
        var qterr = document.getElementById("qt_err2");
        var dperr = document.getElementById("dp_err2");
        var avdv = parseInt(avd.value);
        var vdp = parseInt(dp.value);
        var vq = parseInt(q.value);
        var flkv = parseInt(flk.value);
        var tgtv = parseInt(tgt.value);
        var tgtev = parseInt(tgte.value);
        var string="";
        var passed=0;

        if(tgt.checkValidity() && tgte.checkValidity() && tgtv!=0 && tgtev!=0 && tgtev >= tgtv && tgtev <= parseInt(_last_Chr("1b",chr.value))){
                tgterr.innerHTML = "";
                avderr.innerHTML = "";
                qterr.innerHTML = "";
                dperr.innerHTML = "";
                if((tgtv-flkv) < 0){flk5=tgtv-1;}
                if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev-1;}
                //if((tgtev-tgtv) <= 9999){
                if((tgtev-tgtv+flkv*2) <= 49999){
                        var flk5=flkv;
                        var flk3=flkv;
                        if((tgtv-flkv) < 0){flk5=tgtv-1;}
                        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
                        sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
			sub.disabled = false;
                        passed=1;
                }else if (!flk.checkValidity() || flkv<0) {
                        string="<font color=\"#FF0000\">Invalid value.</font>";
                        sl.innerHTML = string;
			sub.disabled = true;
                        passed = 0;
                }else{
                        string="<font color=\"#FF0000\">Target + flanking region is too long!<br>Maximum size of target + flanking region is 50,000 bp.</font>";
                        tgterr.innerHTML = string;
                        var flk5=flkv;
                        var flk3=flkv;
                        if((tgtv-flkv) < 0){flk5=tgtv-1;}
                        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
                        sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
			sub.disabled = true;
                        passed=0;
                }
        }else{
                string="<font color=\"#FF0000\">Invalid value. Please input target position!</font>";
                sl.innerHTML = string;
		sub.disabled = true;
                passed=0;
        }

        var flk5=flkv;
        var flk3=flkv;
        if(passed == 1){
                if(avd.checkValidity() && dp.checkValidity() && q.checkValidity() && vdp>=0 && vq>=0 && avdv>=0 && flkv >= avdv){
			sub.disabled = false;
//                        sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" >Export</button>";
                } else{
                        if (!avd.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Avoid sites around the target (bp).</font>";
                                avderr.innerHTML = string;
			} else if (!q.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Quality.</font>";
                                qterr.innerHTML = string;
                        } else if (!dp.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in DEPTH.</font>";
                                dperr.innerHTML = string;
			}
			sub.disabled = true;
		}
        }
        $("#prm_p3_s").val(tgtv-flk5);
        $("#prm_p3_e").val(parseInt(tgtev)+parseInt(flk3));
}


//Validate sequence length for primer template  

function _dialog_rp3_len(flg){
	var sub = document.getElementById("rp3_submit");
	var flk = document.getElementById("prm_rp3_flk");
	var sl = document.getElementById("flk_len_r");
	var tgt = document.getElementById("prm_rp3_tgt");
	var tgte = document.getElementById("prm_rp3_tgt_e");
	var tgterr = document.getElementById("tgt_len_err");
	var chr = document.getElementById("prm_rp3_chr");
	var avd = document.getElementById("prm_rp3_avd");
	var avderr = document.getElementById("avd_err");
	var dp = document.getElementById("prm_rp3_dp");
	var q = document.getElementById("prm_rp3_qual");
	var qterr = document.getElementById("qt_err");
	var dperr = document.getElementById("dp_err");
	var rdperr = document.getElementById("rdp_err");
	var ndperr = document.getElementById("ndp_err");
	var genseterr = document.getElementById("gen_set_err");
	var epcrerr = document.getElementById("epcr_err");
        var dp_ratio = document.getElementById("prm_NA_ratio");
        var dp_num = document.getElementById("prm_NA_num");
	var avdv = parseInt(avd.value);
	var vdp = parseInt(dp.value);
	var vq = parseInt(q.value);
	var prdmi = document.getElementById("prm_rp3_prdmi");
	var prdmx = document.getElementById("prm_rp3_prdmx");
	var sizeopt = document.getElementById("prm_rp3_sizopt");
	var sizmax = document.getElementById("prm_rp3_sizmax");
	var sizmin = document.getElementById("prm_rp3_sizmin");
	var tmopt = document.getElementById("prm_rp3_tmopt");
	var tmmx = document.getElementById("prm_rp3_tmmx");
	var tmmi = document.getElementById("prm_rp3_tmmi");
	var tmdif = document.getElementById("prm_rp3_tmdif");
	var lowmsk = document.getElementById("prm_rp3_lowmsk");
        var epcrmi = document.getElementById("prm_epcr_prdmi");
        var epcrmx = document.getElementById("prm_epcr_prdmx");
        var epcrtmmx = document.getElementById("prm_epcr_tmmx");
        var epcrtmmi = document.getElementById("prm_epcr_tmmi");
        var kcl = document.getElementById("prm_epcr_KCl");
        var mgcl2 = document.getElementById("prm_epcr_MgCl2");
        var dntp = document.getElementById("prm_epcr_dNTP");
        var anling = document.getElementById("prm_epcr_annealing");
	var flkv = parseInt(flk.value);
	var tgtv = parseInt(tgt.value);
	var tgtev = parseInt(tgte.value);
	var prdmxv = parseInt(prdmx.value);
	var prdmiv = parseInt(prdmi.value);
        var sizeoptv = parseInt(sizeopt.value);
        var sizmaxv = parseInt(sizmax.value);
        var sizminv = parseInt(sizmin.value);
	var tmoptv = parseInt(tmopt.value);
	var tmmxv = parseInt(tmmx.value);
	var tmmiv = parseInt(tmmi.value);
	var tmdifv = parseInt(tmdif.value);
	var epcrmiv = parseInt(epcrmi.value);
	var epcrmxv = parseInt(epcrmx.value);
        var epcrtmmxv = parseInt(epcrtmmx.value);
        var epcrtmmiv = parseInt(epcrtmmi.value);

	var string="";
	var passed=0;
	if(flg === undefined) {
		flg = "";
	}

	if(tgt.checkValidity() && tgte.checkValidity() && tgtv!=0 && tgtev!=0 && tgtev >= tgtv && tgtev <= parseInt(_last_Chr("1b",chr.value))){
		//if((tgtev-tgtv) <= 9999){
		if((tgtev-tgtv+flkv*2) <= 49999){
			tgterr.innerHTML ="";
			avderr.innerHTML ="";
			qterr.innerHTML ="";
			dperr.innerHTML ="";
			rdperr.innerHTML ="";
			ndperr.innerHTML ="";
			genseterr.innerHTML ="";
			epcrerr.innerHTML ="";
                        var flk5=flkv;
                        var flk3=flkv;
                        if((tgtv-flkv) < 0){flk5=tgtv-1;}
                        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
                        sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
                        sub.disabled = false;
			passed=1;
                }else if (!flk.checkValidity() || flkv<0) {
                        string="<font color=\"#FF0000\">Please input flanking region length!</font>";
                        sl.innerHTML = string;
			sub.disabled = true;
                        passed=0;
		}else{
                        string="<font color=\"#FF0000\">Target + flanking region is too long!<br>Maximum size of target + flanking region is 50,000 bp.</font>";
                        tgterr.innerHTML = string;
                        var flk5=flkv;
                        var flk3=flkv;
                        if((tgtv-flkv) < 0){flk5=tgtv-1;}
                        if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
                        sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
			sub.disabled = true;
                        passed=0;
		}
	}else{
		string="<font color=\"#FF0000\">Invalid value. Please input target position!</font>";
		tgterr.innerHTML = string;
		sub.disabled = true;
		passed=0;
	}

        var flk5=flkv;
        var flk3=flkv;
        if(passed == 1){
                if(avd.checkValidity() && dp.checkValidity() && q.checkValidity() && prdmi.checkValidity() && prdmx.checkValidity() && sizeopt.checkValidity()
                                && sizmax.checkValidity() && sizmin.checkValidity() && tmopt.checkValidity() && tmmx.checkValidity() && tmmi.checkValidity()  && tmdif.checkValidity()
                                && lowmsk.checkValidity() && vdp>=0 && vq>=0 && avdv>=0 && tmdifv >= 0 && flkv >= avdv && prdmxv >= prdmiv
                                && sizminv <= sizeoptv && sizeoptv <= sizmaxv && sizminv <= sizmaxv && tmmiv <= tmmxv && tmmiv <= tmoptv && tmoptv <= tmmxv){
			sub.disabled = false;
//                        sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" >Run</button>";
                        passed=2;
                } else{
                        if (!avd.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Avoid sites around the target (bp).</font>";
                                avderr.innerHTML = string;
                        } else if (flkv < avdv) {
                                string="<font color=\"#FF0000\">Flanking region is shorter than avoiding sites.</font>";
                                avderr.innerHTML = string;
                        } else if (!q.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Quality.</font>";
                                qterr.innerHTML = string;
                        } else if (!dp.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in DEPTH.</font>";
                                dperr.innerHTML = string;
                        } else if (!prdmi.checkValidity() || !prdmx.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Product size range.</font>";
                                genseterr.innerHTML = string;
                        } else if (prdmxv < prdmiv) {
                                string="<font color=\"#FF0000\">Product min size is larger than Product max size.</font>";
                                genseterr.innerHTML = string;
                        } else if (!sizeopt.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Primer optimum size.</font>";
                                genseterr.innerHTML = string;
                        } else if (!sizmax.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Primer max size.</font>";
                                genseterr.innerHTML = string;
                        } else if (!sizmin.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Primer min size.</font>";
                                genseterr.innerHTML = string;
                        } else if (sizminv > sizeoptv || sizeoptv > sizmaxv || sizminv > sizmaxv) {
                                string="<font color=\"#FF0000\">Primer size setting is invalid.</font>";
                                genseterr.innerHTML = string;
                        } else if (tmmiv > tmmxv || tmmiv > tmoptv || tmoptv > tmmxv) {
                                string="<font color=\"#FF0000\">Primer TM setting is invalid.</font>";
                                genseterr.innerHTML = string;
                        } else if (!tmopt.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Primer optimum TM.</font>";
                                genseterr.innerHTML = string;
                        } else if (!tmmx.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Primer max TM.</font>";
                                genseterr.innerHTML = string;
                        } else if (!tmmi.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Primer min TM.</font>";
                                genseterr.innerHTML = string;
                        } else if (!tmdif.checkValidity() || tmdifv < 0) {
				string="<font color=\"#FF0000\">Invalid value in Max TM diffrence.</font>";
                                genseterr.innerHTML = string;
			}
                        //genseterr.innerHTML = string;
			sub.disabled = true;
                        passed=0;
                }
        }

        var dp_ratio_v = parseFloat(dp_ratio.value);
        var dp_num_v = parseInt(dp_num.value);
        accnum=_getList("db").length;

        if(passed == 2){
                if(dp_ratio.checkValidity() && dp_num.checkValidity() && dp_ratio_v>=0 && dp_num_v>=0 && dp_ratio_v<=1 && dp_num_v <= accnum) {
                        if(flg == 1) {
                                dp_num =Math.floor(accnum * dp_ratio_v);
                                $("#prm_NA_num").val(dp_num);
                        } else if(flg ==2) {
                                var dp_num2 = dp_num_v * 100;
                                dp_ratio_pre =dp_num2 / accnum ;
                                dp_ratio = Math.round(dp_ratio_pre)/100;
                                $("#prm_NA_ratio").val(dp_ratio);
                        }
			sub.disabled = false;
//                        sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" >Run</button>";
                        passed = 3;
                } else {
                        if (!dp_ratio.checkValidity()) {
                                if (dp_ratio_v>1 || dp_ratio_v < 0) {
                                        string="<font color=\"#FF0000\">Ratio of \"DEPTH = NA\" accessions is between 0 to 1.</font>";
                                        rdperr.innerHTML = string;
                                } else {
                                        string="<font color=\"#FF0000\">Invalid value on Ratio of \"DEPTH = NA\" accessions.</font>";
                                        rdperr.innerHTML = string;
                                }
                        } else if (!dp_num.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Number of \"DEPTH = NA\" accessions.</font>";
                                ndperr.innerHTML = string;
                        } else if (dp_num_v > accnum || dp_num_v < 0) {
                                string="<font color=\"#FF0000\">Number of \"DEPTH = NA\" accessions is between 0 to "+accnum+".</font>";
                                 ndperr.innerHTML = string;
                        }
			sub.disabled = true;
                        passed = 0;
                }
        }

        $("#prm_rp3_s").val(tgtv-flk5);
        $("#prm_rp3_e").val(parseInt(tgtev)+parseInt(flk3));

        if (passed == 3) {
                if(epcrmi.checkValidity() && epcrmx.checkValidity() && epcrtmmx.checkValidity() && epcrtmmi.checkValidity() && kcl.checkValidity() && mgcl2.checkValidity() && dntp.checkValidity() && anling.checkValidity() && epcrmxv >= epcrmiv && epcrtmmxv >= epcrtmmiv) {
			sub.disabled = false;
                } else {
                        if(!epcrmi.checkValidity() || !epcrmx.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Product size range.</font>";
                                epcrerr.innerHTML = string;
                        } else if (epcrmxv < epcrmiv) {
                                string="<font color=\"#FF0000\">Product min size is larger than Product max size.</font>";
                                epcrerr.innerHTML = string;
                        } else if(!epcrtmmx.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Primer max TM.</font>";
                                epcrerr.innerHTML = string;
                        } else if(!epcrtmmi.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Primer min TM.</font>";
                                epcrerr.innerHTML = string;
                        } else if (epcrtmmxv < epcrtmmiv) {
                                string="<font color=\"#FF0000\">Product min TM is larger than Product max TM.</font>";
                                epcrerr.innerHTML = string;
                        } else if(!kcl.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Concentration of monovalent cations.</font>";
                                epcrerr.innerHTML = string;
                        } else if(!mgcl2.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Concentration of divalent cations.</font>";
                                epcrerr.innerHTML = string;
                        } else if(!dntp.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Concentration of dNTPs(mM).</font>";
                                epcrerr.innerHTML = string;
                        } else if(!anling.checkValidity()) {
                                string="<font color=\"#FF0000\">Invalid value in Annealing oligo concentration(nM).</font>";
                                epcrerr.innerHTML = string;
                        }
			sub.disabled = true;
                        passed=0;
                }
        }

        $("#prm_rp3_s").val(tgtv-flk5);
        $("#prm_rp3_e").val(parseInt(tgtev)+parseInt(flk3));
}


//dialog "_changeRef"

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

	var phenohash = new Array();
	if(phenotypeFlg) {
		document.getElementById("acc_detail_pheno").innerHTML = storage.getItem("_Phenotype");
		phenoexp = storage.getItem("_Phenoexp");
		var phenohash = new Array();
		for(j=0,len=phenoexps.length; j<len; j++) {
			phenotmp = phenoexps[j].split(",");
			phenohash[phenotmp[0]] = phenotmp[1];
		}
	}

	var labels = ["id", "name", "variety", "grp", "origin", "origin_2", "type", "other_1", "other_2"];
	var table_detail = document.getElementById("table_acc_detail_tbody");
	while( table_detail.rows[ 0 ] ) table_detail.deleteRow( 0 );
	addOneRow(table_detail, targetAcc, phenohash);

	if(isTreeUsing()) {
		var accId2ObjMap = _getAllAccId2listsObj();
		var collapsedAccs = treeobj.getCollapsedLeafsByName(targetAcc.id);
		if(collapsedAccs.length > 0) {
			newRow = table_detail.insertRow();
			var newCell = newRow.insertCell();
			newCell.colSpan = labels.length + 1;
			newCell.style.textAlign = "center";
			newCell.style.color = "blue";
			newCell.style.backgroundColor = "#dcdcdc";
			newCell.style.fontWeight = "bold";
			newCell.style.padding = "3px 0px";
			newCell.appendChild( document.createTextNode("Collapsed Accessions") );

			for(var j=0,len=collapsedAccs.length; j<len; j++) {
				var accObj = accId2ObjMap[collapsedAccs[j].childs];
				if(accObj.id === targetAcc.id) continue;
				addOneRow(table_detail, accObj, phenohash, "blue");
			}

			var addRows = collapsedAccs.length;
			if(addRows > 15) addRows = 15;
			var autoHeight = $("#dialog_chref").outerHeight() + (addRows+1)*15;
			$("#dialog_chref").outerHeight(autoHeight);
		}
	}

	function addOneRow(table_detail, targetAcc, phenohash, color) {
		if(color == null) color = 'black';
		var newRow = table_detail.insertRow();
		for(var j=0,len=labels.length; j<len; j++) {
			var newCell = newRow.insertCell();
			newCell.style.color = color;
			newCell.appendChild( document.createTextNode(_escapeHTML(targetAcc[labels[j]])) );
		}
		var newCell = newRow.insertCell();
		newCell.style.color = color;
		if(phenotypeFlg) newCell.appendChild( document.createTextNode(_escapeHTML(phenohash[targetAcc.id])) );
	}
}

//Close dialog:changing reference

function _dlg_chref_cancel() {
	$("#dialog_chref").dialog('close');
}

//Downloading FASTA
function _dialog_fa(str){
	/*
	$("#dialog_fa").dialog({
		autoOpen: true,
		modal: true,
		width: 650,
		draggable: true,
		resizable: true
	});
	*/

        var p3flg = '';
        for(var i=0; i<minPos.length; i++) {
            if(minPos[i] == 'fasta') {
                    p3pos = i;
                    p3flg = 1;
            }
        }
        if(p3flg == 1) {
                for(var i=p3pos; i<minPos.length; i++) {
                        if (minPos[i+1] !== undefined) {
                            minPos[i] = minPos[i+1];
                        } else {
                            minPos.pop();
                        }
                        leftpos = (parseInt(175)*(parseInt(i))+ parseInt(5)*(parseInt(i+1)))+'px';
                        $("."+minPos[i+1]+"_window").css('left',leftpos);
                }
        }
	changeDialogZindex(".fasta_window");
/*
        winFront[winFront.length] = 'fasta';
        for (var i = 0; i < winFront.length; i++) {
                $("."+winFront[i]+"_window").css('z-index',1000+i);
        }
*/
        if($(".under_fasta").hasClass('fa-window-restore')){
                $(".under_fasta").toggleClass('fa-window-restore fa-window-minimize');
        }
	var $fadlgH = $("#tasuke").height() - 20;
	if ($fadlgH > 591 ) {
//		$fadlgH = 483;
		$fadlgH = 590;
	} 
        $("#dialog_fa").css('height',$fadlgH);
	$(".fasta_content").css('height',$fadlgH-43);

	$("#dialog_fa").css('max-height', 603);
	$(".fasta_content").css('max-height', 560);
//        $("#dialog_fa").css('max-height', 543);
//        $(".fasta_content").css('max-height', 500);
//        $("#dialog_fa").css('max-height',$fadlgH);
//        $(".fasta_content").css('max-height',$fadlgH-43);

        $("#dialog_fa").css('display','inline-block');

        if($("#dialog_fa").hasClass('minimized')){
                $("#dialog_fa").toggleClass('minimized');
                $("#dialog_fa").css('top','0px');
                //$("#dialog_fa").css('position','fixed');
                $(".fasta_content").css('display','inline-block');
                $("#dialog_fa").css('width','');
                $("#dialog_fa").css('min-height','42px');
                $("#dialog_fa").css('min-width','178px');
                $("#fasta_title").css('width','848px');
                $("#fasta_title").css('max-width','848px');
                $("#fasta_title").css('top','4px');
                $("#fasta_title").css('left','4px');
                $("#dialog_fa .minimize").css('top','9px');
                $("#dialog_fa .close").css('top','9px');
                $(".fasta_content").css('width','');
                $("#dialog_fa").css('height','');
                $(".fasta_content").css('height','');
                $("#prm_keyword").val('');
                $("#prm_position").val('');
                document.getElementById("fastaname").innerHTML = "&nbsp;&nbsp;Exporting FASTA";
                document.getElementById("fastaname").style.fontSize = "20px";
        }

	var s=parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
	var blk=storage.getItem("_Block");
	var e=s+(blk*_cvtZoom(Objects.Zoom))-1;
	var highlightRegions;
	try { highlightRegions = JSON.parse(storage.getItem("_RegHighlights")); } catch (e) {}
	if( !(highlightRegions instanceof Array) ) highlightRegions = [];

	var id = "";
	var cri = document.getElementById("prm_fa_cri");
	if(str){
		var params = str.split(",");
		s = parseInt(params[0]);
		e = parseInt(params[1]);
		id = _escapeHTML(params[2]);
		$("#prm_fa_objid").val(id);
//		document.getElementById("prm_fa_gene").value = 'cds';
//		document.getElementById("prm_fa_gene").checked = true;
		cri.options[1].selected = true;
		
	} else {
		if(highlightRegions.length > 0 && highlightRegions[0].chr == Objects.Chr) {
			s = parseInt(highlightRegions[0].st);
			e = parseInt(highlightRegions[0].en);
		}
		$("#prm_fa_objid").val("");
//		document.getElementById("prm_fa_gene").checked = false;
		cri.options[0].selected = true;
	}
	document.getElementById("prm_fa_reverse").checked = false;
	document.getElementById("prm_fa_rep_n").checked = false;
	$("#prm_fa_gene").find('option').remove().end();
//	$("#prm_fa_gene").val('cds');

	if((e-s) >= 19999){e=s+19999;}
	$("#prm_fa_s").val(s);
	$("#prm_fa_e").val(e);

	// Set parameters
	var o=new Object(JSON.parse(storage.getItem("_Chrs")));
	var en=new Object(JSON.parse(storage.getItem("_Env")));
	var ld="";
	var q=storage.getItem("_QUAL");
	var dp=storage.getItem("_DP");
	var name=storage.getItem("_Name");
	var nameS=storage.getItem("_NameSub");
	var sl = document.getElementById("flk_len_fa");
//	var sl = document.getElementById("seq_len");
	var len = e-s+1;

	for (var i=0;i<o.length;i++)ld=ld+"<option value='"+o[i].id+"'>"+en.chromosome_name+o[i].id+"</option>";
	$('#prm_fa_chr').find('option').remove().end().append(ld);
	$("#prm_fa_chr").val(Objects.Chr);
	$("#prm_fa_qual").val(q);
	$("#prm_fa_dp").val(dp);
	$("#prm_fa_list").val(_getList("db"));	// Deprecated
	$("#prm_fa_name").val(name);
	$("#prm_fa_nameS").val(nameS);
	$("#prm_fa_ref").val(en.reference_name);
	$("#prm_fa_width").val($("#prm_fa_width").attr("value"));
	if (len > 20000){
		len = 20000;
	}else if (len < 0){
		len = 0;
	}
	sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+parseInt(len)+"&nbsp;bp";

//	_dialog_fa_len();
	_changePosIDFa();
}


//Close dialog:fasta

function _dlg_fa_cancel() {
	$("#dialog_fa").dialog('close');
}

///////////////////////////////////////////////////////////////////////////////////
//for exporting param 
///////////////////////////////////////////////////////////////////////////////////
function _param_display(){
	var dp = document.getElementById("prm_fa_dp");
	var q = document.getElementById("prm_fa_qual");
	var w = document.getElementById("prm_fa_width");
	var vw = w.value;
	var vdp = dp.value;
	var vq = q.value;
	var string = "";
	var errqt = document.getElementById("err_qt");
        var errdp = document.getElementById("err_dp");
        var errlb = document.getElementById("err_lb");
	errqt.innerHTML = string;
	errdp.innerHTML = string;
	errlb.innerHTML = string;
	var sub = document.getElementById("fa_submit");

	var flgPass = false;
	if(dp.checkValidity() && q.checkValidity() && w.checkValidity() && vdp!=0 && vq!=0){
		sub.disabled = false;
		flgPass = true;
	} else {
		if (!(q.checkValidity()) || vq == "") {
			string = "<font color=\"#FF0000\">Invalid value in Quality.</font>";
			errqt.innerHTML = string;
		} 
		if (!(dp.checkValidity()) || vdp == "") {
			string = "<font color=\"#FF0000\">Invalid value in DEPTH.</font>";
			errdp.innerHTML = string;
		}
		if (!(w.checkValidity()) || vw == "") {
			string = "<font color=\"#FF0000\">Invalid value in Line break.</font>";
			errlb.innerHTML = string;
		}
		sub.disabled = true;
	}
	return flgPass;
}

//////////////////////////////////////////////////////////////////////////////////////
//sequence length
var valgene_cache_fa = {};	// This variable should only be used inside _dialog_fa_len().
function _dialog_fa_len(){
	var s = document.getElementById("prm_fa_s");
	var e = document.getElementById("prm_fa_e");
	var len = e.value - s.value + 1;
	var sub = document.getElementById("fa_submit");
	var sl = document.getElementById("flk_len_fa");
	var sv = s.value;
	var ev = e.value;

	var pass = 0;
	if(s.checkValidity() && e.checkValidity() && sv!=0 && ev!=0){
		sub.disabled = false;
		//if (len > 20000){
		if (len > 200000){
			len = 200000;
			e.value=(parseInt(sv)+199999);
			sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+len+"&nbsp;bp";
			passed = 1;
		} else if (len <= 0){
			//len = 0;
			len="<font color=\"#FF0000\">Please check start-postion and end-postion.</font>";
			sl.innerHTML = len;
			sub.disabled = true;
		} else{
			sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+len+"&nbsp;bp";
			passed = 1;
		}
	}else{
		len="<font color=\"#FF0000\">Please input postion!</font>";
		sl.innerHTML = len;
		sub.disabled = true;
	}

	if(passed == 1) {
		var flgPass = _param_display();
		if(flgPass) passed = 2;
	} else {
		sub.disabled = true;
	}

	var idmsg = document.getElementById("fa_id_msg");
	var $elmgene = $('#prm_fa_gene');
	if (passed == 2) {
		if(document.getElementById("prm_fa_cri").value == 1) {
			var objidv = document.getElementById("prm_fa_objid").value;
			if(!objidv) {
				idmsg.innerHTML = "<font color=\"#FF0000\">Input a Feature ID.</font>";
				sub.disabled = true;
				$elmgene.find('option').remove().end();
			} else if(objidv.indexOf('<script>') != -1){
				idmsg.innerHTML = "<font color=\"#FF0000\">Input paramater is invalid.</font>";
				sub.disabled = true;
				$elmgene.find('option').remove().end();
			} else {
				// Get gene info by Ajax and set it in form.
				//TODO: Consider changing named function
				var callback = function(valgene) {
					var sub = document.getElementById("fa_submit");
					var idmsg = document.getElementById("fa_id_msg");
					var $elmgene = $('#prm_fa_gene');
					var type = $elmgene.val();
					if (!valgene['valid']) {
						idmsg.innerHTML = "<font color=\"#FF0000\">This Feature ID is invalid.</font>";
						sub.disabled = true;
						$elmgene.find('option').remove().end();
						sub.disabled = true;
						valgene_cache_fa = {};	// Global var
					} else {
						var chr = valgene['chr'];
						var st = valgene['start'];
						var ed = valgene['end'];
						var cdslen = valgene['regs'];
						$elmgene.find('option').remove().end();
						var optGenome = new Option('Genome', 'genome', false, false); $elmgene.append(optGenome);
						if('exon' in cdslen) {
							var optMrna= new Option('mRNA', 'mrna', false, false); $elmgene.append(optMrna);
						}
						if('cds' in cdslen) {
							var optCds= new Option('CDS', 'cds', false, true); $elmgene.append(optCds);	// CDS is a preferred choice
							var optAa= new Option('Protein', 'aa', false, false); $elmgene.append(optAa);
						}

						// If possible, use the same option as last time.
						if($elmgene.find("option[value='" + type + "']").length) {
							$elmgene.find("option[value='" + type + "']").prop('selected', true);
						} else {
							type = $elmgene.val();
						}

						$("#prm_fa_chr").val(chr);
						$("#prm_fa_s").val(st);
						$("#prm_fa_e").val(ed);
						sub.disabled = false;
						valgene_cache_fa = valgene;	// Global var

						// Generate seq-len message.
						if(Object.keys(cdslen).length > 0) {
							if (type === 'cds') {
								len = parseInt(cdslen['cds']['len']) + "&nbsp;bp";
							} else if(type === 'mrna') {
								len = parseInt(cdslen['exon']['len']) + "&nbsp;bp";
							} else if(type === 'aa') {
								len = parseInt(cdslen['cds']['len'] / 3) + "&nbsp;aa";
							} else {
								// genome
								len = (ed - st + 1) + "&nbsp;bp";
							}
							idmsg.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;" + len +
								"&nbsp;&nbsp;&nbsp;<span style='color:gray;'>* Automatically changed to gene-strand.</span>";
						}
					}
				}	// End of function

				if('gene' in valgene_cache_fa && objidv === valgene_cache_fa['gene']) {
					callback(valgene_cache_fa);	// If ID is the same as last time, reuse it.
				} else {
					_validateGene(objidv, callback);	// Get with Ajax.
				}
			}
		} else {
			$elmgene.find('option').remove().end();
		}
	}

	var reverse = document.getElementById("prm_fa_reverse");
	if($elmgene.val() === 'aa') {
		reverse.checked = false;
		reverse.disabled = true;
	} else {
		reverse.disabled = false;
	}
}


//Downloading CSV
//Check the seq range of exporting csv
/*
function pushBtn(num) {
	var sl = document.getElementById("csv_msg");
	if (num == 0) {
		_dialog_csv_len();
		$("#prm_csv_keyword").val('');
		$("#prm_csv_keyword").prop("disabled",true);
		$("#prm_csv_s").prop("disabled",false);
		$("#prm_csv_e").prop("disabled",false);
		sl.innerHTML = "";
	} else if (num == 1) {
		_dialog_csv_len();
		var s=parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
        	var e=s+1999;
        	$("#prm_csv_s").val(s);
        	$("#prm_csv_e").val(e);
		$("#prm_csv_keyword").prop("disabled",false);
                $("#prm_csv_s").prop("disabled",true);
                $("#prm_csv_e").prop("disabled",true);
        	sl.innerHTML = "";
        };
}
*/
function _dialog_csv_len(){
//        var sub = document.getElementById("csv_submit");
//        var sub_gt012 = document.getElementById("csv_gt012_submit");
        var sl = document.getElementById("csv_msg");
        var sl2 = document.getElementById("csv_id_msg");
        var qmsg = document.getElementById("csv_q");
        var dpmsg = document.getElementById("csv_dp");
        var chr = document.getElementById("prm_csv_chr");
        var tgt = document.getElementById("prm_csv_s");
        var tgte = document.getElementById("prm_csv_e");
        var id = document.getElementById("prm_csv_keyword");
        var dp = document.getElementById("prm_csv_dp");
        var q = document.getElementById("prm_csv_qual");
        var vdp = parseInt(dp.value);
        var vq = parseInt(q.value);
        var tgtv = parseInt(tgt.value);
        var tgtev = parseInt(tgte.value);
	var idv = id.value;
        var string="";
        var passed=0;
        sl.innerHTML = string;
        sl2.innerHTML = string;
        qmsg.innerHTML = string;
        dpmsg.innerHTML = string;

        var allPassed = true;

	if ($('#choose_pos').prop('checked')) { //Position checked
        	if(tgt.checkValidity() && tgte.checkValidity() && tgtv>0 && tgtev>0 && tgtev >= tgtv){
                	if((tgtev-tgtv) <= 199999){
//                                sub.disabled = false;
                        	passed=1;
                	}else{
                        	string="<font color=\"#FF0000\">Target is too long!<br>Maximum size is 200,000 bp.</font>";
                        	sl.innerHTML = string;
//                                sub.disabled = true;
                                allPassed = false;
                        	passed=0;
                	}
        	}else{
                	string="<font color=\"#FF0000\">Invalid value. Please input target position!</font>";
                	sl.innerHTML = string;
//                        sub.disabled = true;
                        allPassed = false;
                	passed=0;
        	}
	} else if ($('#choose_id').prop('checked')) { //ID checked
		if (id.checkValidity() && !(idv.match(/<script>/))&& idv!="") {
//                        sub.disabled = false;
                        passed=1;
		} else if (!id.checkValidity() || idv == "") {
			string="<font color=\"#FF0000\">Please input ID!</font>";
                        sl2.innerHTML = string;
                        allPassed = false;
//                        sub.disabled = true;
                        passed=0;
		} else if (idv.match(/<script>/)) {
			string="<font color=\"#FF0000\">Invalid value. Please input the correct gene ID!</font>";
                        sl2.innerHTML = string;
                        allPassed = false;
//                        sub.disabled = true;
                        passed=0;
		}
	}
        if (passed==1) {
                if(q.checkValidity() && vq>0){
//                        sub.disabled = false;
                        passed=2;
                } else {
                        string="<font color=\"#FF0000\">Invalid value. Please input target quality!</font>";
                        qmsg.innerHTML = string;
                        allPassed = false;
//                        sub.disabled = true;
                        passed=0;
                }
        }
        if (passed==2) {
                if(dp.checkValidity() && vdp>0){
//                        sub.disabled = false;
                } else {
                        string="<font color=\"#FF0000\">Invalid value. Please input target depth!</font>";
                        dpmsg.innerHTML = string;
                        allPassed = false;
//                        sub.disabled = true;
                }
        }

        document.getElementById("csv_submit").disabled = !allPassed;
        document.getElementById("csv_gt012_submit").disabled = !allPassed;
}

function _dialog_csv(str){
	$("#dialog_csv").dialog({
		autoOpen: true,
		modal: true,
		width: 500,
		draggable: true,
		resizable: true
	});
	var ajaxloader = document.getElementById("csv_ajaxloader");
	ajaxloader.innerHTML = "";
	$('input[name=prm_pos_id]:eq(0)').prop('checked', true);
//	pushBtn(0);
	var sub = document.getElementById("csv_submit");
	sub.disabled = false;
//	sub.innerHTML =  "<button type=\"submit\" name=\"csv_submit\" onClick=\"_genCSV();\" >Export</button>";
	var s=parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
	//var e=s+1999;
	var e=s+19999;
	var highlightRegions;
	try { highlightRegions = JSON.parse(storage.getItem("_RegHighlights")); } catch (e) {}
	if( !(highlightRegions instanceof Array) ) highlightRegions = [];

	var id = "";
	if(str){
		var params = str.split(",");
		s = parseInt(params[0]);
		e = parseInt(params[1]);
		id = _escapeHTML(params[2]);
		$("#choose_id").prop('checked', true);
		$("#prm_csv_keyword").val(id);
	} else if(highlightRegions.length > 0 && highlightRegions[0].chr == Objects.Chr){
		s = parseInt(highlightRegions[0].st);
		e = parseInt(highlightRegions[0].en);
		$("#choose_pos").prop('checked', true);
		$("#prm_csv_keyword").val("");
	}
	$("#prm_csv_s").val(s);
	$("#prm_csv_e").val(e);

	// Set parameters
	var o=new Object(JSON.parse(storage.getItem("_Chrs")));
	var en=new Object(JSON.parse(storage.getItem("_Env")));
	$('#prm_csv_chr').find('option').remove();
	for (var i=0;i<o.length;i++) {
		if(Objects.Chr === o[i].id) {
			$('#prm_csv_chr').append("<option value='" + o[i].id + "' selected>" + en.chromosome_name + o[i].id + "</option>");
		} else {
			$('#prm_csv_chr').append("<option value='" + o[i].id + "'>" + en.chromosome_name + o[i].id + "</option>");
		}
	}
	var q=storage.getItem("_QUAL");
	$("#prm_csv_qual").val(q);
	var dp=storage.getItem("_DP");
	$("#prm_csv_dp").val(dp);
	$("#prm_csv_list").val(_getList("db"));	// Deprecated

	if('dbmode' in en && en.dbmode === 'mvcf') {
		$('#csv_span').show();
		$('#csv_gt012_span').hide();
	} else {
		$('#csv_span').hide();
		$('#csv_gt012_span').show();
	}

//	_changeEffGrpForm("expfilter_effgrp");
//	_dialog_csv_len();
	_changePosIDCsv();
}


//Close dialog:csv

function _dlg_csv_cancel() {
	$("#dialog_csv").dialog('close');
}


//Managing of accession lists
function _dialog_list(){
	var resizeFunc = function(e) {
		var parent = $("#dialog_list").parent();
		var myself = $("#dialog_list");
		var w = parseInt(parent.innerWidth()) - parseInt(myself.css("padding-left")) - parseInt(myself.css("padding-right"));
//		var h = parseInt(parent.innerHeight()) - parseInt(myself.css("padding-top")) - parseInt(myself.css("padding-bottom")) - 6 - 36;
//		$("#dialog_list").width(w);
//		$("#dialog_list").height(h);

		$("#list_acc_tabulator").width(w - 75 - 35);
	};

	var dialog = $("#dialog_list").dialog({
		autoOpen: true,
		modal: false,
		width: 930,	// <- 830
		maxHeight: window.innerHeight-15,
		draggable: true,
		resizable: true,
		open: resizeFunc,
		resize: resizeFunc,
/*
                position: {
                        of:'body',
                        at:'top',
                        my:'center'
                },
*/
//		dialogClass: 'ui-dialog-accession-manager'
		classes: {"ui-dialog": "ui-dialog-accession-manager"}
	});
//	dialog.parent().css('opacity', '0.9');
	setClickEventToDialog(dialog, '.ui-dialog-accession-manager');
	
	changeDialogZindex(".ui-dialog-accession-manager");

	if(isTreeUsing() && storage.getItem('_AccmanagerListType') !== 'standard') {
		setRadioGroupValue("lstBox_grp", "tree");

		// Unhide SystemTree options block without anime
		$('#div_systree').css("display", "block");
		$('#div_systree_notice').css("display", "none");
	} else {
		setRadioGroupValue("lstBox_grp", "sort");

		// Hide SystemTree options block without anime
		$('#div_systree').css("display", "none");
		$('#div_systree_notice').css("display", "block");
	}

	$("#lstBox1").resizable({
		"handles":"s",
		"minHeight":100,
		"maxHeight":500,
		"alsoResize":"#lstBox2"
	});

	// for SystemTree
	// Set for PhylipTree even if you don't use SystemTree
	$('#prm_systree_type').val(storage.getItem('_SystemTreeMode'));
	$('#prm_systree_correct').val(storage.getItem('_SystemTreeCorrect'));
	$('#prm_systree_sort').val(storage.getItem("_SystemTreeSort"));
	$('#prm_systree_sorttype').val(storage.getItem("_SystemTreeSortType"));
	$('#prm_systree_collapseType').val(storage.getItem('_SystemTreeAutoCollapseType'));
	$('#prm_systree_collapseHeight').val(storage.getItem('_SystemTreeAutoCollapseThreshold'));
	if(storage.getItem('_SystemTreeMode') === 'cladogram') $('#prm_systree_correct').prop('disabled', true);

	syncStyleSystreeSortType();

	// Deselect lists
	$('#lstBox1').val([]);
	$('#lstBox2').val([]);

	var lists = getListsForSystemTree();
	_dlg_make_list(lists);
	$('#prm_systreeW').val(storage.getItem("_SystemTreeW"));	// Execute first, _dlg_make_list > _dlg_make_systree > _appendTreeWOption;
	_dlg_title_color();
	$('#prm_list_upfile').replaceWith('<input type="file" id="prm_list_upfile" size="30" accept="text/plain" onChange="_validateAccList(this.files)">');
	_setClickCloseEvent();

	if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		listListManager.clearHistory();
//		listListManager.clearSearchHit();
		listListManager.syncList2SearchSelect2();
		listListManager.syncBtnMoveRow();
		listListManager.scrollToTop();
		$('#list_std_selectCangeViewMode').val("");

		$('#list_std_AllRows').text(_getAccListObjArray('_Lists-origin').length);
	}
}

function _dlg_title_color(){
	var col = new Object(JSON.parse(storage.getItem("_GrpCol")));
	var dest_subtitle = storage.getItem("_NameSub");
	if(dest_subtitle == "subvariety"){dest_subtitle = "grp";}
	var grps = _getList(dest_subtitle).filter(function (x, i, self) {
		return self.indexOf(x) === i;
	});
	var selectbox = "";
	for(var i=0; i<grps.length; i++){
		selectbox += "<option value='"+grps[i]+"'>"+grps[i]+"</option>";
	}
	if(storage.getItem("_ColorCode") == "on"){
		document.getElementById("prm_grpcol_switch").options[1].selected = true;
	}else{
		document.getElementById("prm_grpcol_switch").options[0].selected = true;
	}
	$('select[name=prm_grpcol_grp]').find('option').remove().end().append(selectbox);
	_update_dlg_title_color_grp();
	$("#prm_grpcol_col").val(col[$("select[name=prm_grpcol_grp]").val()]);
	$("#prm_grpcol_col").ColorPicker({
		onSubmit: function(hsb, hex, rgb, el) {
			$(el).val("#"+hex);
			$(el).ColorPickerHide();
			var col = new Object(JSON.parse(storage.getItem("_GrpCol")));
			col[$("select[name=prm_grpcol_grp]").val()] = "#"+hex;
			storage.setItem("_GrpCol",JSON.stringify(col));
			_update_dlg_title_color_grp();
			_drawCanvas();
		},
		onBeforeShow: function () {
			$(this).ColorPickerSetColor(this.value);
		}
	}).bind('keyup', function(){
		$(this).ColorPickerSetColor(this.value);
	});
}

function _update_dlg_title_color_grp(){
	var col = new Object(JSON.parse(storage.getItem("_GrpCol")));
	$("span[id=prm_grpcol_ind]").css("color",_getTitleColor($("select[name=prm_grpcol_grp]").val()));
	$("#prm_grpcol_col").val(col[$("select[name=prm_grpcol_grp]").val()]);
}

function _reset_dlg_title_color_grp(){
	_setTitleColor();
	var grp2col = JSON.parse(storage.getItem("_GrpCol"));
	var grp = $("#prm_grpcol_grp").val();
	$("#prm_grpcol_ind").css('color', grp2col[grp]);
	$("#prm_grpcol_col").val(grp2col[grp]);
//	$("#prm_grpcol_ind").css('color','rgb(250, 143, 143)');
//	$("#prm_grpcol_col").val('#fa8f8f');
	_drawCanvas();
}

function _appendTitleWOption() {
	var en = JSON.parse(storage.getItem("_Env"));
	if( !("accession_cvs_width" in en) ) return;

	var accCvsW = en["accession_cvs_width"];
	var matchOption = $('#prm_tw option').filter(function(index){
		return $(this).val() == accCvsW;
	});
	if(!matchOption || !matchOption.val()) {
		$('#prm_tw').append('<option value="' + accCvsW +'">' + accCvsW + 'px</option>');
	}
}
function _appendTreeWOption() {
	var en = JSON.parse(storage.getItem("_Env"));
	if( !("systreeWidth" in en) ) return;

	var treeW = en["systreeWidth"];
	var matchOption = $('#prm_systreeW option').filter(function(index){
		return $(this).val() == treeW;
	});
	if(!matchOption || !matchOption.val()) {
		$('#prm_systreeW').append('<option value="' + treeW +'">' + treeW + 'px</option>');
	}
}
function getListsAndDeleted(lists, mode) {
	if(mode == null) mode = 'sort';

	var listsObjArray = [];	// Normally it is 1D array, but only in "tree" it becomes a partially 2D array.
	if(mode === 'tree') {
//	if(isTreeUsing()) {
		listsObjArray = convListsForSystemTree(lists);
	} else {
		listsObjArray = lists;
	}
	return [listsObjArray, sortListsByTrackOrder(getDeletedLists(listsObjArray))];
}
function getDeletedLists(listsObjArray) {
	var allAccs = _getAccListObjArray('_Lists-origin');
//	var allAccs = new Object(JSON.parse(storage.getItem('_Lists-origin')));
	var isUsingAcc = {};
	for(var i=0,iLen=listsObjArray.length; i<iLen; i++) {
		var listsObj = listsObjArray[i];
		if(listsObj instanceof Array) {
			for(var j=0,jLen=listsObj.length; j<jLen; j++) {
				isUsingAcc[listsObj[j].id] = true;
			}
		} else {
			isUsingAcc[listsObj.id] = true;
		}
	}

	var deletedObjArray = [];
	for(var i=0,len=allAccs.length; i<len; i++) {
		var accListObj = allAccs[i];
		if(accListObj.id in isUsingAcc) continue;

		deletedObjArray.push(accListObj);
	}
	return deletedObjArray;
}
function getListForm(elemId) {
	lists = [];
	var accId2ObjMap = _getAllAccId2listsObj();
	$('#' + elemId + ' option').each(function(){
		var params = $(this).val().split('|');
		var accId = params[0];
		lists.push(accId2ObjMap[accId]);
	});
	return lists;
}
function setListsForm(listsId, deletedId, lists, deleted, sub, opt={order:true, using:true, check:true, clearSelect:true}) {
	// Below, If listListManager is valid, then phyListManager is also valid.
	if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		setListsFormStandard(listsId, lists, opt);
	} else {
		setListsFormLegacy(listsId, deletedId, lists, deleted, sub);
	}
}
function setListsFormStandardWrapper(listsId, opt={order:true, check:true, using:true, clearSelect:true}) {
	var mode = "";
	if(listsId === 'lstBox1') {
		mode = getRadioGroupValue("lstBox_grp");
	} else {
		mode = getRadioGroupValue("idlst_grp");
	}
	var lists = getListsForSystemTree();
	var listsAndDeletedNew = getListsAndDeleted(lists, mode);
	setListsFormStandard(listsId, listsAndDeletedNew[0], opt);
}
function setListsFormStandard(listsId, lists, opt={order:true, check:true, using:true, clearSelect:true}) {
	if(listsId === 'lstBox1') {
		syncList2DlgMakeList(lists, opt);
	} else {
		syncList2DlgMakePhy(lists, opt);
	}
}
function setListsFormLegacy(listsId, deletedId, lists, deleted, sub) {
	if(!sub) sub = 'grp';

	var phenohash = new Array();
	if(phenotypeFlg) {
		phenoexp = storage.getItem("_Phenoexp");
		phenoexps = phenoexp.split("|");
		var phenohash = new Array();
		for(i=0; i<phenoexps.length;i++) {
			phenotmp = phenoexps[i].split(",");
			phenohash[phenotmp[0]] = phenotmp[1];
		}
	}

	if(listsId != null) {
		var selectedAccsMap = {};
		$('#' + listsId + ' option').each(function(key, opt){
			if(opt.selected) {
				selectedAccsMap[opt.value.split('|')[0]] = true;
			}
		});

		var selectedVals = [];
		var elemLists = $('#' + listsId);
		elemLists.find('option').remove().end();
		for (var i=0,len=lists.length; i<len; i++){
			var accObj = lists[i];
			var existSubs = false;
			var style = 'color:black;';
			if(accObj instanceof Array) {
				accObj = lists[i].shift();
				existSubs = true;
				style = 'color:blue;';
			}
			var ss = getDisplayName(accObj);
			var ssDisp = ss;
			if (ssDisp.length > 15) ssDisp = ssDisp.substr(0,14) + "~";
			var pheno = "";
			if(phenotypeFlg  && accObj.id in phenohash) pheno = phenohash[accObj.id].replace(/^\s+|\s+$/g, "");
			var optVal = getOptValue([accObj.id, ss, accObj.variety, accObj[sub], pheno]);
			var optText = getOptText("%1$-16s %2$-16s %3$-16s %4$-16s", [ssDisp, accObj.variety, accObj[sub], pheno]);
			elemLists.append("<option value='" + optVal + "' style='" + style + "'>" + optText + "</option>");
			if(accObj.id in selectedAccsMap) selectedVals.push(optVal);
			if(existSubs) {
				for(var j=0,jLen=lists[i].length; j<jLen; j++) {
					var accObjSub = lists[i][j];
					var ssSub = getDisplayName(accObjSub);
					var ssSubDisp = ssSub;
					if (ssSubDisp.length > 13) ssSubDisp = ssSubDisp.substr(0,12) + "~";
					var phenoSub = "";
					if(phenotypeFlg && accObjSub.id && accObjSub.id in phenohash) phenoSub = phenohash[accObjSub.id].replace(/^\s+|\s+$/g, "");
					var optValSub = getOptValue([accObjSub.id, ssSub, accObjSub.variety, accObjSub[sub], phenoSub]);
					var optTextSub = getOptText("  %1$-14s %2$-16s %3$-16s %4$-16s", [ssSubDisp, accObjSub.variety, accObjSub[sub], phenoSub]);
					elemLists.append("<option value='" + optValSub + "' style='color:#8899ff;'>" + optTextSub + "</option>");
				}
			}
		}
		elemLists.val(selectedVals);
	}

	if(deletedId != null) {
		var elemDeleted = $('#' + deletedId);
		elemDeleted.find('option').remove().end();
		for (var i=0,len=deleted.length; i<len; i++){
			var accObj = deleted[i];
			var opText = accObj.id;
			if(Objects.Name != "id") opText = accObj.name.replace(/^\s+|\s+$/g, "");
			var opVal = accObj.id + "|" + accObj.name.replace(/^\s+|\s+$/g, "") + "|" + accObj.variety.replace(/^\s+|\s+$/g, "") + 
				"|" + accObj.grp.replace(/^\s+|\s+$/g, "") + "|" + accObj.origin.replace(/^\s+|\s+$/g, "") + "|" +
				accObj.type.replace(/^\s+|\s+$/g, "");
			elemDeleted.append("<option value='" + opVal + "'>" + opText + "</option>");
		}
	}

	// Update select2 options.
	if($('#' + listsId + '_search').length) updateSelect2ByForm(listsId + '_search', listsId, sub);
	if($('#' + deletedId + '_search').length) updateSelect2ByForm(deletedId + '_search', deletedId, sub);

	function getDisplayName(accObj) {
		var ss = accObj.id;
		if ( Objects.Name != "id" ) ss = accObj.name.replace(/^\s+|\s+$/g, "");
		return ss;
	}
	function getOptValue(vals) {
		for(var i=0,len=vals.length; i<len; i++) {
			vals[i] = vals[i].replace(/^\s+|\s+$/g, "");
		}
		return escape_html(vals.join('|'));
	}
	function getOptText(textFormat, vals) {
		for(var i=0,len=vals.length; i<len; i++) {
			vals[i] = vals[i].replace(/^\s+|\s+$/g, "");
		}
		return $.format(textFormat, vals[0], vals[1], vals[2], vals[3]).replace(/\s/g,"&nbsp;");
	}
}

function _dlg_make_list(lists){
	var en = JSON.parse(storage.getItem('_Env'));

        _appendTitleWOption();
	$('#prm_tw').val(storage.getItem('_TitleW'));
	$('#prm_switch_name').val(storage.getItem('_Name'));
	$('#prm_switch_sub').val(storage.getItem('_NameSub'));

	//button for sorting
	var sub = null;
	if($('#selsub_bSort')) sub = $('#selsub_bSort').val();
	$('#run_sorting').html( getSelectSortedOptionHtml('bSort', null, 'asc', sub) );
	$('button.asc').button({
		icon: "ui-icon-triangle-1-n", 
		iconPosition: "end"
	});
	$('button.desc').button({
		icon: "ui-icon-triangle-1-s", 
		iconPosition: "end"
	});

	var btnVal = "Apply now";
	var btnValTree = "Apply to tree";
	var btnValTreeLW = "Apply to tree (LightWeight)";
	var noteVal = "*Check/Uncheck accessions, then submit using the \"" + btnVal + "\" button. Only checked ones will be applied to the track.<br>\n*Use filtering, sorting, and row selection to refine accessions and toggle them in bulk via \"Action\".";
	var noteValTree = "*Check/Uncheck accessions, then submit using the \"" + btnValTree + "\" button. Only checked ones will be applied to the track.<br>\n*Use filtering, sorting, and row selection to refine accessions and toggle them in bulk via \"Action\".";

	var usingTree = false;
	if(isTreeAvailable() && treeobj.isTreeUsing()) {
		var lstBox_mode = getRadioGroupValue("lstBox_grp");
//		$('#div_lstBox_mode').css('display', 'block');
		$('#div_lstBox_mode').show('fast');
		_changeListDisplayModeLabel('lbl_lstBox_grp_tree', 'lbl_lstBox_grp_sort', lstBox_mode);

		// For #prm_list_lw_submit
		var dispLwSubmit = false;
		if(en['useSystemTreeLW'] === "1" && isTreeUsing()) {
//			$('#prm_list_lw_submit').css('display', 'inline-block');
			$('#prm_list_lw_submit').show('fast');
			if(isTreeUsing()) {
				usingTree = true;
				$('#prm_list_lw_submit').val(btnValTreeLW);
			} else {
				$('#prm_list_lw_submit').val(btnVal);
			}
			dispLwSubmit = true;
		} else {
//			$('#prm_list_lw_submit').css('display', 'none');
			$('#prm_list_lw_submit').hide('fast');
		}

		// For #prm_list_submit
		if(en['useSystemTree'] === "1" || !dispLwSubmit) {
//			$('#prm_list_submit').css('display', 'inline-block');
			$('#prm_list_submit').show('fast');
			// If you are not using SystemTree and SystemTreeLW and are using PhylipTree, NJ clustering will not be performed even if applied Acc list.
			if(isTreeUsing() && (en['useSystemTree'] === "1" || en['useSystemTreeLW'] === "1")) {
				usingTree = true;
				$('#prm_list_submit').prop('title', 'Run NJ clustering on server side');
				$('#prm_list_submit').val(btnValTree);
			} else {
				$('#prm_list_submit').prop('title', '');
				$('#prm_list_submit').val(btnVal);
			}
		} else {
			$('#prm_list_submit').prop('title', '');
//			$('#prm_list_submit').css('display', 'none');
			$('#prm_list_submit').hide('fast');
		}
	} else {
		setRadioGroupValue("lstBox_grp", "sort");
//		$('#div_lstBox_mode').css('display', 'none');
		$('#div_lstBox_mode').hide('fast');

		$('#prm_list_submit').css('display', 'inline-block');
		$('#prm_list_submit').val(btnVal);
		$('#prm_list_submit').prop('title', '');

		$('#prm_list_lw_submit').css('display', 'none');
		$('#list_std_listnote').html(noteVal);
	}

	if(usingTree) {
		$('#list_std_listnote').html(noteValTree);
	} else {
		$('#list_std_listnote').html(noteVal);
	}

	_changeListDisplayMode(lists);

	if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		$('#list_list_standard').css('display', 'block');
		$('#list_list_legacy').css('display', 'none');
	} else {
		$('#list_list_standard').css('display', 'none');
		$('#list_list_legacy').css('display', 'block');
	}

	_dlg_make_systree();
	if(isTreeUsing()) {
		if($('#div_systree').css("display") === 'none') $('#div_systree').show('fast');
		if($('#div_systree_notice').css("display") !== 'none') $('#div_systree_notice').hide('fast');
	} else {
		if($('#div_systree').css("display") !== 'none') $('#div_systree').hide('fast');
		if($('#div_systree_notice').css("display") === 'none') $('#div_systree_notice').show('fast');
	}
}
function updateSelect2ByForm(select2Id, oriSelectId, sub) {
	var opts = [];
	var acc2Info = _getAllAccId2listsObj();
	if(!sub) sub = 'grp';
	$('#' + oriSelectId + ' option').each(function(key, value) {
		try {
			var vals = $(value).attr('value').split('|');
			var acc = vals[0];
			var infoMap = acc2Info[acc];
			var subinfo = infoMap[sub];
//			var subinfo = "";
//				if(vals[2]) subinfo = vals[2];
			var text = $.format("  %-14s %-16s %-14s %s", acc, infoMap['name'], subinfo, infoMap['variety']).replace(/\s+$/, '').replace(/\s/g, "\u00A0");   // "&nbsp;" is wrong
			opts.push({name:text, value:$(value).attr('value')});
		} catch(e) {
			console.error(e)
		}
	});
	updateSelect2(select2Id, opts);
}
//function getAccInfoStringForSelect2(acc, infoMap, sub) {
//	return $.format("%-14s %-14s %-16s %-16s", acc, infoMap['name'], infoMap['variety'], infoMap[sub]).replace(/\s/g, "\u00A0");	// "&nbsp;" is wrong
//}
function updateSelect2(select2Id, options) {
	var $select2 = $('#' + select2Id);
	var optEmpty = new Option("", "", false, false);
	$select2.find('option').remove().end().append(optEmpty).trigger('change');
	if(options.length === 0) {
		$select2.prop('disabled', true);
	} else {
		$select2.prop('disabled', false);
		for(var i=0,len=options.length; i<len; i++) {
			var opt = new Option(options[i].name, options[i].value, false, false);
			$select2.append(opt);
//			$select2.append(opt).trigger('change');
		}
		$select2.trigger('change');	// change() is heavy, so call it only once at the end.
	}
}
function markSelect2Option(select2opt) {
	var $optObj = $(select2opt);
	if($optObj.hasClass('select2-selected')) {
		$optObj.removeClass('select2-selected');
	} else {
		$optObj.addClass('select2-selected');
	}
}
function markSelect2OptionByVal(elem, value) {
	$('#' + elem.id + '_parent .select2-results__option').each(function(index, opt) {
//		var pat = value.replace(/([\|\?\/\.\^\$\[\]\{\}\(\)\+\-])/g, '\\$1' );	// Escape RegExp meta char.
		var pat = escape_regexp(value) + '$';
		var reg = new RegExp(pat);
		var $optObj = $(opt);
		if(reg.test(opt.id)) {
			markSelect2Option(opt);
			return false;
		}
	});
}
function markSelect2Options(elem) {
	if(!elem.id) return;

	var targetId = elem.id.replace(/_search$/, '');
	var $target = $('#' + targetId);
	var selectedTargets = [];
	if( $target.val() instanceof Array ) {
		selectedTargets = $target.val();
	} else {
		selectedTargets.push($target.val());
	}

	var val2optMap = {};
	$('#' + elem.id + '_parent .select2-results__option').each(function(index, opt) {
		var matches = opt.id.match(/\-result\-[^\-]*\-(.+)$/);
		if(matches) {
			var val = matches[1];
			if(val) {
				val2optMap[val] = opt;
			}
		}
	});

	for(var i=0,len=selectedTargets.length; i<len; i++) {
		if(!selectedTargets[i] || !(selectedTargets[i] in val2optMap)) continue;
		markSelect2Option(val2optMap[selectedTargets[i]]);
	}
} 
function selectBySelect2(elem, targetId) {
	var value = $(elem).val();
	if(value === '') return;

	markSelect2OptionByVal(elem, value);
	var $target = $('#' + targetId);
	var selectedTargetsPre = [];
	if( $target.val() instanceof Array ) {
		selectedTargetsPre = $target.val();
	} else {
		selectedTargetsPre.push($target.val());
	}
	var selectedTargetHash = {};
	for(var i=0,len=selectedTargetsPre.length; i<len; i++) {
		selectedTargetHash[selectedTargetsPre[i]] = true;
	}
	if(value in selectedTargetHash) {
		delete selectedTargetHash[value];
	} else {
		selectedTargetHash[value] = true;
	}
	$target.val(Object.keys(selectedTargetHash));
//	$(elem).prop('selectedIndex', 0).change();	// return to unselected state.
	$(elem).prop('selectedIndex', 0).trigger("change.select2");	// Reset to placeholder.

	// Scroll to $target option.
//	var targetSelectedIndex = $target.prop('selectedIndex');	// If multiple selections, return only the lowest index.
	var targetSelectedIndex = 0;
	var index = 0;
	$('#' + targetId + ' option').each(function(key, opt) {
		if($(opt).attr('value') === value) {
			targetSelectedIndex = index;
			return false;	// break
		}
		index++;
	});
	var optHeight = $target[0].scrollHeight / $target[0].length;
	$target.animate({scrollTop:targetSelectedIndex * optHeight}, 200);

/*
	var offsetSelect = $target.offset().top;
	var offsetElement = $target.find("option[value='" + value + "']").offset().top;
console.log("Top:" + (offsetElement - offsetSelect));
	$target.scrollTop(30);
*/
}

/*
function _changeSub_list() {
//	if(getRadioGroupValue("lstBox_grp") !== "sort") return void(0);

	var lists = getListForm("lstBox1");
	var deleted = getListForm("lstBox2");
	var sub = $('#selsub_bSort').val();
	setListsForm('lstBox1', 'lstBox2', lists, deleted, sub);
}
*/
function _setDbAccOrderLstBox() {
	if(getRadioGroupValue("lstBox_grp") !== "sort") return void(0);

	var lists_origin = _getAccListObjArray("_Lists-origin");
	var acc2order = {};
	var acc2info = {};
	for(var i=0,len=lists_origin.length; i<len; i++) {
		acc2order[lists_origin[i].id] = i;
		acc2info[lists_origin[i].id] = lists_origin[i];
	}

	var sorter = function(a, b) {
		if(acc2order[a.id] < acc2order[b.id]) {
			return -1;
		} else if(acc2order[a.id] > acc2order[b.id]){
			return 1;
		} else {
			return 0;
		}
	};

	var lists = [];
	var deleted = [];
	if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		lists = lists_origin;
	} else {
		lists = getListForm("lstBox1");
		deleted = getListForm("lstBox2");
	}
	lists.sort(sorter);
	deleted.sort(sorter);
	setListsForm('lstBox1', 'lstBox2', lists, deleted, $('#selsub_bSort').val(), {order:true, using:false, check:false, clearSelect:false});
}

function _changeListModeAndSet() {
	lists = [];
	var accId2ObjMap = _getAllAccId2listsObj();

	if(listListManager && storage.getItem("_AccmanagerListType") === "standard") {
		listListManager.clearAllFilter();
		var usingIds = listListManager.getCurrentUsingId();
		for(var i=0,len=usingIds.length; i<len; i++) {
			lists.push(accId2ObjMap[usingIds[i]]);
		}
		_changeListDisplayMode(lists);
	} else {
		$('#lstBox1 option').each(function(){
			var params = $(this).val().split('|');
			var accId = params[0];
			lists.push(accId2ObjMap[accId]);
		});

		var scrollTop1 = $('#lstBox1').scrollTop();
		var scrollTop2 = $('#lstBox2').scrollTop();
		_changeListDisplayMode(lists);
		$('#lstBox1').scrollTop(scrollTop1);
		$('#lstBox2').scrollTop(scrollTop2);
	}
}
function _revertListToCurrentTrack() {
	var lists = getListsForSystemTree();

	var scrollTop1 = $('#lstBox1').scrollTop();
	var scrollTop2 = $('#lstBox2').scrollTop();
	_changeListDisplayMode(lists);
	$('#lstBox1').scrollTop(scrollTop1);
	$('#lstBox2').scrollTop(scrollTop2);
}
function _changeListDisplayMode(lists) {
	var val = getRadioGroupValue("lstBox_grp");
	var disableSort = false;
	_disabled_list_sort();
	if(val === 'sort') {
//		_disabled_list_sort(disableSort);
		if(isTreeUsing() && systreeFlg) {
			$('#prm_list_submit_notice').fadeIn('fast');
		} else {
			$('#prm_list_submit_notice').fadeOut('fast');
		}
		$('#run_sorting button').css("cursor", "pointer");
		$('#run_sorting .ui-icon-triangle-1-n').css("opacity", 1);
		$('#run_sorting .ui-icon-triangle-1-s').css("opacity", 1);

//		if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
//			listListManager.enableMovableRows(true);
//		}
	} else {
		disableSort = true;
//		_disabled_list_sort(disableSort);
		$('#prm_list_submit_notice').fadeOut('fast');

		$('#run_sorting button').css("cursor", "default");
		$('#run_sorting .ui-icon-triangle-1-n').css("opacity", 0.3);
		$('#run_sorting .ui-icon-triangle-1-s').css("opacity", 0.3);

//		if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
//			listListManager.enableMovableRows(false);
//		}
	}
	_changeListDisplayModeLabel('lbl_lstBox_grp_tree', 'lbl_lstBox_grp_sort', val);

	if(listListManager) listListManager.enableAllColumnSorting(!disableSort);

	if(isTreeAvailable() && val === 'tree') {
		$('#btnDefAccOrderLstBox').fadeOut('fast');
		$('#list_std_btn_default').fadeOut('fast');
	} else {
		$('#btnDefAccOrderLstBox').fadeIn('fast');
		$('#list_std_btn_default').fadeIn('fast');
	}

	if(lists != null) {
		var listsAndDeletedNew = getListsAndDeleted(lists, val);
		setListsForm('lstBox1', 'lstBox2', listsAndDeletedNew[0], listsAndDeletedNew[1], $('#selsub_bSort').val());
	}
}
function _changeListDisplayModeLabel(treeId, sortId, mode) {
	if(mode === 'tree') {
		$('#' + treeId).removeClass("block-not-selected").addClass("block-selected");
		$('#' + sortId).removeClass("block-selected").addClass("block-not-selected");
	} else {
		$('#' + treeId).removeClass("block-selected").addClass("block-not-selected");
		$('#' + sortId).removeClass("block-not-selected").addClass("block-selected");

	}
}

function _disabled_buttons(disabled, targetButtonIds) {
	for(var i=0,len=targetButtonIds.length; i<len; i++) {
		$('#' + targetButtonIds[i]).prop('disabled', disabled);
		if(disabled) {
			$('#' + targetButtonIds[i]).css('color', '#aaaaaa');
		} else {
			$('#' + targetButtonIds[i]).css('color', '');
		}
	}
}


var phenotypeInvalidStr = '---';
//function _disabled_list_sort(disabled) {
function _disabled_list_sort() {
	disabled = false;
	var val = getRadioGroupValue("lstBox_grp");
	if(val !== 'sort') disabled = true;

//	_disabled_buttons(disabled, ['bSort1', 'bSort2', 'bSort3', 'bSort4']);
	_disabled_buttons(disabled, ['bSort1', 'bSort2', 'bSort3', 'bSort4', 'bUp', 'bDown', 'list_std_bUp', 'list_std_bDown']);
	if($('#bSort4 .ui-button-text').html() === phenotypeInvalidStr) $('#bSort4').prop('disabled', true);

/*
	targetButtonIds = ['bUp', 'bDown', 'list_std_bUp', 'list_std_bDown'];
	for(var i=0,len=targetButtonIds.length; i<len; i++) {
		$('#' + targetButtonIds[i]).prop('disabled', disabled);
	}
*/
}
//function  _disabled_phy_sort(disabled) {
function  _disabled_phy_sort() {
	var val = getRadioGroupValue("idlst_grp");
	var disabled = false;
	if(val !== 'sort') disabled = true;
	_disabled_buttons(disabled, ['pSort1', 'pSort2', 'pSort3', 'pSort4']);
//	_disabled_buttons(disabled, ['pSort1', 'pSort2', 'selsub_pSort', 'pSort3', 'pSort4']);
	if($('#pSort4 .ui-button-text').html() === phenotypeInvalidStr) $('#pSort4').prop('disabled', true);
}
function getSelectSortedOptionHtml(idBase, targetIndex, orderType, sub) {
	if(!sub) sub = 'grp';

	var phenoname = "";
	if (phenotypeFlg) {
		var strname = storage.getItem("_Phenotype");
		if (strname.length > 16) {
			loop = Math.ceil(strname.length /16);
			for (var i=0;i<loop;i++) {
				start = 16 * i;
				end = 16 * (i + 1);
				phenoname += strname.substring(start,end)+ "<br>";
			}
		} else {
			phenoname = strname;
		}
	}
	if(phenoname === "") phenoname = phenotypeInvalidStr;

	var cls = [];	// cls[0] is undefined 
	for(var i=1; i<=4; i++) {
		cls[i] = {'css':'', 'class':'asc'};
	}
	if(targetIndex != null) cls[targetIndex] = {'css':'color:blue;', 'class':orderType};

	var funcName;
	var pulldownChangeFuncName;
	if(idBase === 'bSort') {
		funcName = "_sort_accession_list";
		pulldownChangeFuncName = "_changeListModeAndSet()";
//		pulldownChangeFuncName = "_changeSub_list()";
	} else {
		funcName = "_sort_accession_phylo";
		pulldownChangeFuncName = "_changePhyListModeAndSet()";
//		pulldownChangeFuncName = "_changeSub_phylo()";
	}

	var dropDownBtnHtml = "<select id=\"selsub_" + idBase + "\" class=\"ui-state-default\" style=\"width:95px;height:29px;border:1px solid white;border-radius:5px 0 0 5px;text-align-last:center;vertical-align:middle;margin-right:1px;" + cls[3].css + "\" onchange=\"" + pulldownChangeFuncName + "\">";
	var subtitles = [['Sub variety', 'grp'], ['Origin', 'origin'], ['Origin2', 'origin_2'], ['Type', 'type'], ['Other 1', 'other_1'], ['Other 2', 'other_2']];
	for(var i=0,len=subtitles.length; i<len; i++) {
		var selected = '';
		if(subtitles[i][1] === sub) selected = 'selected';
		dropDownBtnHtml += "<option value=\"" + subtitles[i][1] + "\" " + selected + ">" + subtitles[i][0] + "</option>";
	}
	dropDownBtnHtml += "</select>";

	var butSort = "<button class=\"" + cls[1].class + "\" style=\"width:110px;font-size:1em;margin-right:5px;" + cls[1].css + "\" id=\"" + idBase + "1\"  onClick=\"" + funcName + "(1,'" + orderType + "')\" >ID/Name</button>" +
		"<button class=\"" + cls[2].class + "\" id=\"" + idBase + "2\" style=\"width:110px;font-size:1em;margin-right:5px;" + cls[2].css + "\" onClick=\"" + funcName + "(2,'" + orderType + "')\">Variety</button>" +
		dropDownBtnHtml + "<button class=\"" + cls[3].class + "\" id=\"" + idBase + "3\" style=\"width:25px;height:27px;font-size:1em;border-radius:0 5px 5px 0;margin-right:5px;padding:0px;" + cls[3].css + "\" onClick=\"" + funcName + "(3,'" + orderType + "')\" />" +
		"<button class=\"" + cls[4].class + "\" id=\"" + idBase + "4\" style=\"width:134px;font-size:1em;margin-right:5px;" + cls[4].css + "\" onClick=\"" + funcName + "(4,'" + orderType + "')\">"+phenoname+"</button>";
	return butSort;
}
function _dlg_make_phylist(lists) {
//	if(lists == null) lists = getListsForSystemTree();

	//button for sorting
	var sub = null;
	if($('#selsub_pSort')) sub = $('#selsub_pSort').val();
	$('#run_sortings').html( getSelectSortedOptionHtml('pSort', null, 'asc', sub) );
	$('button.asc').button({
		icon: "ui-icon-triangle-1-n",
		iconPosition: "end" 
//		icons: {
//			secondary: 'ui-icon-triangle-1-n'
//		}
	});
	$('button.desc').button({
		icon: "ui-icon-triangle-1-s",
		iconPosition: "end" 
//		icons: {
//			secondary: 'ui-icon-triangle-1-s'
//		}
	});

	//select phenotype
	if (phenotypeFlg) {
		var strname = storage.getItem("_Phenotype");
		var phenoname = "";
		if (strname.length > 13) {
			loop = Math.ceil(strname.length /13);
			for (var i=0;i<loop;i++) {
				start = 13 * i;
				end = 13 * (i + 1);
				phenoname += strname.substring(start,end)+ "<br>";
			}
		} else {
			phenoname = strname;
		}
	}

	var idlst_mode = getRadioGroupValue("idlst_grp");
//	setRadioGroupValue("idlst_grp", idlst_mode);
//	if(isTreeAvailable()) {
	if(isTreeAvailable() &&  treeobj.isTreeUsing()) {
		$('#div_idlst_mode').css('display', 'block');
/*
		if(idlst_mode === 'tree') {
			$('#btnDefAccOrderIdlst').css('display', 'none');
		} else {
			$('#btnDefAccOrderIdlst').css('display', 'inline-block');
		}
*/
		_changeListDisplayModeLabel('lbl_idlst_grp_tree', 'lbl_idlst_grp_sort', idlst_mode);
	} else {
		$('#div_idlst_mode').css('display', 'none');
	}
	_changePhyListDisplayMode(lists);

	if(phyListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		$('#phy_list_standard').css('display', 'block');
		$('#phy_list_legacy').css('display', 'none');

		$('#phy_btns_standard').css('display', 'block');
		$('#phy_btns_legacy').css('display', 'none');
	} else {
		$('#phy_list_standard').css('display', 'none');
		$('#phy_list_legacy').css('display', 'block');

		$('#phy_btns_standard').css('display', 'none');
		$('#phy_btns_legacy').css('display', 'block');
	}
}
/*
function _changeSub_phylo() {
//	if(getRadioGroupValue("idlst_grp") !== "sort") return void(0);

	var lists = getListForm("idlst");
	var deleted = getListForm("tree_qry");
	setListsForm('idlst', 'tree_qry', lists, deleted, $('#selsub_pSort').val());
}
*/
function _setDbAccOrderIdlst() {
	if(getRadioGroupValue("idlst_grp") !== "sort") return void(0);

	var lists_origin = _getAccListObjArray("_Lists-origin");
//	var lists_origin = JSON.parse(storage.getItem("_Lists-origin"));
	var acc2order = {};
	var acc2info = {};
	for(var i=0,len=lists_origin.length; i<len; i++) {
		acc2order[lists_origin[i].id] = i;
		acc2info[lists_origin[i].id] = lists_origin[i];
	}

	var sorter = function(a, b) {
		if(acc2order[a.id] < acc2order[b.id]) {
			return -1;
		} else if(acc2order[a.id] > acc2order[b.id]){
			return 1;
		} else {
			return 0;
		}
	};

	var lists = [];
	var deleted = [];
	if(phyListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		lists = lists_origin;
/*
		phyListManager.clearAllFilter();
		var usingArr = phyListManager.getCurrentUsingId();
		for(var i=0,len=usingArr.length; i<len; i++) {
			lists.push(acc2info[usingArr[i]]);
		}
*/
	} else {
		lists = getListForm("idlst");
		deleted = getListForm("tree_qry");
	}
	lists.sort(sorter);
	deleted.sort(sorter);
	setListsForm('idlst', 'tree_qry', lists, deleted, $('#selsub_pSort').val(), {order:true, using:false, check:false, clearSelect:false});
}
function _changePhyListModeAndSet() {
	lists = [];
	var accId2ObjMap = _getAllAccId2listsObj();

	if(phyListManager && storage.getItem("_AccmanagerListType") === "standard") {
		phyListManager.clearAllFilter();
		var usingIds = phyListManager.getCurrentUsingId();
		for(var i=0,len=usingIds.length; i<len; i++) {
			lists.push(accId2ObjMap[usingIds[i]]);
		}
		_changePhyListDisplayMode(lists);
	} else {
		$('#idlst option').each(function(){
			var params = $(this).val().split('|');
			var accId = params[0];
			lists.push(accId2ObjMap[accId]);
		});

		var scrollTop1 = $('#idlst').scrollTop();
		var scrollTop2 = $('#tree_qry').scrollTop();
		_changePhyListDisplayMode(lists);
		$('#idlst').scrollTop(scrollTop1);
		$('#tree_qry').scrollTop(scrollTop2);
	}
}
function _revertPhyListToCurrentTrack() {
	var lists = getListsForSystemTree();

	var scrollTop1 = $('#idlst').scrollTop();
	var scrollTop2 = $('#tree_qry').scrollTop();
	_changePhyListDisplayMode(lists);
	$('#idlst').scrollTop(scrollTop1);
	$('#tree_qry').scrollTop(scrollTop2);
}
function _changePhyListDisplayMode(lists) {
	var val = getRadioGroupValue("idlst_grp");
	var disableSort = false;
	if(val !== 'sort') disableSort = true;

	_disabled_phy_sort();
/*
	if(val === 'sort') {
		_disabled_phy_sort(disableSort);
	} else {
		disableSort = true;
		_disabled_phy_sort(disableSort);
	}
*/
	_changeListDisplayModeLabel('lbl_idlst_grp_tree', 'lbl_idlst_grp_sort', val);

	if(phyListManager) phyListManager.enableAllColumnSorting(!disableSort);

	if(isTreeAvailable() && val === 'tree') {
		$('#btnDefAccOrderIdlst').fadeOut('fast');
		$('#phy_std_btn_default').fadeOut('fast');

		$('#run_sortings button').css("cursor", "default");
		$('#run_sortings .ui-icon-triangle-1-n').css("opacity", 0.3);
		$('#run_sortings .ui-icon-triangle-1-s').css("opacity", 0.3);
	} else {
		$('#btnDefAccOrderIdlst').fadeIn('fast');
		$('#phy_std_btn_default').fadeIn('fast');

		$('#run_sortings button').css("cursor", "pointer");
		$('#run_sortings .ui-icon-triangle-1-n').css("opacity", 1);
		$('#run_sortings .ui-icon-triangle-1-s').css("opacity", 1);
	}

	if(lists != null) {
		var listsAndDeletedNew = getListsAndDeleted(lists, val);
		var sub = $('#selsub_pSort').val();
		setListsForm('idlst', 'tree_qry', listsAndDeletedNew[0], listsAndDeletedNew[1], sub);
	}
}

function _dlg_make_systree() {
	_appendTreeWOption();
	_changeSysTreeThresholdInfo();
}
function _dialog_systree_collpse_by_leafs() {
	$("#dialog_systree_collpse_by_leafs").dialog({
		autoOpen: true,
		modal: true,
		width: 580,
		height: 140,
		draggable: true,
		resizable: true
	});

	$("#prm_systree_collapse_by_leafs").attr('max', treeobj.tree.leafs.length);
	$("#prm_systree_collapse_by_leafs").val(treeobj.order.length);
}
function _dialog_systree_collpse_by_leafs_check() {
	var currentTreeLeafsNum = treeobj.order.length;
	var leafsNumStr = $("#prm_systree_collapse_by_leafs").val();
	if(/[^0-9]/.test(leafsNumStr)) {
		$("#prm_systree_collapse_by_leafs").val(currentTreeLeafsNum)
		leafsNumStr = String(currentTreeLeafsNum);
	}

	var leafsNum = parseInt(leafsNumStr);
	var maxLeafsNum = treeobj.tree.leafs.length;
//	if(leafsNum < 2) $("#prm_systree_collapse_by_leafs").val(2);
	if(leafsNum > maxLeafsNum) $("#prm_systree_collapse_by_leafs").val(maxLeafsNum);
	if(leafsNumStr === "") {
		$("#submit_systree_collapse_by_leafs").prop("disabled", true);
	} else {
		$("#submit_systree_collapse_by_leafs").prop("disabled", false);
	}
}
function _dlg_collapse_by_leafs() {
	$("#submit_systree_collapse_by_leafs").prop("disabled", true);
	var leafsNum = parseInt($("#prm_systree_collapse_by_leafs").val());
	var threshold = _getSystreeThresholdByLeafCount(leafsNum);
	if(threshold !== null) {
//console.log("Threshold:" + threshold);
		var type = $("#prm_systree_collapseType").val();
		if(type === "ratio") threshold = threshold / treeobj.oriMaxHeight;
		$("#prm_systree_collapseHeight").val(threshold);
		_changeSysTreeThresholdInfo();
		_resetAutoCollapse();

		if(leafsNum !== treeobj.order.length) alert("Can't collapse SystemTree to specified number(" + leafsNum + "), so It set to a close value.(" + treeobj.order.length + ")");
		$("#dialog_systree_collpse_by_leafs").dialog('close');
	} else {
		alert("An unknown error has occurred. The process has been cancelled.");
	}
	$("#submit_systree_collapse_by_leafs").prop("disabled", false);
}
function syncDlgMakeList(lists) {
	// if lists is null, don't change the accession list form.
	// Basically, lists are only needed for recoveryAccList(),_uploadAccList() to reset acc list form. 
	if ($('#dialog_go').is(":visible")) _dlg_make_searchAcc();	// Search dialog
	if ($('#dialog_list').is(":visible")) _dlg_make_list(lists);	// Accession Manager
	if ($('#dialog_phy').is(":visible") && !$("#dialog_phy").hasClass('minimized')) _dlg_make_phylist(lists);	// Phylogenetic Tree
//	if ($('#dialog_systree').is(":visible")) _dlg_make_systree(); 
}
function syncList2DlgMakeList(lists, opt = {order:true, check:true, clearSelect:true}) {
/*
	// for Debug
	var caller = 'Unknown';
	if(syncList2DlgMakeList.caller) caller = syncList2DlgMakeList.caller.name;
	console.log("Call syncList2DlgMakeList from " + caller);
	if(!caller) {
		try{ throw new Error('Call syncList2DlgMakeList Trace'); } catch(e) { console.log(e) };
	}
*/
	if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		var accOrder = [];
		for(var i=0,iLen=lists.length; i<iLen; i++) {
			var accObj = lists[i];
			if(accObj instanceof Array) {
				var arr = [];
				for(var j=0,jLen=accObj.length; j<jLen; j++) {
					arr.push(accObj[j].id);
				}
				accOrder.push(arr);
			} else {
				accOrder.push(accObj.id);
			}
		}
		listListManager.resetOrder(accOrder, opt);
	} else {
		// There is nothing to do in Legacy mode.
	}
}
function syncList2DlgMakePhy(lists, opt = {order:true, check:true, clearSelect:true}) {
	if(phyListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		var accOrder = [];
		for(var i=0,iLen=lists.length; i<iLen; i++) {
			var accObj = lists[i];
			if(accObj instanceof Array) {
				var arr = [];
				for(var j=0,jLen=accObj.length; j<jLen; j++) {
					arr.push(accObj[j].id);
				}
				accOrder.push(arr);
			} else {
				accOrder.push(accObj.id);
			}
		}
		phyListManager.resetOrder(accOrder, opt);
	} else {
		// There is nothing to do in Legacy mode.
	}
}
function _fitDialogHeightToWindow(dialogObj, contentObj) {
    if(dialogObj.is(':hidden')) return;

    var windowHeight = parseInt($('#tasuke').css('height')) - 20;
    var dialogBottom = parseInt(dialogObj.css('top')) + parseInt(dialogObj.css('height'));
    if(windowHeight < dialogBottom) {
        var dialogHeight = windowHeight - parseInt(dialogObj.css('top')) + 1;
        dialogObj.css('height', dialogHeight);

        var contentHeight = dialogHeight - 43;
        contentObj.css('height', contentHeight);
//console.log(dialogObj.attr('id') + ":" + dialogObj.css('top') + "+" + dialogObj.css('height') + "=" + dialogBottom + "/" + windowHeight);
    }
}

/*
function _dialog_systree() {
	if(storage.getItem('_SYSTREE') === 'off') return void(0);

	var dialog = $("#dialog_systree").dialog({
		autoOpen: true,
		modal: false,
		width: 350,
//		maxHeight: window.innerHeight-15,
		draggable: true,
		resizable: true,
		dialogClass: 'ui-dialog-systree'
	});
	setClickEventToDialog(dialog, '.ui-dialog-systree');

	changeDialogZindex(".ui-dialog-systree");

	$('#prm_systree_type').val(storage.getItem('_SystemTreeMode'));
	$('#prm_systree_correct').val(storage.getItem('_SystemTreeCorrect'));
	$('#prm_systree_sort').val(storage.getItem("_SystemTreeSort"));
	$('#prm_systree_collapseType').val(storage.getItem('_SystemTreeAutoCollapseType'));
        $('#prm_systree_collapseHeight').val(storage.getItem('_SystemTreeAutoCollapseThreshold'));

	if(storage.getItem('_SystemTreeMode') === 'cladogram') $('#prm_systree_correct').prop('disabled', true);

	_dlg_make_systree();
	$('#prm_systreeW').val(storage.getItem("_SystemTreeW"));
}
*/

function recoveryAccList() {
	var en = new Object(JSON.parse(storage.getItem("_Env")));

	_windowGffClose();
	_setAccListObjArray("_Lists", _getAccListObjArray("_Lists-origin"));
	_setAccListObjArray("_ListsDeleted", []);
//	storage.setItem("_Lists",storage.getItem("_Lists-origin"));
//	storage.setItem("_ListsDeleted","[]");
//	_showLoading();		// Must be executed within syncListsWithCancelPhylipTree
	storage.removeItem("_ListsTgt");
//	FROMSCROLL=false;
	var threshold = en.systreeAutoCollapseThreshold;
	var type = en.systreeAutoCollapseType;
	storage.setItem('_SystemTreeAutoCollapseType', type);
	storage.setItem('_SystemTreeAutoCollapseThreshold', threshold);
	document.getElementById("prm_systree_collapseType").value = type;
	document.getElementById("prm_systree_collapseHeight").value = Number(threshold);
	if(isTreeUsing()) {
		_showLoadingDialog();
	} else {
		_messageOnScreen("Recovery list (original)");
	}
	setTimeout(function() {
		// syncListsWithCancelPhylipTree() is heavy, so _messageOnScreen() will not work without setTimeout().
		syncListsWithCancelPhylipTreeDefault(threshold);

		// Wait for it to be set in storage"Lists" and execute. 
		// It only affects the form and preview values, so if it doesn't work in time, give up (you can reopen the dialog)
//		setTimeout(function() {
//			lists = getListsForSystemTree();
//			syncDlgMakeList(lists);
//		}, 100);
	}, 50);
}

//Set accession sorting event
$(document).ready(function() {
	$('#prm_list_init').click(function(e) {
		recoveryAccList();
	});

/*
	if (storage.getItem("_runBlast") == 1) {
        	$(window).resize(function() {
        	        $(".blast_window").css('max-height', $("#mv_dlg").height());
                	$(".blast_content").css('max-height', $("#mv_dlg").height()-15);
        	});
	}
*/

/*
	$(window).resize(function() {
		$Hlength = $(window).height() - 68;
		$Wlength = $(window).width() - 26;
		$("#phy_tree_res").css('height',$Hlength);
		$("#phy_tree_res").css('width',$Wlength);
		$("#phy_svg").css('height',$Hlength);	// css height <svg style="height:xxx, ...
		$("#phy_svg").css('width',$Wlength);	// css wdth
	});
*/
        $(window).resize(function() {
                if(!($(".phylo_window").hasClass('minimized'))){
                        _fitDialogHeightToWindow($(".phylo_window"), $(".phylo_content"));
		} else {                                        
                        $(".phylo_window").css('top', $("#bottom").offset().top +'px');
                }
        });
        $(window).resize(function() {
                if(!($(".p3_window").hasClass('minimized'))){
                        _fitDialogHeightToWindow($(".p3_window"), $('.p3_content'));
                } else {
			$(".p3_window").css('top', $("#bottom").offset().top +'px');
		}
		
        });

        $(window).resize(function() {
                if(!($(".gwas_window").hasClass('minimized'))){
                        _fitDialogHeightToWindow($(".gwas_window"), $('.gwas_content'));
                } else {
                        $(".gwas_window").css('top', $("#bottom").offset().top +'px');
                }

        });

	$(window).resize(function() {
    		if(!$(".blast_window").hasClass('minimized')){
                        if($('#result').html() || !$("#blst_opt").hasClass("close") || !$('#blst_hist').hasClass("close")) _fitDialogHeightToWindow($(".blast_window"), $('.blast_content'));
                } else {
      			$(".blast_window").css('top', $("#bottom").offset().top+'px');
    		}
  	});

        $(window).resize(function() {
                if($(".search_window").hasClass('minimized')){
                        $(".search_window").css('top', $("#bottom").offset().top+'px');
                }
        });

        $(window).resize(function() {
                if(!($(".fasta_window").hasClass('minimized'))){
                        _fitDialogHeightToWindow($(".fasta_window"), $(".fasta_content"));
                } else {
                        $(".fasta_window").css('top', $("#bottom").offset().top +'px');
                }
        });

	$('#prm_list_submit').click(function(e) {
		if(listListManager) listListManager.clearAllFilter();
		if(isTreeUsing()) {
			 var count = 0;
			if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
				count = listListManager.getCurrentCheckedId().length;
			} else { 
				$('#lstBox1 option').each(function(){ count++; });
			}
			if(count < 3) {
				alert("Select three or more Accessions.");
				return;
			}
			_showLoadingDialog();
		} else {
			_messageOnScreen("Apply accession list");
		}
		_reset_accession_lists();

		storage.removeItem("_ListsTgt");
//		FROMSCROLL=false;
		var threshold = parseFloat(storage.getItem("_SystemTreeAutoCollapseThreshold"));
		setTimeout(function() {
			syncListsWithCancelPhylipTree(threshold);
		}, 50);
	});

	$('#prm_list_lw_submit').click(function(e) {
		if(listListManager) listListManager.clearAllFilter();
		if(isTreeUsing()) {
			var count = 0;
			if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
				count = listListManager.getCurrentCheckedId().length;
			} else {
				$('#lstBox1 option').each(function(){ count++; });
			}
			if(count < 3) {
				alert("Select three or more Accessions.");
				return;
			}
			_showLoadingDialog();
		} else {
			_messageOnScreen("Apply accession list");
		}
		_reset_accession_lists();

		storage.removeItem("_ListsTgt");
		var threshold = parseFloat(storage.getItem("_SystemTreeAutoCollapseThreshold"));
		setTimeout(function() {
			syncListsWithCancelPhylipTreeLW(threshold);
		}, 50);
	});

	$('#btnRight').click(function(e) {
		var selectedOpts = $('#lstBox1').val();
		if (selectedOpts ==null || selectedOpts.length == 0) {
			alert("Nothing to move.");
			e.preventDefault();
			return;
		}

		var accId2ObjMap = _getAllAccId2listsObj();

		var selectedOptsMap = {};
		for(var i=0,len=selectedOpts.length; i<len; i++) {
			var params = selectedOpts[i].split('|');
			var accId = params[0];
			selectedOptsMap[accId] = true;
		}

		var newLists = [];
		$('#lstBox1 option').each(function(){
			var params = $(this).val().split('|');
			var accId = params[0];
			if(accId in selectedOptsMap) { 
			} else {
				newLists.push(accId2ObjMap[accId]);
			}
		});

		var listsAndDeletedNew = getListsAndDeleted(newLists, getRadioGroupValue("lstBox_grp"));
		setListsForm('lstBox1', 'lstBox2', listsAndDeletedNew[0], listsAndDeletedNew[1], $('#selsub_bSort').val());
	});

	$('#btnLeft').click(function(e) {
		var selectedOpts = $('#lstBox2').val();
		if (selectedOpts ==null || selectedOpts.length == 0) {
			alert("Nothing to move.");
			e.preventDefault();
			return;
		}

		var accId2ObjMap = _getAllAccId2listsObj();

		var newLists = [];
		$('#lstBox1 option').each(function(){
			var params = $(this).val().split('|');
			var accId = params[0];
			newLists.push(accId2ObjMap[accId]);
		});

		var selectedOptsMap = {};
		for(var i=0,len=selectedOpts.length; i<len; i++) {
			var params = selectedOpts[i].split('|');
			var accId = params[0];
			selectedOptsMap[accId] = true;

			newLists.push(accId2ObjMap[accId]);
		}
/*
		var newDeleted = [];
		$('#lstBox2 option').each(function(){
			var params = $(this).val().split('|');
			var accId = params[0];
			if(accId in selectedOptsMap) {
			} else {
				newDeleted.push(accId2ObjMap[accId]);
			}
		});
*/
		var listsAndDeletedNew = getListsAndDeleted(newLists, getRadioGroupValue("lstBox_grp"));
//		var listsAndDeletedNew = getListsAndDeleted(newLists, $('#lstBox_mode').val());
		setListsForm('lstBox1', 'lstBox2', listsAndDeletedNew[0], listsAndDeletedNew[1], $('#selsub_bSort').val());
	});

        $('#addQry').click(function(e) {
		var selectedOpts = $('#idlst').val();
		if (selectedOpts ==null || selectedOpts.length == 0) {
			alert("Nothing to move.");
			e.preventDefault();
			return;
		}

		var selectedOptsMap = {};
		for(var i=0,len=selectedOpts.length; i<len; i++) {
			var params = selectedOpts[i].split('|');
			var accId = params[0];
			selectedOptsMap[accId] = true;
		}

		var accId2ObjMap = _getAllAccId2listsObj();
		var newLists = [];
		$('#idlst option').each(function(){
			var params = $(this).val().split('|');
			var accId = params[0];
			if(accId in selectedOptsMap) {
			} else {
				newLists.push(accId2ObjMap[accId]);
			}
		});

		var listsAndDeletedNew = getListsAndDeleted(newLists, getRadioGroupValue("idlst_grp"));
		setListsForm('idlst', 'tree_qry', listsAndDeletedNew[0], listsAndDeletedNew[1], $('#selsub_pSort').val());
        });

        $('#rmQry').click(function(e) {
		var selectedOpts = $('#tree_qry').val();
		if (selectedOpts ==null || selectedOpts.length == 0) {
			alert("Nothing to move.");
			e.preventDefault();
			return;
		}

		var accId2ObjMap = _getAllAccId2listsObj();

		var newLists = [];
		$('#idlst option').each(function(){
			var params = $(this).val().split('|');
			var accId = params[0];
			newLists.push(accId2ObjMap[accId]);
		});

		var selectedOptsMap = {};
		for(var i=0,len=selectedOpts.length; i<len; i++) {
			var params = selectedOpts[i].split('|');
			var accId = params[0];
			selectedOptsMap[accId] = true;

			newLists.push(accId2ObjMap[accId]);
		}

		var listsAndDeletedNew = getListsAndDeleted(newLists, getRadioGroupValue("idlst_grp"));
		setListsForm('idlst', 'tree_qry', listsAndDeletedNew[0], listsAndDeletedNew[1], $('#selsub_pSort').val());
        });

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

	$("#list_std_bUp,#list_std_bDown").click(function() {
		if(listListManager) {
			if(this.id === 'list_std_bUp') {
				listListManager.moveRows('up');
			} else {
				listListManager.moveRows('down');
			}
		}
	});
});

function _sort_accession(listsFormId, type, order, sub){
	if(!sub) sub = 'grp';

	var lists = [];
	$('#' + listsFormId + ' option').each(function(){
		lists.push($(this).val());
	});
        var sorterByPheno = function(a, b) {
                var aPheno = parseFloat(a.split("|")[4]);
                var bPheno = parseFloat(b.split("|")[4]);
                var ret = (aPheno > bPheno)  ? 1 : -1;
                if(order === "desc") ret = ret * -1;
                return ret;
        };
        var sorterByStr = function(a, b) {
		var aStr = a.split("|")[parseInt(type)];
		var bStr = b.split("|")[parseInt(type)];

		var aFloat = parseFloat(aStr);
		var bFloat = parseFloat(bStr);

		var ret;
		if(isNaN(aFloat) || isNaN(bFloat)) {
			ret = (aStr > bStr) ? 1 : -1;
		} else {
			ret = (aFloat > bFloat)  ? 1 : -1;
		}
		if(order === "desc") ret = ret * -1;
		return ret;
/*
                var aStr = a.split("|")[parseInt(type)];
                var bStr = b.split("|")[parseInt(type)];
                var ret = (aStr > bStr) ? 1 : -1;
                if(order === "desc") ret = ret * -1;
//console.log("Test:" + aStr + " > " + bStr + " = " + ret);
                return ret;
*/
        };

	if(type==4) {
		lists.sort(sorterByPheno);
	} else {
		lists.sort(sorterByStr);
	}

	var newLists = [];
	var accId2ObjMap = _getAllAccId2listsObj();
	for(var i=0,len=lists.length; i<len; i++) {
		var params = lists[i].split("|");
		newLists.push(accId2ObjMap[params[0]]);
	}
	setListsForm(listsFormId, null, newLists, null, sub);
}
function reverseOrder(order) {
	var orderForNext;
	if(order === "asc"){
		orderForNext="desc";
	} else {
		orderForNext="asc";
	}
	return orderForNext;
}
function _sort_accession_phylo(type,order){
	var sub = $('#selsub_pSort').val();
	_sort_accession('idlst', type, order, sub);
	$('#run_sortings').html( getSelectSortedOptionHtml('pSort', type, reverseOrder(order), sub) );
        $('button.asc').button({
		icon: "ui-icon-triangle-1-n",
		iconPosition: "end"
//                icons: {
//                        secondary: 'ui-icon-triangle-1-n'
//                }
        });
        $('button.desc').button({
		icon: "ui-icon-triangle-1-s",
		iconPosition: "end"
//                icons: {
//                        secondary: 'ui-icon-triangle-1-s'
//                }
        });
}
function _sort_accession_list(type, order){
	var sub = $('#selsub_bSort').val();
	_sort_accession('lstBox1', type, order, sub);
	$('#run_sorting').html( getSelectSortedOptionHtml('bSort', type, reverseOrder(order), sub) );
	$('button.asc').button({
		icon: "ui-icon-triangle-1-n",
		iconPosition: "end"
//		icons: {
//			secondary: 'ui-icon-triangle-1-n'
//		}
	});
	$('button.desc').button({
		icon: "ui-icon-triangle-1-s", 
		iconPosition: "end"
//		icons: {
//			secondary: 'ui-icon-triangle-1-s'
//		}
	});
}

//Reset accession list
function _reset_accession_lists() {
	// _Lists
	var value1 = [];
	if(listListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		listListManager.clearAllFilter();
		value1 = listListManager.getCurrentCheckedId();
	} else {
		$("#lstBox1 option").each(function () {
			var valAry = $(this).val().split("|");
			value1.push(valAry[0]);
		}, null);
	}
	_reset_accession_lists_byArray(value1);
}

//Search keyword & jump position

function _dialog_go(){
	/*
	$("#dialog_go").dialog({
		autoOpen: true,
		modal: false,
		width: 800,
		ONdraggable: true,
		resizable: true
	});
	*/
	var p3flg = '';
        for(var i=0; i<minPos.length; i++) {
            if(minPos[i] == 'search') {
                    p3pos = i;
                    p3flg = 1;
            }
        }
        if(p3flg == 1) {
                for(var i=p3pos; i<minPos.length; i++) {
                        if (minPos[i+1] !== undefined) {
                            minPos[i] = minPos[i+1];
                        } else {
                            minPos.pop();
                        }
                        leftpos = (parseInt(175)*(parseInt(i))+ parseInt(5)*(parseInt(i+1)))+'px';
                        $("."+minPos[i+1]+"_window").css('left',leftpos);
                }
        }
	changeDialogZindex(".search_window");

        if($(".under_search").hasClass('fa-window-restore')){
                $(".under_search").toggleClass('fa-window-restore fa-window-minimize');
        }
        if($("#dialog_go").hasClass('minimized')){
                $("#dialog_go").toggleClass('minimized');
                $("#dialog_go").css('top','0px');
                //$("#dialog_go").css('position','fixed');
                $(".search_content").css('display','inline-block');
	        $("#dialog_go").css('width','');
		$("#dialog_go").css('min-height','42px');
		$("#dialog_go").css('min-width','178px');
                $("#search_title").css('width','848px');
                $("#search_title").css('max-width','848px');
                $("#search_title").css('top','4px');
                $("#search_title").css('left','4px');
                $("#dialog_go .minimize").css('top','9px');
                $("#dialog_go .close").css('top','9px');
                $(".search_content").css('width','');
                $("#dialog_go").css('height','');
                $(".search_content").css('height','');
                $("#prm_keyword").val('');
                $("#prm_position").val('');
		
		document.getElementById("searchname").innerHTML = "&nbsp;&nbsp;Search";
                document.getElementById("searchname").style.fontSize = "20px";
        }

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

	// Note that it is looking at the previous search word
/*
	if(storage.getItem("_HighlightVariantGene")) {
		$('#cb_highlight_keyword_variant').prop('checked', true);
	} else { 
		$('#cb_highlight_keyword_variant').prop('checked', false);
	}
*/
	if(storage.getItem("_HighlightVariantExclUpDown") === "1") {
		$('#cb_hlvar_kw_exclude_updown').prop('checked', true);
	} else {
		$('#cb_hlvar_kw_exclude_updown').prop('checked', false);
	}

	_dlg_make_searchAcc();
}
function _dlg_make_searchAcc() {
	// Set Accession
	$('#prm_accession_search').find('option').remove().end()
	var optEmpty = new Option(" --- ", "", false, false);
	$('#prm_accession_search').find('option').remove().end().append(optEmpty).trigger('change');
	var nameType = storage.getItem("_Name");
	var subtitle = storage.getItem("_NameSub");
		if(subtitle == "subvariety" || !subtitle) {subtitle = "grp";}
	if(isTreeUsing()) {
		var accId2ObjMap = _getAllAccId2listsObj();
		var allAccs = treeobj.getAllPotentialNameOrder();
		for(var i=0,len=allAccs.length; i<len; i++) {
			var text = $.format("%-14s %-14s %s", allAccs[i], accId2ObjMap[allAccs[i]].name, accId2ObjMap[allAccs[i]][subtitle]).replace(/\s/g, "\u00A0");	// "&nbsp;" is wrong
//			var text = allAccs[i] + " / " + accId2ObjMap[allAccs[i]].name;
//			var text = allAccs[i];
//			if(nameType !== 'id') text = accId2ObjMap[allAccs[i]].name;
			var opt = new Option(text, allAccs[i], false, false);
			$('#prm_accession_search').append(opt);
//			$('#prm_accession_search').append(opt).trigger('change');
		}
		$('#prm_accession_search').trigger('change');
	} else {
		var allAccs = _getAccListObjArray("_Lists");
//		var allAccs = JSON.parse(storage.getItem("_Lists"));
		for(var i=0,len=allAccs.length; i<len; i++) {
			var text = $.format("%-14s %-14s %s", allAccs[i].id, allAccs[i].name, allAccs[i][subtitle]).replace(/\s/g, "\u00A0");	// "&nbsp;" is wrong
//			var text = allAccs[i].id + " / " + allAccs[i].name;
//			var text = allAccs[i].id;
//			if(nameType !== 'id') text = allAccs[i].name;
			var opt = new Option(text, allAccs[i].id, false, false);
			$('#prm_accession_search').append(opt);
//			$('#prm_accession_search').append(opt).trigger('change');
		}
		$('#prm_accession_search').trigger('change');
	}
	var highlightAcc = storage.getItem("_AccHighlight");
//	if(highlightAcc !== '' ) $('#prm_accession_search').val(highlightAcc).trigger('change');	// change event occurs! don't use
	if(highlightAcc != null && highlightAcc !== '') {
		$('#prm_accession_search').val(highlightAcc);
		$('#prm_accession_research').prop('disabled', false);
	} else {
		$('#prm_accession_research').prop('disabled', true);
	}
}

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

///////////////////////////// Convert length of chromosome as zoom
function _setHistory(str){
	var a=JSON.parse(storage.getItem("_History"));
//	var isRedundant = false
	for(var i=0,len=a.length; i<len; i++) {
		if(a[i] === str) {
			a.splice(i,1);
			i--;
//			isRedundant = true;
			break;
		} 
	}
//	if(isRedundant) return;

	if(a.length>20) a.pop();
	a.unshift(str);
	storage.setItem("_History",JSON.stringify(a));
	_setComboHistory();
}

//Execute history command
function _historyCmd() {
	var callback = function(type, geneid, chr, stpos, edpos) {
		_changeAutoPosZoom(chr, stpos, edpos);
		setRegionHighlight({"chr":chr, "st":stpos, "en":edpos});	// Region Highlight
		_showLoading();
		if(type === "search") {
			_messageOnScreen("Loading position "+ geneid);
		} else if(type === "position") {
			_messageOnScreen("Loading position "+ stpos + "-" + edpos);
		}
		FROMSCROLL=false;
		_execCanvas();
	};

	var history=parseInt($('#prm_history_cmd').val());
	var h=JSON.parse(storage.getItem("_History"));
	var t=h[history].split(",");
	if(t[0] === "accession") {
		searchAndExpandAccInTree(t[1]);
		_dlg_make_searchAcc();
	} else {
		if(t[0] === "search") {
			_histID(t[0], t[1], callback);
		} else {
			chr = t[1];
			stpos = t[2].replace(/,/g,"");
			edpos = t[3].replace(/,/g,"");
			callback(t[0], null, chr, stpos, edpos);
		}
	}
	_setHistory(h[history]);
}
function _histID(type, keyword, callback) {
        $.ajax({
                url: "./bin/"+_backendSelector("validateGene.php"),
                type: "POST",
                cache: false,
                async: false,
                data: {
			"prm_fa_gene":keyword
                },
                success: function(data) {
                        geneinfo = JSON.parse(data);
			chr = geneinfo['chr'];
			stpos = parseInt(geneinfo['start']);
			edpos = parseInt(geneinfo['end']);
			callback(type, keyword, chr, stpos, edpos);
                }
        });
}
function _jumpPOS(e){
	prm_pos=$('#prm_position').val();

	// "chr01:10001" -> "chr01:10001-10001"
	var res = prm_pos.match(/^([^\:\s]+)\:([\d,]+)$/);
	if(res && res.length == 3) prm_pos = prm_pos + "-" + res[2];

	// "chr01:10001-10001"
	res = prm_pos.match(/^([^\:\s]+)\:([\d,]+)\-([\d,]+)$/);
	if(res && res.length == 4) {
		jumpPosition(prm_pos);

		c = res[1];
		var stpos = res[2].replace(/,/g,"");
		var edpos = res[3].replace(/,/g,"");
		$("#pos_note").empty();
		$("#pos_note").append(c + ":" + stpos + " - " + edpos + " with " + Objects.Block + " blocks");
		FROMSCROLL=false;
		_setHistory("position," + c + "," + stpos + "," + edpos);
	} else {
		_messageOnScreen("Invalid: Position format is invalid");
	}
}

function _searchID(e){
	str=$('#prm_keyword_res').val();
	ids=str.split("|");
	id=ids[0];
	_setHistory("search,"+id);
	if(!str){return;}
	if(str.length>3) {
		_execSearch(str, true);
		$('#prm_keyword_res').blur();
//		$("#dialog_keyword").dialog('close');
//		$("#dialog_go").dialog('close');
	} 
}

function _preSearchID(e){
	if(e.keyCode == 13 || ! e.keyCode){
		str=$('#prm_keyword').val();
		mode=$('#prm_opt').val();
		if(str.length>=3) {
			$('#prm_keyword_res').find('OPTGROUP').remove().end();
			$('#prm_keyword_res').find('option').remove().end().append("<option value=\'\'>Searching...</option>");
			_preExecSearch(str,mode);
			$('#prm_keyword').blur();
			$('#prm_opt').blur();
		} else {
			_drawCanvas();
			_messageOnScreen("The keyword must have at least 3 characters.");
		}
//		$("#dialog_keyword").dialog('close');
	}
}
function _highlightTrackAccession() {
	var acc = $('#prm_accession_search').val();
	if(acc === '') {
		$('#prm_accession_research').prop('disabled', true);
	} else {
		var text = $('#prm_accession_search  option:selected').text();
		$('#prm_accession_research').prop('disabled', false);
		_setHistory("accession," + acc + "," + text);
		searchAndExpandAccInTree(acc);
	}
}

//Track manager

function _dialog_track(){
	var dialog = $("#dialog_track").dialog({
		autoOpen: true,
		modal: false,
		width: 620,
		draggable: true,
		resizable: true,
//		dialogClass: 'ui-dialog-track-manager'
		classes: { "ui-dialog": "ui-dialog-track-manager"}
	});
	setClickEventToDialog(dialog, '.ui-dialog-track-manager');
	$('#dialog_track').empty();
	$('#dialog_track').append(_html_track());

	changeDialogZindex(".ui-dialog-track-manager");
}

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

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

function _changeViewTrack(Obj) {
	var n=Obj.name.split("_");			// "_track_v_1"
	var v=Obj.options[Obj.selectedIndex].value;	// on/off
	var t=new Object(JSON.parse(storage.getItem('_Tracks')));

	var cmp = "1";
	if ( v == "off" ) {cmp = "0";}

	t[n[3]].p = cmp;
	storage.setItem("_Tracks", JSON.stringify(t));

	if(v == "off") {
		_showLoading();
//		_drawCanvas();
		storage.removeItem("_ListsTgt");
		FROMSCROLL=false;
		_execCanvas();
	} else {
		_drawCanvas();
	}
}

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

	var targetIdx = parseInt(n[3]);
	for (var i=0,len=t.length; i<len; i++) {
		if (i === targetIdx) t[i].h = String(v);
		t[i].s = String(i);
	}
	storage.setItem("_Tracks", JSON.stringify(t));
/*
	var str="[";

	for ( var i=0; i<t.length; i++ ) {
		str=str+"{";
		str=str+"\"track\":\""+t[i].track+"\",";
		str=str+"\"p\":\""+t[i].p+"\",";
		if ( t[i].s == n[3] ){
			str=str+"\"h\":\""+v+"\",";
		} else {
			str=str+"\"h\":\""+t[i].h+"\",";
		}
		str=str+"\"c\":\""+t[i].c+"\",";
		str=str+"\"s\":\""+i+"\"}";
		if ( i < t.length-1 ) {
			str=str+",";
		}
	}
	str=str+"]";
	storage.setItem("_Tracks",str);
*/
	_drawCanvas();
}

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

	for ( var i=0; i<t.length; i++ ) {
		a[i] = i;	// a[fromIndex] = distindex 
	}
	a[n[3]]=v; 
	a[v]=n[3];
*/
	// Swap fromIndex and distIndex
	var fromTrack = _getGffTrackMap('_Track_' + n[3]);
	var distTrack = _getGffTrackMap('_Track_' + v);
//	var fromTrack = storage.getItem('_Track_'+n[3]);
//	var distTrack = storage.getItem('_Track_'+v);
 
	_setGffTrackMapByJson("_Track_" + n[3], JSON.stringify(distTrack));
	_setGffTrackMapByJson("_Track_" + v, JSON.stringify(fromTrack));
//	storage.setItem("_Track_"+n[3], distTrack);
//	storage.setItem("_Track_"+v, fromTrack);

	var tracksFromRef = t[n[3]];
	var tracksDistRef = t[v];
	t[n[3]] = tracksDistRef;
	t[v] = tracksFromRef;
	storage.setItem("_Tracks", JSON.stringify(t));
	$('#dialog_track').empty();
	$('#dialog_track').append(_html_track());
	_drawCanvas();
}


//Help

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


//About

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

//About Tools

function _dialog_about_PRIMER(){
        $("#dialog_about_PRIMER").dialog({
                autoOpen: true,
                modal: true,
                width: 450,
                draggable: true,
                resizable: true
        });
}

function _dialog_about_blast(){
        $("#dialog_about_blast").dialog({
                autoOpen: true,
                modal: true,
                width: 450,
                draggable: true,
                resizable: true
        });
}

function _dialog_about_phytree(){
        $("#dialog_about_phytree").dialog({
                autoOpen: true,
                modal: true,
                width: 450,
                draggable: true,
                resizable: true
        });
}

//About Tools

function _dialog_tutrial(){
        $("#dialog_tutrial").dialog({
                autoOpen: true,
                modal: true,
                width: 650,
                height: 600,
                draggable: true,
                resizable: true
        });
}

//Citation

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


function _dialog_changechr() {
	$('#prm_chr').prop('disabled', true);

//	var selectedVal = $('#prm_chr').val();
	var selectedVal = $('#prm_chr  option:selected').text();
	$("#dialog_changechr").dialog({
		autoOpen: true,
		modal: true,
		width: 270,
		height: 280,
		draggable: false,
		resizable: false,
		close: function (event) { $('#prm_chr').prop('disabled', false); }
	});
	var txtform = $('#dialog_changechr_keyword');
	txtform.val(selectedVal);

	_searchAndSetAllChrs();
	txtform.focus();
}

function _searchAndSetAllChrs() {
	_searchChrsByKeyword(null);
}
function _searchAndSetChrs() {
	var keyword = $('#dialog_changechr_keyword').val();
	_searchChrsByKeyword(keyword);
}

var onLoadChangeChr = 0;	// Prohibit multiple execution of Chr search
function _searchChrsByKeyword(keyword) {
	if(onLoadChangeChr == 1) {
		console.log("Skip _searchChrsByKeyword");
		return;
	}

	onLoadChangeChr = 1;
	var en = new Object(JSON.parse(storage.getItem("_Env")));
	if(keyword) keyword = keyword.replace(new RegExp('^' + en.chromosome_name), '');

	var chrs = JSON.parse(storage.getItem("_Chrs"));
	var prematchRegexp = new RegExp('^' + keyword)
	var ld = "";
	for(var i=0, chrsLen=chrs.length; i<chrsLen; i++) {
		if(!keyword || prematchRegexp.test(chrs[i].id)) {
			ld = ld + "<option value='" + chrs[i].id + "'>" + en.chromosome_name + chrs[i].id + "</option>";
		} 
	}
	$('select#dialog_changechr_list').find('option').remove().end().append(ld);
	onLoadChangeChr = 0;
/*
	onLoadChangeChr = 1;
	$.ajax({
		url: "./bin/chr.php",
		type: "POST",
		cache: false,
		data: {
			"keyword":keyword
		}
	}).done(function(data){
		if(data != null){
			var chrs = new Object(JSON.parse(data));
			var chrsLen = chrs.length;
			if(chrsLen > 0) {
				var ld = "";
				for(var i=0; i<chrsLen; i++) {
					var chr = chrs[i];
					ld = ld + "<option value='" + chr.id + "'>" + en.chromosome_name + chr.id + "</option>";
				}
				$('select#dialog_changechr_list').find('option').remove().end().append(ld);
			} else {
				$('select#dialog_changechr_list').find('option').remove();
			}
		}
		onLoadChangeChr = 0;
	}).fail(function(data){
		onLoadChangeChr = 0;
	});
*/
}
function _changeChrPulldown() {
	var selected = $('select#dialog_changechr_list').val();
	$("select#dialog_changechr_list option").attr("selected", false);
	$('#dialog_changechr').dialog('close');
	$('#prm_chr').prop('disabled', false);
	$('#prm_chr').val(selected).change();	// Change event is not executed just by setting val(). Explicitly change().
}

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

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

function _dlg_reset_confirm() {
	storage.clear();
	_clearAccListObjArray();
	_clearVariantDepthMap();
	_clearGffTrackMap();
	//_initCache();
	location.replace('./');
}


//Variants filter

function _dialog_filter(){
	var dialog = $("#dialog_filter").dialog({
		autoOpen: true,
		modal: false,
		width: 350,
		draggable: true,
		resizable: true,
//		dialogClass: 'ui-dialog-variant-filter'
		classes: { "ui-dialog": "ui-dialog-variant-filter"}
	});
	setClickEventToDialog(dialog, '.ui-dialog-variant-filter');
	$('#prm_quality').val(storage.getItem('_QUAL'));
	$('#prm_depth').val(storage.getItem('_DP'));
	$('#prm_dp4').val(storage.getItem('_DP4'));

	_syncVariantDefaultButton();

	_changeEffGrpForm('filter_effgrp');
	changeDialogZindex(".ui-dialog-variant-filter");
}

/////////////////////////////////////////////// Clear hilighted gene variant
function _clearHighlightedGeneVariant() {
	var highlightVariantGene = storage.getItem("_HighlightVariantGene");

	storage.setItem("_HighlightVariantGene", "");
//	storage.setItem("_HighlightVariantExclUpDown","");
	_reloadCanvas("Clear variant highlight : " + highlightVariantGene);
}

/////////////////////////////////////////////// Change variant Default
function _changeVariantDefault() {
	storage.setItem("_EffGrps", JSON.stringify(_getEffNoFilterArray()));
	storage.setItem("_QUAL", String(DEF_QUAL));
	storage.setItem("_DP", String(DEF_DP));
	storage.setItem("_DP4", String(DEF_DP4));

	// Don't change() because it's very heavy.
	$('#prm_quality').val(String(DEF_QUAL));
	$('#prm_depth').val(String(DEF_DP));
	$('#prm_dp4').val(String(DEF_DP4));
	_changeEffGrpForm('filter_effgrp');

	_syncVariantDefaultButton();

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

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

	_syncVariantDefaultButton();
}

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

	_syncVariantDefaultButton();
}

/////////////////////////////////////////////// Change variant EffImpact
function _changeEffGrp() {
	storage.setItem("_EffGrps", JSON.stringify(_getEffGrpArray("filter_effgrp")));
	_reloadCanvas("Changing filter: SnpEff Variant impact");

	_syncVariantDefaultButton();
}
function _changeEffGrpForm(idPrefix) {
        var impact2checked = _getEffFilterMap();
        for(key in impact2checked) {
                var checkBox = "";
                if(key === "-1") {
                        checkBox = '#' + idPrefix + 'None';
                } else {
                        checkBox = '#' + idPrefix + key;
                }
//                $(checkBox).prop("checked", impact2checked[key]).change();	// Very heavy processing
                $(checkBox).prop("checked", impact2checked[key]);
        }
}
function _getEffGrpArray(idPrefix) {
	var chk3 = $("#" + idPrefix + "3").prop("checked");
	var chk2 = $("#" + idPrefix + "2").prop("checked");
	var chk1 = $("#" + idPrefix + "1").prop("checked");
	var chk0 = $("#" + idPrefix + "0").prop("checked");
	var chkNone = $("#" + idPrefix + "None").prop("checked");

	var array = [];
	if(chk3) array.push(3);
        if(chk2) array.push(2);
        if(chk1) array.push(1);
        if(chk0) array.push(0);
	if(chkNone) array.push(-1);
	return array;
}
function _syncVariantDefaultButton() {
	if(isVariantFiltered()) {
		$('#btn_variant_default').prop("disabled", false);
	} else {
		$('#btn_variant_default').prop("disabled", true);
	}
}

//Options view: block

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

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

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

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

/////////////////////////////////////////////// Change title width
function _changeTitleW(){
	var prewidth=storage.getItem("_TitleW");
	var width=$('#prm_tw').val();
	storage.setItem("_TitleW", width);
//        _syncContentWidth();
	$("#ind").css({'left':'','top':''});
	var preleft;
	if ($("#indicator").css('left') == 'auto') {
		preleft = parseInt(0);
	} else {
		preleft = parseInt($("#indicator").css('left'));
	}
	var indleft = parseInt(preleft)+parseInt(width)-parseInt(prewidth)+'px';
	$("#indicator").css({'position':'absolute','left':indleft,'buttom':'70px'});
	_messageOnScreen("Changing width of title: "+width+" pixel");
	_drawCanvas();	// exec _syncContentWidth() in this.
}

/////////////////////////////////////////////// Change title with ID or Name
function _changeTitleID(){
	//var name=$('#prm_switch_name').val();
	storage.setItem("_Name",$('#prm_switch_name').val());
	var name = storage.getItem("_Name");
	if(name == "id") {
		var prewidth=storage.getItem("_TitleW");
		var width=180;
        	storage.setItem("_TitleW", width);
        	//_messageOnScreen("Changing width of title: "+width+" pixel");
	} else if (name == "name") {
		var prewidth=storage.getItem("_TitleW");
		var width=220;
        	storage.setItem("_TitleW", width);
        	//_messageOnScreen("Changing width of title: "+width+" pixel");
	}
	_drawCanvas();

	if(storage.getItem('_AccmanagerListType') === 'legacy') {
		if ($('#dialog_list').is(":visible")) {
			var lists = getListForm("lstBox1");
			_dlg_make_list(lists);
		}
		if ($('#dialog_phy').is(":visible") && !$("#dialog_phy").hasClass('minimized')) {
			var lists = getListForm("idlst");
			_dlg_make_phylist(lists);
		}
//		syncDlgMakeList();
	}
}

/////////////////////////////////////////////// Change title with ID or Name
function _changeTitleVariety(){
	storage.setItem("_NameSub",$('#prm_switch_sub').val());
	_setTitleColor();
	_dlg_title_color();
	//_update_dlg_title_color_grp();
	_drawTitleColor();
}


//Dialog: Cell information

function _dialog_infocell(str){
	var dialog = $("#dialog_infocell").dialog({
		autoOpen: true,
		modal: false,
		width: 900,
		maxHeight: 600,
		draggable: true,
		resizable: true,
		classes: { "ui-dialog": "ui-dialog-infocell"}
//		dialogClass: 'ui-dialog-infocell'
	});
	setClickEventToDialog(dialog, '.ui-dialog-infocell');
	$('#dialog_cellinformation').empty();
	$('#dialog_cellinformation').append(str);

	changeDialogZindex(".ui-dialog-infocell");
}


//Dialog: Blocks

function _dialog_block(){
	var dialog = $("#dialog_block").dialog({
		autoOpen: true,
		modal: false,
		width: 300,
		draggable: true,
		resizable: true,
		classes: { "ui-dialog": "ui-dialog-block-options"}
//		dialogClass: 'ui-dialog-block-options'
	});
	setClickEventToDialog(dialog, '.ui-dialog-block-options');
	$('#prm_bn').val(storage.getItem('_Block'));
	$('#prm_bh').val(storage.getItem('_BlockH'));
	$('#prm_bw').val(storage.getItem('_BlockW'));

	changeDialogZindex(".ui-dialog-block-options");
}


/////////////////////////////////////////////// Change column(load block)
function _changeBlock(){
	bn = parseInt(storage.getItem("_Block"));
	blkw = parseInt(storage.getItem("_BlockW"));
	var col=parseInt($('#prm_bn').val());
	storage.setItem('_Block', String(col));
//	_syncContentWidth();
	$("#ind").css({'left':'','top':''});
	_showLoading();
	_messageOnScreen("Changing "+Objects.Block+" to "+col+" blocks");
	FROMSCROLL=false;
	_execCanvas();
}

/////////////////////////////////////////////// Change block width
function _changeBlockW(){
        bn = parseInt(storage.getItem("_Block"));
        blkw = parseInt(storage.getItem("_BlockW"));
	var width=parseInt($('#prm_bw').val());
	storage.setItem("_BlockW", width);
//	_syncContentWidth();
	$("#ind").css({'left':'','top':''});
	_messageOnScreen("Changing width of block: "+width+" pixel");
	setTimeout(function() {
		_drawCanvas();
	}, 500);
}

/////////////////////////////////////////////// Change block height
function _changeBlockH(){
	var lastHeight = parseInt(storage.getItem("_BlockH"));
	var height = parseInt($('#prm_bh').val());
	if(isFirefox()) {
		var numAccs = _getAccListObjArray('_Lists').length;
		if(!validBlockHForFirefox(numAccs, height)) {
			alert("This value is invalid because it exceeds Firefox's max element size.");
			$('#prm_bh').val(lastHeight);
			return;
		}
	}
	storage.setItem("_BlockH", height);
	_messageOnScreen("Changing width of height: " + height + " pixel");
/*
	if(lastHeight > height) {
		//TODO: Supports cases where Acc list fits on the screen and does not require DB loading
		_drawCanvas();	// Content size needs to be changed first
		_showLoading();
		 FROMSCROLL=false;
		_execCanvas();
	} else {
		setTimeout("_drawCanvas()", 500);
	}
*/
	setTimeout(function() {
		flgUpdateTree = true;
		_drawCanvas();	// Canvas size needs to be changed first
		drawTrackFromScroll();
	}, 500);
}


//Effect level list

function _dialog_list_effect(){
	var height =  $(window).height() - 5;
	var dialogHeight = $("#dialog_list_effect").height();
	if(height > dialogHeight) height = dialogHeight; 
	$("#dialog_list_effect").dialog({
		autoOpen: true,
		modal: false,
		width: 350,
		height: height,
		draggable: true,
		resizable: true
	});
	$("#dialog_list_effect").scrollTop(0);
}

/////////////////////////////////////////////// Clear Highlight
function _dialog_clearHighlight() {
	if(isAnythingHighlighted()) {
		clearRegionHighlight();
		clearAccHighlight();
		clearSystreeHighlight();
		if(isTreeUsing()) flgUpdateTree = true;
		_drawCanvas();
	} else {
		return void(0);
	}
}
function _dialog_clearRegionHighlight() {
	if(!isRegionHighlighted())  return void(0);

	clearRegionHighlight();
	_drawCanvas();	// execute _setMenu(), _drawIndicator(), _drawDirection() in this
}
function _dialog_clearAccHighlight() {
	if(!isAccHighlighted()) return void(0);

	clearAccHighlight();
	_drawCanvas();	// execute _setMenu(), _drawIndicator(), _drawDirection() in this
}
function _dialog_clearSystreeHighlight() {
	if(!isSystreeHighlighted()) return void(0);

	clearSystreeHighlight();
	if(isTreeUsing()) flgUpdateTree = true;
	_drawCanvas();	// execute _setMenu(), _drawIndicator(), _drawDirection() in this
}
function _dialog_clearVariantFilterAndHighlight() {
	if(!isVariantHighlightGene() && !isVariantFiltered()) return void(0);

	//_dialog_clearVariantHighlight > _clearHighlightedGeneVariant
	var highlightVariantGene = storage.getItem("_HighlightVariantGene");
	storage.setItem("_HighlightVariantGene", "");

	// _dialog_clearVariantFilter > _changeVariantDefault
	_changeVariantDefault();
}
function _dialog_clearVariantHighlight() {
	if(isVariantHighlightGene()) {
		_clearHighlightedGeneVariant();
	} else {
		return void(0);
	}
}
function _dialog_clearVariantFilter() {
	if(isVariantFiltered()) {
		_changeVariantDefault();
	} else {
		return void(0);
	}
}

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

	if(_isUndefined(KeyRelation[depth_max])){depth_max=roundBasedOnArray(depth_max,valArray);}
	if(_isUndefined(KeyRelation[depth_min])){depth_min=roundBasedOnArray(depth_min,valArray);}
	if(_isUndefined(KeyRelation[cstm_max])){depth_max=roundBasedOnArray(cstm_max,valArray);}
	if(_isUndefined(KeyRelation[cstm_min])){cstm_min=roundBasedOnArray(cstm_min,valArray);}
	if(_isUndefined(KeyRelationPct[snp_max])){snp_max=roundBasedOnArray(snp_max,valArrayPct);}
	if(_isUndefined(KeyRelationPct[snp_min])){snp_min=roundBasedOnArray(snp_min,valArrayPct);}
	if(_isUndefined(KeyRelationPct[indel_max])){indel_max=roundBasedOnArray(indel_max,valArrayPct);}
	if(_isUndefined(KeyRelationPct[indel_min])){indel_min=roundBasedOnArray(indel_min,valArrayPct);}
	$("#snp_slider_range_view").text("Range: "+(snp_min)+"% - "+(snp_max)+"%");
	$("#indel_slider_range_view").text("Range: "+(indel_min)+"% - "+(indel_max)+"%");
	$("#depth_slider_range_view").text("Range: "+valArray[KeyRelation[depth_min]]+" - "+valArray[KeyRelation[depth_max]]);
	$("#cstm_slider_range_view").text("Range: "+valArray[KeyRelation[cstm_min]]+" - "+valArray[KeyRelation[cstm_max]]);
	$("#manager_snp_max").val(en.snp_max_col);
	$("#manager_snp_min").val(en.snp_min_col);
	$("#manager_indel_max").val(en.indel_max_col);
	$("#manager_indel_min").val(en.indel_min_col);
	$("#manager_depth_max").val(en.depth_max_col);
	$("#manager_depth_min").val(en.depth_min_col);
	$("#manager_cstm_max").val(en.cstm_max_col);
	$("#manager_cstm_min").val(en.cstm_min_col);
	_drawManagerInd();

	var colormDialog = $("#dialog_color_manager").dialog({
		autoOpen: true,
		modal: false,
		width: 650,
		maxHeight: window.innerHeight-15,
		draggable: true,
		resizable: true,
/*
		position: {
			of:'body',
			at:'center top',
			my:'center top'
		},
*/
		classes: { "ui-dialog": "ui-dialog-color-manager"}
//		dialogClass: 'ui-dialog-color-manager'
	});
	setClickEventToDialog(colormDialog, '.ui-dialog-color-manager');
	changeDialogZindex('.ui-dialog-color-manager');

	var colorObjects=["#manager_snp_max","#manager_snp_min","#manager_indel_max","#manager_indel_min","#manager_depth_max","#manager_depth_min","#manager_cstm_max","#manager_cstm_min"];
	for(var b=0; b<colorObjects.length; b++){
		$(colorObjects[b]).ColorPicker({
			onSubmit: function(hsb, hex, rgb, el) {
				$(el).val("#"+hex);
				$(el).ColorPickerHide();
				_drawManagerInd(1);
			},
			onBeforeShow: function () {
				$(this).ColorPickerSetColor(this.value);
			}
		}).bind('keyup', function(){
			$(this).ColorPickerSetColor(this.value);
		});
	}

	$(function() {
		$( "#snp_slider_range" ).slider({
			range: true,
			min: 0,
			max: valArrayPct.length-1,
			values: [ KeyRelationPct[snp_min], KeyRelationPct[snp_max] ],
			slide: function( event, ui ) {
				if(ui.values[0] >= ui.values[1]){return false;}
				$("#snp_slider_min").val(valArrayPct[ui.values[0]]);
				$("#snp_slider_max").val(valArrayPct[ui.values[1]]);
				$("#snp_slider_range_view").text("Range: "+valArrayPct[ui.values[0]]+"% - "+valArrayPct[ui.values[1]]+"%");
				_changeRangeOfGrad("snp");
			}
		});
		$("#snp_slider_min").val(valArrayPct[$( "#snp_slider_range" ).slider( "values", 0 )]);
		$("#snp_slider_max").val(valArrayPct[$( "#snp_slider_range" ).slider( "values", 1 )]);
	});
	$(function() {
		$( "#indel_slider_range" ).slider({
			range: true,
			min: 0,
			max: valArrayPct.length-1,
			values: [ KeyRelationPct[indel_min], KeyRelationPct[indel_max] ],
			slide: function( event, ui ) {
				if(ui.values[0] >= ui.values[1]){return false;}
				$("#indel_slider_min").val(valArrayPct[ui.values[0]]);
				$("#indel_slider_max").val(valArrayPct[ui.values[1]]);
				$("#indel_slider_range_view").text("Range: "+valArrayPct[ui.values[0]]+"% - "+valArrayPct[ui.values[1]]+"%");
				_changeRangeOfGrad("indel");
			}
		});
		$("#indel_slider_min").val(valArrayPct[$( "#indel_slider_range" ).slider( "values", 0 )]);
		$("#indel_slider_max").val(valArrayPct[$( "#indel_slider_range" ).slider( "values", 1 )]);
	});
	$(function() {
		$( "#depth_slider_range" ).slider({
			range: true,
			min: 0,
			max: valArray.length-1,
			values: [ KeyRelation[depth_min], KeyRelation[depth_max] ],
			slide: function( event, ui ) {
				if(ui.values[0] >= ui.values[1]){return false;}
				$("#depth_slider_min").val(valArray[ui.values[0]]);
				$("#depth_slider_max").val(valArray[ui.values[1]]);
				$("#depth_slider_range_view").text("Range: "+valArray[ui.values[0]]+" - "+valArray[ui.values[1]]);
				_changeRangeOfGrad("depth");
			}
		});
		$("#depth_slider_min").val(valArray[$( "#depth_slider_range" ).slider( "values", 0 )]);
		$("#depth_slider_max").val(valArray[$( "#depth_slider_range" ).slider( "values", 1 )]);
	});
	$(function() {
		$( "#cstm_slider_range" ).slider({
			range: true,
			min: 0,
			max: valArray.length-1,
			values: [ KeyRelation[cstm_min], KeyRelation[cstm_max] ],
			slide: function( event, ui ) {
				if(ui.values[0] >= ui.values[1]){return false;}
				$("#cstm_slider_min").val(valArray[ui.values[0]]);
				$("#cstm_slider_max").val(valArray[ui.values[1]]);
				$("#cstm_slider_range_view").text("Range :"+valArray[ui.values[0]]+" - "+valArray[ui.values[1]]);
				_changeRangeOfGrad("cstm");
			}
		});
		$("#cstm_slider_min").val(valArray[$( "#cstm_slider_range" ).slider( "values", 0 )]);
		$("#cstm_slider_max").val(valArray[$( "#cstm_slider_range" ).slider( "values", 1 )]);
	});
}

function _resetColorEnv(){
	if("snp_min_rate" in Objects){delete Objects.snp_min_rate;}
	if("indel_min_rate" in Objects){delete Objects.indel_min_rate;}
	$.ajax({
		url: "./bin/env.php",
		cache: false,
		async: false
	}).done(function(data){
		storage.setItem("_Env", data);
		_drawCanvas();
		_dialog_colorManager();
	}).fail(function(){
		alert("Failed to get settings from server.");
	});
/*
	_execEnv();
	_drawCanvas();
	_dialog_colorManager();
*/
}

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

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

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

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

function _windowGffClose(){
	var elementcell = document.getElementById("cellinf");
	var elementcellDoc = document.getElementById("cellinf_doc"); 
	elementcellDoc.innerHTML = "";
	elementcellDoc.style.border = "none"; 
	elementcell.style.top = '1px'; 
	elementcell.style.left = '1px';
	elementcellDoc.style.width = 1+"px";
	elementcellDoc.style.height = 1+"px";
	elementcellDoc.style.backgroundColor = 'rgba(0,0,0,0)';
	ctx10.clearRect(0, 0, cvs10.width, cvs10.height);
	ctx10.fillStyle='rgba(0,0,0,0)';
	ctx10.fillRect(0,0,cvs10.width,cvs10.height);
}

function _dialog_phenotypes(){
	var p3flg = '';
        for(var i=0; i<minPos.length; i++) {
            if(minPos[i] == 'gwas') {
                    p3pos = i;
                    p3flg = 1;
            }
        }
        if(p3flg == 1) {
                for(var i=p3pos; i<minPos.length; i++) {
                        if (minPos[i+1] !== undefined) {
                            minPos[i] = minPos[i+1];
                        } else {
                            minPos.pop();
                        }
                        leftpos = (parseInt(175)*(parseInt(i))+ parseInt(5)*(parseInt(i+1)))+'px';
                        $("."+minPos[i+1]+"_window").css('left',leftpos);
                }
        }

        $("#dialog_phenotypes").css('height',$("#tasuke").height() - 20);
        $(".gwas_content").css('height',$("#tasuke").height()-63);

        $("#dialog_phenotypes").css('max-height', "2048px");
        $(".gwas_content").css('max-height', "2005px");

        $("#dialog_phenotypes").css('display','inline-block');
	$(".effgrp_checkbox").prop('checked',true);
	if ($('input[name=changeSort]:eq(0)').prop('checked')) {
		$('input[name=changeSort]:eq(1)').prop('checked',true);
	}
        if($(".under_gwas").hasClass('fa-window-restore')){
		$(".under_gwas").toggleClass('fa-window-restore fa-window-minimize');
	}
        if($("#dialog_phenotypes").hasClass('minimized')){
                $("#dialog_phenotypes").toggleClass('minimized');
                $("#dialog_phenotypes").css('top','0px');
                //$("#dialog_phenotypes").css('position','fixed');
                $(".gwas_content").css('display','inline-block');
                $(".gwas_content").css('background-color','white');
                $("#dialog_phenotypes").css('width','1020px');
                $("#dialog_phenotypes").css('min-width','178px');
                $("#dialog_phenotypes").css('min-height','42px');
                $("#gwas_title").css('width','1008px');
                $("#gwas_title").css('max-width','1008px');
                $("#gwas_title").css('top','4px');
                $("#gwas_title").css('left','4px');
                $("#dialog_phenotypes .minimize").css('top','9px');
                $("#dialog_phenotypes .close").css('top','9px');
                $(".gwas_content").css('width','1016px');
		document.getElementById("gname").innerHTML = "&nbsp;&nbsp;GWAS";
                document.getElementById("gname").style.fontSize = "20px";
        }
	changeDialogZindex(".gwas_window");
	$('#select_phenotype_div').empty();
	$('#choose_pheno').empty();
	var o=new Object(JSON.parse(storage.getItem("_Phenotypes")));
        var selected_phenotype = storage.getItem("_Phenotype");
	var useragent = storage.getItem("_UA");
	var select_phenotype_html = "<table><tr>";
	$('#select_phenotype_div').css({'overflow':'scroll','white-space': 'nowrap','width':'770px','max-height':'90px','border':'1px solid black','margin-top':'10px'});
	for(var i=0;i<o.length;i++){
		select_phenotype_html += "<td><label for=\"gwasd_radio_pheno_" + i + "\" style=\"white-space: nowrap;\">" +
			"<input type=\"radio\" id=\"gwasd_radio_pheno_" + i + "\" class=\"phenotype_radio\" name=\"select_phenotype\" value=\"" + o[i].phenotype + "\"";
		if(o[i].phenotype == selected_phenotype){
			select_phenotype_html += " checked";
		}
		select_phenotype_html += ">" + o[i].phenotype + "</label></td>";
		if(i%4 == 3) {
			if(i < o.length) {
				select_phenotype_html += "</tr><tr>";
			} else {
				select_phenotype_html += "</tr>";
			}
		}
	}
	select_phenotype_html += "</table>";
	$('#select_phenotype_div').append(select_phenotype_html);

	storage.setItem("_Sort","Probability");
	var selected_chr = "all";
	make_phenotype_gene_table(selected_chr,selected_phenotype,"Probability");
	_setClickPhenotypeRadioEvent();
//	_setClickSnpEffCheckboxEvent();
	//_setClickEffGrpCheckboxEvent();
	_filterEffGrpEvent();
	_setClickCloseEvent();
	var phenotype_png_name = selected_phenotype.replace(/\s+/g, "_");
	_createGWAS(selected_phenotype);
	//$("#plot_img").attr("src", "images/plot/plot_" + phenotype_png_name + ".png");
/*
	$("#dialog_phenotypes").dialog({
		autoOpen: true,
		//modal: true,
		modal: false,
		width: 855,
		maxHeight: window.innerHeight-15,
		draggable: true,
		resizable: true,
                position: {
                        of:'body',
                        at:'top',
                        my:'center'
                }
	});
*/

	$(".gwas_content").scrollTop(0);
}

function make_phenotype_gene_table(selected_chr,selected_phenotype,sort_term){
	if ( $.fn.dataTable.isDataTable("#phenotype_gene_table") ) {
		$('#phenotype_gene_table').DataTable().destroy();
	}
	$('#phenotype_gene_table').empty();
	var en = new Object(JSON.parse(storage.getItem("_Env")));

	var thSnpeff = "SnpEff Impact level<span onclick=\"_dialog_list_effect();\" style=\"cursor:pointer;\"><img src=\"./images/info_label.png\" width=\"11px\"></span>";
	$('#phenotype_gene_table').DataTable( {
		"destroy": true,
		"processing": true,
		"serverSide": true,
		"searching": false,
		"ordering": false,
		"displayLength": 25,
		"ajax": {
			"url": "./bin/phenotype_gene.php",
			"type": "POST",
			"data": function ( d ) {
				d.chr = selected_chr;
				d.sort_term = sort_term;
				d.prm_phenotype = selected_phenotype;
				d.prm_effgrps = $("input[name='effgrp_checkbox']:checked").map(function(){
                                        return $(this).val();
                                }).get();
			},
			"complete": function() {

			}
		},
		columnDefs: [
			{ "targets": 0, "name": "chr", "title": "Chr", 
				"data": function (row, type, set, meta) {
					return "<div align=\"center\">" + en.chromosome_name + row[0] + "</div>";
				}},
			{ "targets": 1, "name": "pos", "title": "Pos", 
				"data": function (row, type, set, meta) {
					return "<div align=\"center\"><a href=\"javascript:_moveVarpos('" + row[0] + "|" + row[1] + "');\"title=Move this position.\">" + row[2] + "</a></div>";
				}},
			{ "targets": 2, "name": "pobability", "title": "Probability(-log<sub><small>10</small>)", 
				"data": function (row, type, set, meta) {
					return "<div align=\"center\">" + row[3] + "</div>";
				}},
			{ "targets": 3, "name": "geneid", "title": "Gene ID", 
				"data": function (row, type, set, meta) {
					return "<span class=\"GeneID\">" + row[4] + "</span>";
				}},
			{ "targets": 4, "name": "name", "title": "Name", 
				"data": function (row, type, set, meta) {
					return "<span class=\"Name\">" + row[5] + "</span>"
				}},
			{ "targets": 5, "name": "snpeff", "title": thSnpeff, "data": 6},
		]
	});

	$("#pheno_chr").off("change");
	$("#pheno_chr").find('option').remove();
	if(selected_chr === "all") {
		$("#pheno_chr").append("<option value='all' selected>all</option>");
	}else {
		$("#pheno_chr").append("<option value='all'>all</option>");
	}

	var o=new Object(JSON.parse(storage.getItem("_Chrs")));
	for (i=0;i<o.length;i++) {
		if (selected_chr === o[i].id) {
			$("#pheno_chr").append("<option value=\"" + o[i].id + "\" selected>" + en.chromosome_name + o[i].id + "</option>");
		} else {
			$("#pheno_chr").append("<option value=\"" + o[i].id + "\">" + en.chromosome_name + o[i].id + "</option>");
		}
	}
	$("#pheno_chr").on("change", function() {_changeChrPheno(selected_phenotype);});
}

function make_phenotype_gene_eff_table(selected_phenotype){
	if ( $.fn.dataTable.isDataTable("#phenotype_gene_table") ) {
		$('#phenotype_gene_table').DataTable().destroy();
	}
	$('#phenotype_gene_table').empty();
	var phenotype_gene_table_html = '<thead><tr><th>Species</th><th>Chr</th><th>Pos</th><th>Prob</th><th>Gene ID</th><th>Name</th><th>Description</th><th>Eff Name</th><th>Eff Group</th></tr></thead>';
	phenotype_gene_table_html += '<tfoot><tr><th>Species</th><th>Chr</th><th>Pos</th><th>Prob</th><th>Gene ID</th><th>Name</th><th>Description</th><th>Eff Name</th><th>Eff Group</th></tr></tfoot>';
	$("#phenotype_gene_table").append(phenotype_gene_table_html);
	$('#phenotype_gene_table').DataTable( {
		"destroy": true,
		"processing": true,
		"serverSide": true,
		"searching": false,
		"ordering": false,
		"ajax": {
			"url": "./bin/phenotype_gene_eff.php",
			"type": "POST",
			"data": function(d){
				d.prm_phenotype = selected_phenotype;
				d.prm_effgrps = $("input[name='effgrp_checkbox']:checked").map(function(){
					return $(this).val();
				}).get();
			},
			"complete": function() {

			}
		}
	});
}	 

function _dialog_gwas_plot(){    
	$("#dialog_gwas_plot").dialog({
		autoOpen: true,
		modal: true,
		width: 500,
		draggable: true,
		resizable: true
	});
}
/*
function _dialog_phenotype_paper(i){
	var o = _getAccListObjArray('_Lists');
//	var o=new Object(JSON.parse(storage.getItem('_Lists')));
	var paper_array = _getPhenotypePapers(o[i].id, storage.getItem("_Phenotype"));
	var phenotype_paper_html = '';
	$("#phenotype_paper_div").empty();
	for(var j = 0; j < paper_array.length; j++){
		phenotype_paper_html += '<div id="paper_' + j + '_div" class="paper_div">';
		phenotype_paper_html += '<div id="paper_' + j + '_title_str_div" class="paper_dialog_head_div">Title</div>';
		phenotype_paper_html += '<div id="paper_' + j + '_title_div" class="paper_dialog_content_div">' + paper_array[j].title + '</div>';
		phenotype_paper_html += '<div id="paper_' + j + '_author_str_div" class="paper_dialog_head_div">Author</div>';
		phenotype_paper_html += '<div id="paper_' + j + '_author_div" class="paper_dialog_content_div">' + paper_array[j].author + '</div>';
		phenotype_paper_html += '<div id="paper_' + j + '_pmid_str_div" class="paper_dialog_head_div">PMID</div>';
		phenotype_paper_html += '<div id="paper_' + j + '_pmid_div"  class="paper_dialog_content_div"><a href="http://www.ncbi.nlm.nih.gov/pubmed/' + paper_array[j].PMID + '" target="_blank">' + paper_array[j].PMID + '</a></div>';
		phenotype_paper_html += '<div id="paper_' + j + '_abst_str_div" class="paper_dialog_head_div">Abstract</div>';
		phenotype_paper_html += '<div id="paper_' + j + '_abst_div"  class="paper_dialog_content_div">' + paper_array[j].abst + '</div></div>';
	}
	if (phenotype_paper_html=='') {
		phenotype_paper_html += '<br><br><font size="4">There is no paper information about this phenotype.</font><br><br><br>';
	}
	$("#phenotype_paper_div").append(phenotype_paper_html);
	$("#dialog_phenotype_paper").dialog({
		autoOpen: true,
		modal: true,
		width: 500,
		draggable: true,
		resizable: true
	});
}
*/
function _SyncPrimer32Expseq() {
        chr = $("#prm_rp3_chr").val();
        tgts = $("#prm_rp3_tgt").val();
        tgte = $("#prm_rp3_tgt_e").val();
        flk = $("#prm_rp3_flk").val();
	sl = document.getElementById("flk_len");
        avd = $("#prm_rp3_avd").val();
        //Ns = $("#prm_rp3_Ns").val();
	form = document.forms.prm_rp3_Ns;
	Ns = form.Ns_selection.value;
        qual = $("#prm_rp3_qual").val();
        dp = $("#prm_rp3_dp").val();
	$("#prm_p3_chr").val(chr).trigger('change');
//	$("#prm_p3_chr").select2().val(chr).change();	// Does not work properly in IE
//        $("#prm_p3_chr").val(chr);
        $("#prm_p3_tgt").val(tgts);
        $("#prm_p3_tgt_e").val(tgte);
        $("#prm_p3_flk").val(flk);
        $("#prm_p3_avd").val(avd);
        $("#prm_p3_Ns").val(Ns);
        $("#prm_p3_qual").val(qual);
        $("#prm_p3_dp").val(dp);
        $("#prm_p3_s").val(parseInt(tgts)-parseInt(flk));
        $("#prm_p3_e").val(parseInt(tgte)+parseInt(flk));
        flk5=parseInt(flk);
        flk3=parseInt(flk);
        if((parseInt(tgts)-flk) < 0){flk5=parseInt(tgts)-1;}
         sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
	if(Ns==1) {
		_showVarsite2(Ns);
                var element = document.getElementById( "prm_rp3_Ns2" ) ;
                var elements = element.Ns2_selection ;
                elements[0].checked = true;
	} else if (Ns==0) {
		_hideVarsite2(Ns);
                var element = document.getElementById( "prm_rp3_Ns2" ) ;
                var elements = element.Ns2_selection ;
                elements[1].checked = true;
	}
	_dialog_p3_len();
}

//TODO _dialog_rp3_len is called twice
function _SyncExpseq2Primer3() {
        chr = $("#prm_p3_chr").val();
        tgts = $("#prm_p3_tgt").val();
        tgte = $("#prm_p3_tgt_e").val();
        flk = $("#prm_p3_flk").val();
	sl = document.getElementById("flk_len");
        avd = $("#prm_p3_avd").val();
        //Ns = $("#prm_p3_Ns").val();
        form = document.forms.prm_rp3_Ns2;
        Ns = form.Ns2_selection.value;
        qual = $("#prm_p3_qual").val();
        dp = $("#prm_p3_dp").val();
	$("#prm_rp3_chr").val(chr).trigger('change');
//	$("#prm_rp3_chr").select2().val(chr).change();	// Does not work properly in IE
//        $("#prm_rp3_chr").val(chr);
        $("#prm_rp3_tgt").val(tgts);
        $("#prm_rp3_tgt_e").val(tgte);
        $("#prm_rp3_flk").val(flk);
        $("#prm_rp3_avd").val(avd);
        $("#prm_rp3_Ns").val(Ns);
        $("#prm_rp3_qual").val(qual);
        $("#prm_rp3_dp").val(dp);
        $("#prm_rp3_s").val(parseInt(tgts)-parseInt(flk));
        $("#prm_rp3_e").val(parseInt(tgte)+parseInt(flk));
        flk5=parseInt(flk);
        flk3=parseInt(flk);
        if((parseInt(tgts)-flk) < 0){flk5=parseInt(tgts)-1;}
        if((parseInt(tgte)+flk) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-parseInt(tgte);}
         sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
        if(Ns==1) {
                _showVarsite(Ns);
		var element = document.getElementById( "prm_rp3_Ns" ) ;
		var elements = element.Ns_selection ;
		elements[0].checked = true;
        } else if (Ns==0) {
                _hideVarsite(Ns);
		var element = document.getElementById( "prm_rp3_Ns" ) ;
                var elements = element.Ns_selection ;
                elements[1].checked = true;
        }
	_dialog_rp3_len();
}

function _checkNs(lprm_from,lprm_to,rprm_from,lprm_to,chrv) {
	var Nspos = "";
	$.ajax({
        	url: "./bin/"+_backendSelector("checkNs.php"),
                type: "POST",
                cache: false,
		async: false,
                data: {
                	"prm_lprm_from":lprm_from,
                        "prm_lprm_to":lprm_to,
                        "prm_rprm_from":rprm_from,
                        "prm_rprm_to":rprm_to,
                        //"prm_s_from":s_from,
                        //"prm_s_to":s_to,
                        "prm_chr":chrv,
                        "prm_list":_getList("db").toString()
                },
                success: function(data) {
			Nspos = data;
                }
	});
	 return Nspos;
}

function _createHelp(text_id){
	document.getElementById("dialog_p3").onclick = function(e) {
        	var elementcell = document.getElementById("helptext");
        	var elementcellDoc = document.getElementById("helptextDoc");
		var boux = e.pageX;
		var bouy = e.pageY;
		elementcell.style.position = "fixed";
		elementcell.style.left = (boux+10) + 'px';
        	elementcell.style.top = (bouy+8) + 'px';
                //elementcellDoc.style.width = (180)+"px";
                elementcellDoc.style.height = (18)+"px";
                elementcellDoc.style.backgroundColor = 'white';
		if($.isNumeric(text_id)) {
			if(text_id==1) {
				elementcellDoc.style.width = (180)+"px";
				str = "<font>&nbsp;Target for primer designing</font>";
			} else if (text_id==2) {
                                elementcellDoc.style.width = (235)+"px";
                                str = "<font>&nbsp;Primer is selected from this region.</font>";
                        } else if (text_id==3) {                                                                elementcellDoc.style.width = (290)+"px";
                                str = "<font>&nbsp;Primer does not overlap around the target.</font>";
                        } else if (text_id==4) {                               
                                elementcellDoc.style.width = (260)+"px";
                                str = "<font>&nbsp;Variant sites are replaced by 'N' letter.</font>";
                        } else if (text_id==5) {
                                elementcellDoc.style.width = (290)+"px";
                                str = "<font>&nbsp;Quality threshold for variant sites masking.</font>";
			} else if (text_id==6) {
                                elementcellDoc.style.width = (290)+"px";
                                str = "<font>&nbsp;Depth threshold for variant sites masking.</font>";
			} else if (text_id==7) {
                                elementcellDoc.style.width = (165)+"px";
                                str = "<font>&nbsp;mask as \"N\" in the input</font>";
			} else if (text_id==8) {
                                elementcellDoc.style.width = (160)+"px";
                                str = "<font>&nbsp;only highlight in results</font>";
			} else if (text_id==9) {
                                elementcellDoc.style.width = (300)+"px";
				elementcellDoc.style.height = (36)+"px";
                                str = "<font>&nbsp;Using the e-PCR option, you can check the specificity of the primer predicted primer3.</font>";
                        }
	        	elementcellDoc.innerHTML = str;
       	        	elementcellDoc.style.border = "solid 1px black";
		} else {
			elementcellDoc.style.backgroundColor = "";
			str = "";
                        elementcellDoc.innerHTML = str;
                        elementcellDoc.style.border = "";
		}
		text_id = "";
	}
}

function _createHelp2(text_id){
        document.getElementById("dialog_p3").onclick = function(e) {
                var elementcell = document.getElementById("helptext2");
                var elementcellDoc = document.getElementById("helptextDoc2");
                var boux = e.pageX;
                var bouy = e.pageY;
                elementcell.style.position = "fixed";
                elementcell.style.left = (boux+10)+'px';
                elementcell.style.top = (bouy+8)+'px';
                //elementcellDoc.style.width = (180)+"px";
                elementcellDoc.style.height = (18)+"px";
                elementcellDoc.style.backgroundColor = 'white';
                if($.isNumeric(text_id)) {
                        if(text_id==1) {
                                elementcellDoc.style.width = (180)+"px";
                                str = "<font>&nbsp;Target for primer designing</font>";
                        } else if (text_id==2) {
                                elementcellDoc.style.width = (235)+"px";
                                str = "<font>&nbsp;Primer is selected from this region.</font>";
                        } else if (text_id==3) {                                                                e
				elementcellDoc.style.width = (290)+"px";
                                str = "<font>&nbsp;Primer does not overlap around the target.</font>";
                        } else if (text_id==4) {
                                elementcellDoc.style.width = (260)+"px";
                                str = "<font>&nbsp;Variant sites are replaced by 'N' letter.</font>";
                        } else if (text_id==5) {
                                elementcellDoc.style.width = (290)+"px";
                                str = "<font>&nbsp;Quality threshold for variant sites masking.</font>";
                        } else if (text_id==6) {
                                elementcellDoc.style.width = (290)+"px";
                                str = "<font>&nbsp;Depth threshold for variant sites masking.</font>";
                        }
                        elementcellDoc.innerHTML = str;
                        elementcellDoc.style.border = "solid 1px black";
                } else {
                        elementcellDoc.style.backgroundColor = "";
                        str = "";
                        elementcellDoc.innerHTML = str;
                        elementcellDoc.style.border = "";
                }
                text_id = "";
        }
}

function _helpEvent() {
	$(".help_tgt").mouseover(function(){
		///nothing///
	}).mouseout(function() {
		var elementcellDoc = document.getElementById("helptextDoc");
		elementcellDoc.style.backgroundColor = "";
        	str = "";
        	elementcellDoc.innerHTML = str;
        	elementcellDoc.style.border = "";
	});
}

function _helpEvent2() {
        $(".help_tgt").mouseover(function(){
                ///nothing///
        }).mouseout(function() {
                var elementcellDoc = document.getElementById("helptextDoc2");
                elementcellDoc.style.backgroundColor = "";
                str = "";
                elementcellDoc.innerHTML = str;
                elementcellDoc.style.border = "";
        });
}

function searchOnTrack() {
	var query = document.getElementById("searchTrk").value.replace(/^\s+/,'').replace(/\s+$/,'');

	// "chr01:10001" -> "chr01:10001-10001"
        var res = query.match(/^([^\:\s]+)\:([\d,]+)$/);
        if(res && res.length == 3) query = query + "-" + res[2];

	// "chr01:10001-10001"
        res = query.match(/^([^\:\s]+)\:([\d,]+)\-([\d,]+)$/);
        if(res && res.length == 4) {
//	if(/:/.test(query)) {
		jumpPosition(query);
	} else {
		// Keyword search
		$(".search_window").css('display','inline-block');
		document.getElementById("prm_keyword").value=query;
		_dialog_go();
		_preSearchID(1);

		// Accession search
		var valid = false;
		$('#prm_accession_search option').each(function(){
			if($(this).val() === query) {
				valid = true;
				return false;	// break
			}
		});
		if(valid) {
			$('#prm_accession_search').val(query);
			$('#prm_accession_research').prop('disabled', false);
		}
	}
}
function searchOnTrackByRuturn(e) {
	if(e.keyCode===13) {
		console.log(e);
		searchOnTrack();
	}
}
function jumpPosition(query) {
        //search chromosome pos//
                qpos = query;
                query = "all|";
                var chrpos = qpos.split(":");
                var posinfos = chrpos[1].split("-");

		var en = new Object(JSON.parse(storage.getItem("_Env")));
		if(en.chromosome_name) chrpos[0] = chrpos[0].replace(new RegExp('^' + en.chromosome_name), '');

		prm_fa_s = posinfos[0].replace(/,/g,"");
		prm_fa_e = posinfos[1].replace(/,/g,"");
		//validate chr and pos keyword
		$.ajax({
                	url: "./bin/"+_backendSelector("validateChr.php"),
                	type: "POST",
                	cache: false,
                	data: {
				"prm_fa_chr":chrpos[0],
                        	"prm_fa_s":prm_fa_s,
                        	"prm_fa_e":prm_fa_e,
                        	"prm_blk":storage.getItem("_Block")
			},
			success: function(data) {
			 	var errflgs = data;
				var errstr = "";
				if (errflgs != "") {
					if (errflgs.match(/1/)) {
						errstr = "Invalid:string is entered on the position!!";
					} 
					if (errflgs.match(/2/)) {
						if(errstr != "") {
							errstr += "<br>Invalid:start position and end position is reversed!!";
						} else {
							errstr += "Invalid:start position and end position is reversed!!";
						}
					}
                                        if (errflgs.match(/3/)) {
						if(errstr != "") {
							errstr += "<br>Invalid:the length between start to end is longer than " + parseInt(100000*storage.getItem("_Block")) +"bp!!";
						} else {
							errstr = "Invalid:the length between start to end is longer than " + parseInt(100000*storage.getItem("_Block")) +"bp!!";
						}
                                        }
                                        if (errflgs.match(/4/)) {
						if (!errflgs.match(/5/)) {
							if(errstr != "") {
                                                		errstr += "<br>Invalid:the position you entered is out of range on this chromosome!!";
							} else {
                                                		errstr = "Invalid:the position you entered is out of range on this chromosome!!";
							}
						}
                                        }
                                        if (errflgs.match(/5/)) {
						if(errstr != "") {
                                                	errstr += "<br>Invalid:this chromosomeis not registered!!";
						} else {
                                                	errstr = "Invalid:this chromosomeis not registered!!";
						}
                                        }
					_messageOnScreen(errstr);
				} else {
					_changeAutoPosZoom(chrpos[0], prm_fa_s, prm_fa_e);
					setRegionHighlight({"chr":chrpos[0], "st":prm_fa_s, "en":prm_fa_e});	// Region Highlight
//                                        addRegionHighlight({"chr":chrpos[0], "st":prm_fa_s, "en":prm_fa_e});	// Region Highlight
                			_changeChromosomeSearch(chrpos[0]+":"+posinfos[0]+"bp - "+posinfos[1]+"bp"+" with 100blocks");
				}
			}
		});
}

function _dialog_gwas_btn(){
        prm_effgrps = $("input[name='effgrp_checkbox']:checked").map(function(){
                return $(this).val();
        }).get();
        sub = document.getElementById("filterbtn");
        if(prm_effgrps.length > 0) {
                sub.innerHTML = '<button type=\"submit\" id=\"filterbtn\" value=\"refresh\">Refresh</button>';
        } else {
                sub.innerHTML = '<button type=\"submit\" id=\"filterbtn\" value=\"refresh\" disabled>Refresh</button>';
        }
}

function _validateGene(gene, callback) {
        gene = _escapeHTML(gene);
        $.ajax({
                url: "./bin/"+_backendSelector("validateGene.php"),
                type: "POST",
                async:false,
                cache: false,
                data: {
                        "prm_fa_gene":gene,
                },
                success: function(data) {
			var hash = JSON.parse(data);
			callback(hash);
                }
        });
}
/*
function _getCDSlength(id) {
        id = _escapeHTML(id);
        reg_info = {};
        $.ajax({
                url: "./bin/"+_backendSelector("getCDSLength.php"),
                type: "POST",
                async:false,
                cache: false,
                data: {
			"prm_objid":id
                },
                success: function(data) {
                        reg_info=data;
                }
        });
        return JSON.parse(reg_info);
}
*/
function _createGWAS(phenostr) {
	var chrstr = $('#pheno_chr').val();
	var phenotype = phenostr;
        $.ajax({
        	url: "./bin/getQqdata.php",
                type: "POST",
                cache: false,
                async: false,
                data: {
                	"chr": chrstr,
                        "phenotype":phenotype
                },
                success: function(datas) {
                        forplot = datas;
                }
        });
        var json = JSON.parse(forplot);
        var chrs = json['chrs'];
        var forplots = json['probs'];
//        forplots = forplot.split("|");
        var chrinfo = {};
        var chrtotal = 0;
        for(var i=0, chrLen=chrs.length; i<chrLen; i++) {
                chrinfo[chrs[i][0]] = {ind:i, size:chrs[i][1]};
                chrtotal++;
        }
//        var datas = "[";
        var prechr="";
//        var pnum = forplots.length - 1;
        var colornum = 0;
        var tickary = [];
	var xmax;
	if (chrstr == "all") {
		zrange = [0, chrtotal];
		xmax = chrtotal;
		for(var i=0; i<chrtotal; i++) {
			tickary.push([i, chrs[i][0]]);
		}
	} else {
		zrange = [0, chrs[0][1]];
		xmax = chrs[0][1];
		var unit = 5000000;
		var loop = 0;
		while(true) {
			tickary.push([unit*loop, String(unit*loop)]);
			loop++;
			if(unit * loop > chrs[0][1]) break;
		}
	}

	var d2 = [];
	for (var i = 0, forplotsLen=forplots.length; i<forplotsLen; i++) {
//        for (var i = 0; i<forplots.length;i++) {
//        	var forplotss = forplots[i].split("--SPL--");
//                var chrpos = forplotss[2];
//		var chrlen = forplotss[3];
//		var posinfo = chrpos.split(" ");
//		var chr = posinfo[0];
		var chr = forplots[i][0];
		if(!chrinfo[chr]) continue;

		var chrlen = chrinfo[chr]['size'];
		var pos = forplots[i][1];
		if(pos > chrlen) continue;

		var prob = forplots[i][2];
                var color="";

		var plotx;
		if (chrstr == "all") {
			if (prechr != chr) colornum += 1;
			plotx = pos / chrinfo[chr]['size'] + chrinfo[chr]['ind'];
		} else {
			plotx = pos;
		}
/*
		if (chrstr == "all") {
                	if (prechr != chr) {
                       		tickary.push([colornum, chr]);
                       		colornum += 1;
                	}
		} else {
			tickary = Math.floor(chrlen/5000000);
		}
*/
                if (colornum %2 == 0) {
                	color = "#00bfff";
                } else if ( colornum % 2 == 1) {
                	color = "#00ffff";
                }

                prechr = chr;

		var label = chr + " " + pos.toLocaleString();
		d2.push( {label:label, color:color, points:{fillColor:color}, data: [[plotx, prob]]} );
//		datas += "{\"label\":\"" + label + "\",\"color\":\"" + color + "\",\"points\":{\"fillColor\":\"" + color + "\"},\"data\":[[" + plotx + "," + prob + "]]},";
/*
                datas += "{\"label\":\"" + chrpos + "\",\"color\":\"" + color + "\",\"points\":{\"fillColor\":\"" + color + "\"},\"data\":[[" + forplotss[0] + "," + forplotss[1] + "]]},";
                if (i == pnum) {
                	datas = datas.slice(0,-1);
                        datas += "]";
                }
*/
	}
        var labelopt = "axisLabel: \"Chromosome and Position\"";
        titlediv = document.getElementById("title");
	if (chrstr == "all") {
        	titlediv.innerHTML = phenotype;
	} else {
		titlediv.innerHTML = phenotype+":"+chrstr;
	}
        var data = d2;
/*
	var o=new Object(JSON.parse(storage.getItem("_Chrs")));
	if(chrstr == "all") {
		zrange = [0, o.length];
	} else {
		zrange = [0, chrlen];
	}
*/
        var options = {
        	series: {
                	points: {
                        	show: true,
                        	fill: true,
				radius: 3
                        }
                },
                grid: {
                   	hoverable: true,
                      	clickable: true
                },
                legend: {
                        show: false
                },
                xaxis: {
                	color: "black",
                        axisLabel: "Chromosome and Position",
                        ticks:tickary,
                        min: 0,
                        max: xmax,
                        axisLabelUseCanvas: true,
                        axisLabelFontSizePixels: 12,
                        axisLabelFontFamily: 'Verdana, Arial',
                        axisLabelPadding: 10,
                        zoomRange:zrange,
                        panRange:zrange,
               	},
                yaxis: {
                  	color: "black",
                        axisLabel: "P-value(-log10)",
                        axisLabelUseCanvas: true,
                        axisLabelFontSizePixels: 12,
                        axisLabelFontFamily: 'Hebratica, Arial',
                        axisLabelPadding: 5,
                        zoomRange: false,
                        panRange: false,
             	},
                zoom: {
                        interactive: true
                },
                pan: {
                        interactive: true
                }
   	};

        var plot = $.plot("#placeholder", data, options);

        $("#placeholder").bind("plotselected", function (event, ranges) {
        	$.each(plot.getXAxes(), function(_, axis) {
        		var opts = axis.options;
       			opts.min = ranges.xaxis.from;
               		opts.max = ranges.xaxis.to;
       		});
        	plot.setupGrid();
        	plot.draw();
        	plot.clearSelection();
    	});

        $("#placeholder").bind("plotpan", function (event, plot) {
             	var axes = plot.getAxes();
        });

        $("#placeholder").bind("plotzoom", function (event, plot) {
               	var axes = plot.getAxes();
        });
        $("<div id='tooltip' onclick=\"\"></div>").css({
         	position: "absolute",
                display: "none",
                border: "1px solid #fdd",
                padding: "2px",
               	"background-color": "#fee",
                opacity: 0.80
       	}).appendTo("body");

        $("#placeholder").bind("plothover", function (event, pos, item) {
        	if (item) {
                      	var x = item.datapoint[0],
                            y = item.datapoint[1].toFixed(4);

                        //$("#tooltip").html("position : "+item.series.label+"<br>phtnotype : "+ phenotype + "<br> p-value\(-log10\) : "+y)
                        $("#tooltip").html("position : "+item.series.label+"<br>phenotype : "+ phenotype + "<br> p-value\(-log10\) : "+y+"<input type=\"hidden\" id=\"tippos\" value=\""+item.series.label+"\"/>")

                                     .css({top: item.pageY+5, left: item.pageX+5})
                                     .fadeIn(200);
           	} else {
                    	$("#tooltip").hide();
                }
     	});

        var isiPad = navigator.userAgent.match(/iPad/i) != null;
        var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
        var isAndroid = navigator.userAgent.match(/Android/i) != null;
        if (isiPad || isiPhone || isAndroid) {    //iPad & iPhone & Android
                $(document).bind("click","#tooltip",function () {
                        var tipdoc = document.getElementById("tippos");
			if(tipdoc != null) {
                            var tippos = tipdoc.value;
       	                    var labels = tippos.split(" ");
       	                    var chr = labels[0];
                            var pos = labels[1];
                            pos = pos.replace(/,/g,"");
                            _moveVarpos(chr+"|"+pos);
			}
                });
        } else {
                $("#placeholder").bind("plotclick", function (event, pos, item) {
                        if (item) {
                                var label = item.series.label;
                                var labels = label.split(" ");
                                var chr = labels[0];
                                var pos = labels[1];
                                pos = pos.replace(/,/g,"");
                                _moveVarpos(chr+"|"+pos);
                        }
                });
        }


	$('#placeholder').bind('touchstart', function(){
		$(window).on('touchmove.noScroll', function(e) {
			e.preventDefault();
		});
	});

	$('#placeholder').bind('touchend', function(){
		$(window).off('.noScroll');
	});
	
	var movePoint = { x: 0, y: 0 };
	$('#placeholder').bind('gesturestart', function(ev){
		movePoint.x = ev.originalEvent.layerX;
		movePoint.y = ev.originalEvent.layerY;
	});
					
	$('#placeholder').bind('gesturechange', function(ev){
		var scale = ev.originalEvent.scale;
		var lX = ev.originalEvent.layerX;
		var lY = ev.originalEvent.layerY;
		var position = { "left": lX, "top": lY };
		plot.zoom({"amount": scale, "center": position});
		var moveP = { "left": movePoint.x - lX, "top": movePoint.y - lY};
		plot.pan(moveP);
		movePoint.x = ev.originalEvent.layerX;
		movePoint.y = ev.originalEvent.layerY;
	});
	return chrstr;
}

function _syncChrPheno() {
	var selected_phenotype = storage.getItem("_Phenotype");
	_changeChrPheno(selected_phenotype);
}
function _changeChrPheno(phenotype) {
	var chr = _createGWAS(phenotype);
	var sort = storage.getItem("_Sort");
	make_phenotype_gene_table(chr,phenotype,sort);
}

var jqxhrRunPhy = null;
function _stopRunPhy() {
	if(jqxhrRunPhy) jqxhrRunPhy.abort();	// exec $.ajax.always();
}

$(document).ready(function() {
  var sub = document.getElementById("phy_submit");
  var stop = document.getElementById("phy_stop");	// The button is currently hidden.
  $('#phy_submit').click(function(){
	var accArr = [];
	if(phyListManager && storage.getItem('_AccmanagerListType') === 'standard') {
		phyListManager.clearAllFilter();
		accArr = phyListManager.getCurrentCheckedId();
	} else {
//		$('#idlst option').each(function(){ idlstCount++; });
		$('#idlst option').each(function(){
			var select = $(this).val();
			var selectarr = select.split("|");
			accArr.push(selectarr[0]);
		 });
	}
//	if(idlstCount < 3) {
	if(accArr.length < 3) {
		alert("Select three or more Accessions.");
		return;
	}

	sub.disabled = true;	// Button無効化.
	stop.disabled = false;
	$.ajax({
                url: "./bin/checkPid.php",
        }).done(function (response) {
        	//Ajax通信が成功した場合に呼び出されるメソッド
        	//デバッグ用 アラートとコンソール
        	if (response['snum'] > 1 || response['sflg'] != "") {
			alert("This program is too busy.");
		} else {
			qrylst = accArr.join(",");
/*
        		var qrylst = "";
			var idlstDoc = document.getElementById("idlst");
        		for (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="";

				var phy_method = document.getElementById("prm_phy_method").value;

				var vtypes = "";
				if(document.getElementById("prm_phy_method_s").checked) vtypes += 's';
				if(document.getElementById("prm_phy_method_i").checked) vtypes += 'i';
				if(document.getElementById("prm_phy_method_d").checked) vtypes += 'd';

	        		param =  {'sid':response['sid'],
                                	"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,
					"prm_phy_method":phy_method,
					"prm_phy_method_vtypes":vtypes
					 };
	                	jqxhrRunPhy = $.ajax({
	                        	type: "POST",
	                        	url:"./bin/exec.php",
	                        	data:param
                		}).done(function (dataArr) {
                        		if(dataArr['status'] == 0) {
						currentPhyloTarget = {
							'cri':document.getElementById("prm_phy_cri").value,
							'chr':document.getElementById("prm_phy_chr").value,
							's':document.getElementById("prm_phy_s").value,
							'e':document.getElementById("prm_phy_e").value,
							'objid':document.getElementById("prm_phy_objid").value,
							'gene':cds,
							'name':storage.getItem('_Name'),
							'namesub':storage.getItem('_NameSub')
						};

                                		ajaxloader.innerHTML = "";
						data = dataArr['result'];
                                		if(/Invalid/.test(data) || /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(
                                                        	"",
                                                  		"Phylogenetic Tree Result",
                                                  		"width=600,height=600,scrollbars=no,resizable=yes"
                                                		);
                                        		var results = _genPhyResult(data,fileName, phy_method);
                                        		var retString = results.retString;
                                        		var phyResult = results.phyResult;

                                        		res.innerHTML = phyResult;
                                        		pop_win.window.document.open();
                                        		pop_win.window.document.write(
                                                		'<!DOCTYPE html>'
                                                		+'<head><title>Exporting Phylogenetic Tree</title>'
                                                		+'<script src="./js/jquery-3.7.1.min.js" type="text/javascript"></script>'
                                                		+'<script src="./js/jquery-ui-1.13.2.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/env.js" type="text/javascript"></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>'

+ '<script type="text/javascript"> \
function adjustSvgSize() { \
    $Hlength = $(window).height() - 68; \
    $Wlength = $(window).width() - 26; \
    $("#phy_tree_res").css("height",$Hlength); \
    $("#phy_tree_res").css("width",$Wlength); \
    $("#phy_svg").css("height",$Hlength); \
    $("#phy_svg").css("width",$Wlength); \
} \
function showtreeWrapper() { \
	showtree("newick","phy_svg"); \
	adjustSvgSize(); \
} \
$(document).ready(function() { $(window).resize(adjustSvgSize); }); \
</script>'
								+'</head>'
								+'<body onload="showtreeWrapper();">'
//                                                		+'<body onload="showtree(\'newick\',\'phy_svg\');">'
                                               			+ $("#phy_result").html()
                                                		+ '<input id="newick" name="newick" value="' + _convPhylipTreeName($("#newick").val()) + '" type="hidden">'
                                                		+ '<input id="fasta" name="filename" value="' + _convPhylipTreeName($("#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();
							pop_win.focus();
                                        		res.innerHTML = retString;
                                		}
                        		}
					/*
                        		error: function(XMLHttpRequest, textStatus, errorThrown) {
                        		ajaxloader.innerHTML = XMLHttpRequest.status+" Error";
                        		}
					*/
                                }).fail(function(XMLHttpRequest, textStatus, errorThrown){
					if(textStatus === 'abort') {
					    ajaxloader.innerHTML = "Processing aborted";
					} else {
                                            alert('Error : ' + errorThrown);
                                            $("#XMLHttpRequest").html("XMLHttpRequest : " + XMLHttpRequest.status);
                                            $("#textStatus").html("textStatus : " + textStatus);
                                            $("#errorThrown").html("errorThrown : " + errorThrown);
i					}
                                }).always(function() {
                                        sub.disabled = false;
                                        stop.disabled = true;
                                        jqxhrRunPhy = null;
                                });
        		}
		}
    }).fail(function(XMLHttpRequest, textStatus, errorThrown){
                //Ajax通信が失敗した場合に呼び出されるメソッド
                alert('Error : ' + errorThrown);
                $("#XMLHttpRequest").html("XMLHttpRequest : " + XMLHttpRequest.status);
                $("#textStatus").html("textStatus : " + textStatus);
                $("#errorThrown").html("errorThrown : " + errorThrown);
      });
      return false;
  });
});

