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

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

function _drawProgress(value,start){
	var str = "";
	if(_isUndefined(start)){
		str = "<progress value='"+value+"' max='100'></progress>"+value+"%";
		$('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++;
				str = "<progress value='"+val+"' max='100'></progress>"+val+"%";
				$('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);
			}
		}
	}
}

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

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

	$("#dialog_cstm_cond").dialog({
		autoOpen: true,
		modal: false,
		width: 550,
		draggable: true,
		resizable: true
	});
	//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 = localStorage.getItem("_CrtCondition").split("|");
				condArray[0] = parseInt( ui.value);
				localStorage.setItem("_CrtCondition", condArray.join("|"));
				_setCondName();
				_setCondSelect();
				_drawCanvas();
			}
		});
		$( "#prm_cond_sel" ).change(function() {
			slider.slider( "value", this.selectedIndex );
			condArray = localStorage.getItem("_CrtCondition").split("|");
			condArray[0] = parseInt(this.selectedIndex);
			localStorage.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 = localStorage.getItem("_CrtCondition").split("|");
	for(var i=0; i<condArray.length; i++){
		var tgt = 'select[name=cond_select_row'+i+']';
		condArray[i] = $(tgt).val();
	}
	localStorage.setItem("_CrtCondition", condArray.join("|"));
	_setCondSelect();
}

function _setCondSelect(){
	var str = "";
	var condArray = localStorage.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(localStorage.getItem("_Env")));
	var condArray = localStorage.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, link){
	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.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;'>"+
	"<p><strong>Position</strong><br>"+
	"<span class='gffWindowStr'>"+_escapeHTML(Objects.Chr)+" "+parseInt(pos)+"-"+parseInt(end)+"</span></p>"+
	"<p><strong>Link</strong><br>"+
	"<span class='gffWindowItems'><a target='_blank' href='"+link+"'>"+_escapeHTML(id)+"</a></span></p>"+
	"<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)+"');\">FASTA</span><br>"+
	"<span class='gffWindowItems' onclick=\"_dialog_csv('"+parseInt(pos)+","+parseInt(end)+"');\">CSV</span></p>"+
	"</div>"+
	"<div style='text-align:center;'><button onclick=\"_zoomFromGffWindow('"+_escapeHTML(id)+"|"+parseInt(pos)+"|"+parseInt(end)+"|"+_escapeHTML(Objects.Chr)+"')\">Zoom</button><div>";
	elementcellDoc.innerHTML = strForGff;
	elementcellDoc.style.border = "solid 2px #b0c4de"; 
}
//////////////////////////////////////////////////////////////////////////////////////
//dialog for phylogenetic analysis

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'
                }
	});
	*/
	
	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);
        	}
	}

        $("#dialog_phy").css('height',$("#mv_dlg").height());
        $("#dialog_phy").css('max-height',$("#mv_dlg").height());
        $(".phylo_content").css('max-height',$("#mv_dlg").height()-43);
        $(".phylo_content").css('height',$("#mv_dlg").height()-43);
        $("#dialog_phy").css('display','inline-block');

        if($(".under_phy").hasClass('fa-window-restore')){
                $(".under_phy").toggleClass('fa-window-restore fa-window-minimize');
        }
        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','900px');
                $("#phylo_title").css('width','888px');
                $("#phylo_title").css('max-width','888px');
                $("#phylo_title").css('min-width','260px');
                $(".phylo_content").css('width','896px');
                $("#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";
        }

        winFront[winFront.length] = 'phylo';
        for (var i = 0; i < winFront.length; i++) {
                $("."+winFront[i]+"_window").css('z-index',1000+i);
        }

	var blk = localStorage.getItem("_Block");
	var s = parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
	var e = s+(blk*_cvtZoom(Objects.Zoom))-1;

	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{
		$("#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(localStorage.getItem("_Chrs")));
	var en = new Object(JSON.parse(localStorage.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(localStorage.getItem("_QUAL"));
	$("#prm_phy_dp").val(localStorage.getItem("_DP"));
	$("#prm_phy_list").val(_getList("db"));
	var l=new Object(JSON.parse(localStorage.getItem('_Lists')));
        var d=new Object(JSON.parse(localStorage.getItem('_ListsDeleted')));
        var ls="";
        var ld="";
        var ss="";
  	var phenohash = new Array();
	if(phenotypeFlg) {
  		phenoexp = localStorage.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];
  		}
	}	

        $('#prm_tw').val(localStorage.getItem('_TitleW'));
        $('#prm_switch_name').val(localStorage.getItem('_Name'));
        $('#prm_switch_sub').val(localStorage.getItem('_NameSub'));
        for (var i=0;i<l.length;i++){
                if ( Objects.Name == "id" ) {
                        ss=l[i].id
                        ss2=l[i].id
                } else {
                        ss=l[i].name
                        if (ss.length > 15) {
                                ss2 = ss.substr(0,14) + "~";
                        } else {
				ss2 = ss;
			}
                }
		var st = "";
		if(!phenotypeFlg) {
			 phenohash[l[i].id] = "";
		}
		if (phenohash[l[i].id] === undefined) {
                	st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss2.replace(/^\s+|\s+$/g, ""), l[i].variety.replace(/^\s+|\s+$/g, ""), l[i].grp.replace(/^\s+|\s+$/g, ""), "").replace(/\s/g,"&nbsp;");
                	ls=ls+"<option value='"+l[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+l[i].variety.replace(/^\s+|\s+$/g, "")+"|"+l[i].grp.replace(/^\s+|\s+$/g, "")+"|"+""+"'>"+st+"</option>";
		} else {
                	st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss2.replace(/^\s+|\s+$/g, ""), l[i].variety.replace(/^\s+|\s+$/g, ""), l[i].grp.replace(/^\s+|\s+$/g, ""), phenohash[l[i].name].replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;");
                	ls=ls+"<option value='"+l[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+l[i].variety.replace(/^\s+|\s+$/g, "")+"|"+l[i].grp.replace(/^\s+|\s+$/g, "")+"|"+phenohash[l[i].name].replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>";
		}	
	}
        for (var i=0;i<d.length;i++){
                if ( Objects.Name == "id" ) {
                        ld=ld+"<option value='"+d[i].id+"'>"+d[i].id+"</option>";
                } else {
                        ld=ld+"<option value='"+d[i].id+"'>"+d[i].name+"</option>";
                }
        }
        $('#idlst').find('option').remove().end().append(ls);
        $('#tree_qry').find('option').remove().end().append(ld);
	localStorage.setItem("_usePhylo",ls);
	//select phenotype
	if (phenotypeFlg) {
           var strname = localStorage.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;
        }
	}
        //button for sorting
        var butSort = "<button class=\"asc\" style=\"width:135px;\" id=\"pSort\"  onClick=\"_sort_accession_phylo(1,'asc')\" >ID/Name</button>\
                <button class=\"asc\" id=\"pSort2\" style=\"width:125px;\" onClick=\"_sort_accession_phylo(2,'asc')\">Variety</button>\
                <button class=\"asc\" id=\"pSort3\" style=\"width:125px;\" onClick=\"_sort_accession_phylo(3,'asc')\">Subvariety</button>\
                <button class=\"asc\" id=\"pSort4\" style=\"width:125px;\" onClick=\"_sort_accession_phylo(4,'asc')\">" + phenoname + "</button>";
        $('#run_sortings').html(butSort);

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

	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();
	_setClickPhenotypePhyloEvent();
}

//////////////////////////////////////////////////////////////////////////////////////
//sequence length for phylogenetic analysis

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 = e.value-s.value+1;
	var sv =s.value;
	var ev =e.value;
	idmsg.innerHTML = "";
	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.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" onClick=\"_runPhylogen();\">";
		passed = 1;
        } else {
                if (!s.checkValidity() || !e.checkValidity()) {
                        len="<font color=\"#FF0000\">Please input postion!</font>";
                        sl.innerHTML = len;
                        sub.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" 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";
/*
                        len="<font color=\"#FF0000\">Maximum size between start and end is 20,000 bp.</font>";
                        sl.innerHTML = len;
                        sub.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" disabled=\"true\">";
*/
		} 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.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" disabled=\"true\">";
		}
	}
        if (passed == 1) {
                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.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" onClick=\"_runPhylogen();\" >";
                        passed = 2;
                } else {
                        if (!dp.checkValidity() || vdp<0) {
                                dpmsg.innerHTML = "<font color=\"#FF0000\">DEPTH value is invalid!</font>";
                                sub.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" disabled=\"true\">";
                        } else if ( !q.checkValidity() || vq<0) {
                                qualmsg.innerHTML = "<font color=\"#FF0000\">Quality value is invalid!</font>";
                                sub.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" 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.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" disabled=\"true\" onClick=\"_runPhylogen();\">";
                        } else if(objidv.indexOf('<script>') != -1){
                                idmsg.innerHTML = "<font color=\"#FF0000\">Input paramater is invalid.</font>";
                                sub.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" disabled=\"true\" onClick=\"_runPhylogen();\">";
                        } else {
                                idmsg.innerHTML = "";
                                sub.innerHTML = "<input id=\"phy_submit\" type=\"submit\" value=\"Run\" onClick=\"_runPhylogen();\" >";
                        }
                }
        }

        if (document.getElementById("prm_phy_cri").value == 0 && document.getElementById("prm_phy_gene").checked === true) {
                document.getElementById("prm_phy_gene").checked = false;
        }

	var elmcri = document.getElementById("prm_phy_cri");
	var elmid = document.getElementById("prm_phy_objid");
	var elmchr = document.getElementById("prm_phy_chr");
	var elms = document.getElementById("prm_phy_s");
	var elme = document.getElementById("prm_phy_e");
	var elmgene = document.getElementById("prm_phy_gene");
	if(elmcri.value == 0){
		elmchr.disabled = false;
		elms.disabled = false;
		elme.disabled = false;
		elmid.disabled = true;
		elmgene.disabled = true;
		elmid.value = "";
	}else{
		elmchr.disabled = true;
		elms.disabled = true;
		elme.disabled = true;
		elmid.disabled = false;
		elmgene.disabled = false;
		var stpos=parseInt(localStorage.getItem("_Pos")-1) * _cvtZoom(localStorage.getItem("_Zoom")) + 1;
		len = 20000;
                s.value=parseInt(stpos);
                e.value=(parseInt(stpos)+19999);
                sl.innerHTML = "Sequence&nbsp;length&nbsp;:&nbsp;&nbsp;"+parseInt(len)+"&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'
    }
  });
  */
        localStorage.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);
        	}
	}
	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('max-height', '382px');
        $(".blast_window").css('height', '382px');
        $(".blast_content").css('max-height', '339px');
        $(".blast_content").css('height', '339px');

	$(".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.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>";
                        sub.innerHTML = "<button type=\"submit\" name=\"blast_submit\" onclick=\"_runBlast();\" disabled = \"true\">Run</button>";
                } else if (!mm.checkValidity()) {
                        mmm.innerHTML = "<font color=\"#FF0000\">Please input max matches!</font>";
                        sub.innerHTML = "<button type=\"submit\" name=\"blast_submit\" onclick=\"_runBlast();\" disabled = \"true\">Run</button>";
                } else if (!ev.checkValidity() || !isFinite(evv) || evv<0) {
                        evm.innerHTML = "<font color=\"#FF0000\">Please input E-value!</font>";
                        sub.innerHTML = "<button type=\"submit\" name=\"blast_submit\" onclick=\"_runBlast();\" disabled = \"true\">Run</button>";
                }
        }
}

//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);
        	}
	}

        $(".p3_content").css('max-height',$("#mv_dlg").height()-36);
        $(".p3_content").css('height',$("#mv_dlg").height()-36);
        $("#dialog_p3").css('height',$("#mv_dlg").height());
        $("#dialog_p3").css('max-height',$("#mv_dlg").height());
	$(".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','798px');
		$("#p3_title").css('max-width','798px');
		$("#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";
	}
        winFront[winFront.length] = 'p3';
        for (var i = 0; i < winFront.length; i++) {
                $("."+winFront[i]+"_window").css('z-index',1000+i);
        }
	
        //define target site
	dlgchk = str.split("---BLS---");
	var s = "";
	var blk=localStorage.getItem("_Block");
	var e = "";
	if (dlgchk[1] == 'open') {
        	s=parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
        	e=s+(blk*_cvtZoom(Objects.Zoom))-1;
        	if((e-s) >= 99){e=s+99;}
        	$("#prm_rp3_tgt").val(s);
        	$("#prm_rp3_tgt_e").val(e);
        	$("#prm_p3_tgt").val(s);
        	$("#prm_p3_tgt_e").val(e);
		_initp3Dlg();
	} else {
		s = dlgchk[1];
		e = dlgchk[2];
                $("#prm_rp3_tgt").val(s);
                $("#prm_rp3_tgt_e").val(e);
                $("#prm_p3_tgt").val(s);
                $("#prm_p3_tgt_e").val(e);
	}
	//for exporting sequence 
	var strarray = str.split("|");
	//var accession = strarray[0];
	//var target=parseInt(strarray[1]);
	//var targetEnd=parseInt(strarray[2]);
	var variant=strarray[3];
	var q=localStorage.getItem("_QUAL");
	var dp=localStorage.getItem("_DP");
	var s = 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);
	$("#prm_p3_flk").val(500);
	$("input[name=prm_p3_s]").val(s);
	$("input[name=prm_p3_e]").val(e);

	// Set chromosome
	var o=new Object(JSON.parse(localStorage.getItem("_Chrs")));
	var en=new Object(JSON.parse(localStorage.getItem("_Env")));
	var name=localStorage.getItem("_Name");
	var nameS=localStorage.getItem("_NameSub");
	var chr = document.getElementById("_Chr");
	var ld="";
	for (var i=0;i<o.length;i++)ld=ld+"<option value='"+o[i].id+"'>"+en.chromosome_name+o[i].id+"</option>";

	//Form & param
	$("#prm_p3_name").val(name);
	$("#prm_p3_nameS").val(nameS);
	$("#prm_p3_ref").val(en.reference_name);
	$('#dialog_p3').tabs();
	$('select[name=prm_p3_chr]').find('option').remove().end().append(ld);
	$("select[name=prm_p3_chr]").val(Objects.Chr);
	//$("input[name=prm_p3_tgt]").val(target);
	//$("input[name=prm_p3_tgt_e]").val(targetEnd);

	//dynamic contents
	var sl = document.getElementById("flk_len");
	var len = 500;
	var flk5=len;
	var flk3=len;
	if((s-len) < 0){flk5=s-(s-len);}
	if((e+len) > parseInt(_last_Chr("1b",chr))){flk3=e-(e+len);}
	sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+parseInt(flk5)+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+parseInt(flk3)+"&nbsp;bp";
	_dialog_p3_len();
	_dialog_rp3_len();
	var res = document.getElementById("p3_query_res");
	res.innerHTML="";
/*
	if($("#p3Setting").is(":hidden") != true){
		$("#p3Setting").hide();
	}
*/
	if($("#p3HistArea").is(":hidden") != true){
		$("#p3HistArea").hide();
	}
/*
	//define target site
	var s=parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
        var blk=localStorage.getItem("_Block");
        var e=s+(blk*_cvtZoom(Objects.Zoom))-1;
        if((e-s) >= 9999){e=s+9999;}
        $("#prm_rp3_tgt").val(s);
        $("#prm_rp3_tgt_e").val(e);
	$("#prm_p3_tgt").val(s);
        $("#prm_p3_tgt_e").val(e);
*/
	_sessionStart();
	_helpEvent();
	_helpEvent2();
}

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 (localStorage.getItem("_blstHistFlg") == 1 || $("#blst_opt").hasClass("open")) {
			$(".blast_window").css('height', $("#mv_dlg").height());
    			$(".blast_window").css('max-height', $("#mv_dlg").height());
    			$(".blast_content").css('height', $(".blast_window").height()-43);
    			$(".blast_content").css('max-height', $(".blast_window").height()-43);
    			$(window).resize(function() {
        			if(!($(".blast_window").hasClass('minimized'))){
                			$(".blast_window").css('height', $("#mv_dlg").height());
                			$(".blast_window").css('max-height', $("#mv_dlg").height());
                			$(".blast_content").css('height', $(".blast_window").height()-43);
                			$(".blast_content").css('max-height', $(".blast_window").height()-43);
				}
			 });
		}
        } 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 (localStorage.getItem("_runBlast") == 0 && $("#blst_opt").hasClass("close")) {
			$(".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');
                	});
		} else if (localStorage.getItem("_runBlast") == 1 || $("#blst_opt").hasClass("open")){
                        $(".blast_window").css('height', $("#mv_dlg").height());
                        $(".blast_window").css('max-height', $("#mv_dlg").height());
                        $(".blast_content").css('height', $(".blast_window").height()-43);
                        $(".blast_content").css('max-height', $(".blast_window").height()-43);
                        $(window).resize(function() {
                                if(!($(".blast_window").hasClass('minimized'))){
                                        $(".blast_window").css('height', $("#mv_dlg").height());
                                        $(".blast_window").css('max-height', $("#mv_dlg").height());
                                        $(".blast_content").css('height', $(".blast_window").height()-43);
                                        $(".blast_content").css('max-height', $(".blast_window").height()-43);
                                }
                         });
		}
        }
}
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');
    $(".blast_window").css('height', $("#mv_dlg").height());
    $(".blast_window").css('max-height', $("#mv_dlg").height());
    $(".blast_content").css('height', $(".blast_window").height()-43);
    $(".blast_content").css('max-height', $(".blast_window").height()-43);
    $(window).resize(function() {
        if(!($(".blast_window").hasClass('minimized'))){
                $(".blast_window").css('height', $("#mv_dlg").height());
                $(".blast_window").css('max-height', $("#mv_dlg").height());
                $(".blast_content").css('height', $(".blast_window").height()-43);
                $(".blast_content").css('max-height', $(".blast_window").height()-43);
        }
    });
  } else {
    $("#blastSetting").slideUp();
    $('#blst_opt.open').toggleClass('open close');
    $('#blst_opt.close').toggleClass('ui-icon-triangle-1-s ui-icon-triangle-1-e');
    if (localStorage.getItem("_runBlast") != 1) {
   	$(".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")) {
    $("#epcrTable"+count).slideDown("fast");
  } else {
    $("#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 _switchCosts(scores) {
	var score = scores.options[scores.selectedIndex].value;
        var select = document.getElementById('gap_costs');
        select.textContent = null;
        var selectBox = _selectPairs(score);
        for (var i in selectBox) {
                var option = document.createElement('option');
                option.setAttribute('value',i);
                option.innerHTML = _escapeHTML(selectBox[i]);
                select.appendChild(option);
        }
}

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.innerHTML =  "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" >Export</button>";
                        passed=1;
                }else if (!flk.checkValidity() || flkv<0) {
                        string="<font color=\"#FF0000\">Invalid value.</font>";
                        sl.innerHTML = string;
                        sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" disabled  >Export</button>";
                        passed = 0;
                }else{
                        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.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" disabled  >Export</button>";
                        passed=0;
                }
        }else{
                string="<font color=\"#FF0000\">Invalid value. Please input target position!</font>";
                sl.innerHTML = string;
                sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" disabled  >Export</button>";
                passed=0;
        }

        var flk5=flkv;
        var flk3=flkv;
        if(passed == 1){
                if(avd.checkValidity() && dp.checkValidity() && q.checkValidity() && vdp>=0 && vq>=0 && avdv>=0 && flkv >= avdv){
                        sub.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" >Export</button>";
                } else{
                        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;
			}
		}
        }
        $("#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.innerHTML =  "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" >Run</button>";
			passed=1;
                }else if (!flk.checkValidity() || flkv<0) {
                        string="<font color=\"#FF0000\">Please input flanking region length!</font>";
                        sl.innerHTML = string;
                        sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
                        passed=0;
		}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.innerHTML = "<button type=\"submit\" name=\"prm_p3_submit\" onClick=\"_genPrimer3Query();\" disabled  >Run</button>";
                        passed=0;
		}
	}else{
		string="<font color=\"#FF0000\">Invalid value. Please input target position!</font>";
		tgterr.innerHTML = string;
		sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
		passed=0;
	}
/*
	var flk5=flkv;
	var flk3=flkv;
	if(passed == 1){
		if(flk.checkValidity() && flkv!=0){
			sub.innerHTML =  "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" >Run</button>";
			if (flkv > 2000){
				$("#prm_p3_flk").val(2000);
				flkv = parseInt(flk.value);
				flk5=flkv;
				flk3=flkv;
				if((tgtv-flkv) < 0){flk5=tgtv-1;}
				if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
				sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
				passed=2;
			} else if (flkv <= 0){
				string="<font color=\"#FF0000\">Primer is selected from this region.</font>";
				sl.innerHTML = string;
				sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
				passed=0;
			} else{
				if((tgtv-flkv) < 0){flk5=tgtv-1;}
				if((tgtev+flkv) > parseInt(_last_Chr("1b",chr.value))){flk3=parseInt(_last_Chr("1b",chr.value))-tgtev;}
				sl.innerHTML = "5\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk5+"&nbsp;bp<br>3\'&nbsp;flanking&nbsp;&nbsp;region:&nbsp;&nbsp;"+flk3+"&nbsp;bp";
				passed=2;
			}
		}else{
			string="<font color=\"#FF0000\">Please input flanking region length!</font>";
			sl.innerHTML = string;
			sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
			passed=0;
		}
	}
*/
        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.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.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
                        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.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.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
                        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.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" >Run</button>";
                } 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.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Run</button>";
                        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: 470,
		draggable: true,
		resizable: true
	});	
	var cr = document.getElementById("chref_ac");
	var o=new Object(JSON.parse(localStorage.getItem('_Lists')));
	var label = localStorage.getItem("_Name");
	if(Objects.Onebase=="off"){
		if ( localStorage.getItem("_Ref") != o[i].db ) {
			if(label == "id"){
				cr.innerHTML = "Change&nbsp;the&nbsp;reference&nbsp;sequence&nbsp;to&nbsp;<font color=\"red\">"+_escapeHTML(o[i].id)+"<\/font>.";
			} else{
				cr.innerHTML = "Change&nbsp;the&nbsp;reference&nbsp;sequence&nbsp;to&nbsp;<font color=\"red\">"+_escapeHTML(o[i].name)+"<\/font>.";
			}
		} else {
			cr.innerHTML = "Reset&nbsp;reference&nbsp;sequence.";
		}
	}else{
		cr.innerHTML = "This&nbsp;function&nbsp;is&nbsp;disabled&nbsp;when&nbsp;the&nbsp;frequency&nbsp;mode&nbsp;is&nbsp;turned&nbsp;off.";
	}
}


//Close dialog:changing reference

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


//Downloading FASTA

function _dialog_fa(str){
	$("#dialog_fa").dialog({
		autoOpen: true,
		modal: true,
		width: 650,
		draggable: true,
		resizable: true
	});
	var s=parseInt(Objects.Pos-1)*_cvtZoom(Objects.Zoom)+1;
	var blk=localStorage.getItem("_Block");
	var e=s+(blk*_cvtZoom(Objects.Zoom))-1;
	if(str){
		var params = str.split(",");
		s = parseInt(params[0]);
		e = parseInt(params[1]);
	}
	if((e-s) >= 19999){e=s+19999;} 
	$("#prm_fa_s").val(s);
	$("#prm_fa_e").val(e);

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

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


//Close dialog:fasta

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

///////////////////////////////////////////////////////////////////////////////////
//for exporting param 
///////////////////////////////////////////////////////////////////////////////////
function _param_display(){
	var dp = document.getElementById("prm_fa_dp");
	var q = document.getElementById("prm_fa_qual");
	var w = document.getElementById("prm_fa_width");
	var vw = w.value;
	var vdp = dp.value;
	var vq = q.value;
	var 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");

	if(dp.checkValidity() && q.checkValidity() && w.checkValidity() && vdp!=0 && vq!=0){
		sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" onClick=\"_genFasta();\" >";
	}
	if (!(q.checkValidity()) || vq == "") {
		string = "<font color=\"#FF0000\">Invalid value in Quality.</font>";
		errqt.innerHTML = string;
		sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" disabled=\"true\">";
	} 
	if (!(dp.checkValidity()) || vdp == "") {
                string = "<font color=\"#FF0000\">Invalid value in DEPTH.</font>";
                errdp.innerHTML = string;
                sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" disabled=\"true\">";
        }
        if (!(w.checkValidity()) || vw == "") {
                string = "<font color=\"#FF0000\">Invalid value in Line break.</font>";
                errlb.innerHTML = string;
                sub.innerHTML = "<input id=\"fa_submit\" type=\"submit\" value=\"Export\" disabled=\"true\">";
        }
}

//////////////////////////////////////////////////////////////////////////////////////
//sequence length

function _dialog_fa_len(){
	var s = document.getElementById("prm_fa_s");
	var e = document.getElementById("prm_fa_e");
	var len = e.value-s.value+1;
	var sub = document.getElementById("fa_submit");
	var sl = document.getElementById("seq_len");
	var sv =s.value;
	var ev =e.value;

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


//Downloading CSV
//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 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;

	if ($('input[name=prm_pos_id]:eq(0)').prop('checked')) { //Position checked
        	if(tgt.checkValidity() && tgte.checkValidity() && tgtv>0 && tgtev>0 && tgtev >= tgtv){
                	if((tgtev-tgtv) <= 199999){
                        	sub.innerHTML =  "<button type=\"submit\" name=\"csv_submit\" onClick=\"_genCSV();\" >Export</button>";
                        	passed=1;
                	}else{
                        	string="<font color=\"#FF0000\">Target is too long!<br>Maximum size is 200,000 bp.</font>";
                        	sl.innerHTML = string;
                        	sub.innerHTML = "<button type=\"submit\" name=\"csv_submit\" onClick=\"_genCSV();\" disabled>Export</button>";
                        	passed=0;
                	}
        	}else{
                	string="<font color=\"#FF0000\">Invalid value. Please input target position!</font>";
                	sl.innerHTML = string;
                	sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Export</button>";
                	passed=0;
        	}
	} else if ($('input[name=prm_pos_id]:eq(1)').prop('checked')) { //ID checked
		if (id.checkValidity() && !(idv.match(/<script>/))&& idv!="") {
			sub.innerHTML =  "<button type=\"submit\" name=\"csv_submit\" onClick=\"_genCSV();\" >Export</button>";
                        passed=1;
		} else if (!id.checkValidity() || idv == "") {
			string="<font color=\"#FF0000\">Please input accession id!</font>";
                        sl2.innerHTML = string;
                        sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Export</button>";
                        passed=0;
		} else if (idv.match(/<script>/)) {
			string="<font color=\"#FF0000\">Invalid value. Please input the correct accession id!</font>";
                        sl2.innerHTML = string;
                        sub.innerHTML = "<button type=\"submit\" name=\"prm_rp3_submit\" onClick=\"_runPrimer3();\" disabled>Export</button>";
                        passed=0;
		}
	}
        if (passed==1) {
                if(q.checkValidity() && vq>0){
                        sub.innerHTML =  "<button type=\"submit\" name=\"csv_submit\" onClick=\"_genCSV();\" >Export</button>";
                        passed=2;
                } else {
                        string="<font color=\"#FF0000\">Invalid value. Please input target quality!</font>";
                        qmsg.innerHTML = string;
                        sub.innerHTML = "<button type=\"submit\" name=\"csv_submit\" onClick=\"_genCSV();\" disabled>Export</button>";
                        passed=0;
                }
        }
        if (passed==2) {
                if(dp.checkValidity() && vdp>0){
                        sub.innerHTML =  "<button type=\"submit\" name=\"csv_submit\" onClick=\"_genCSV();\" >Export</button>";
                } else {
                        string="<font color=\"#FF0000\">Invalid value. Please input target depth!</font>";
                        dpmsg.innerHTML = string;
                        sub.innerHTML = "<button type=\"submit\" name=\"csv_submit\" onClick=\"_genCSV();\" disabled=\"\">Export</button>";
                }
        }
}

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.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;
	if(str){
		var params = str.split(",");
		s = parseInt(params[0]);
		e = parseInt(params[1]);
	}
	$("#prm_csv_s").val(s);
	$("#prm_csv_e").val(e);

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


//Close dialog:csv

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


//Managing of accession lists

function _dialog_list(){
	$("#dialog_list").dialog({
		autoOpen: true,
		modal: false,
		width: 800,
		maxHeight: window.innerHeight-15,
		draggable: true,
		resizable: true,
                position: {
                        of:'body',
                        at:'top',
                        my:'center'
                }
	});
	_dlg_make_list();
	_dlg_title_color();
	$('#prm_list_upfile').replaceWith('<input type="file" id="prm_list_upfile" size="30" accept="text/plain" onChange="_validateAccList(this.files)">');
	_setClickCloseEvent();
}

function _dlg_title_color(){
	var col = new Object(JSON.parse(localStorage.getItem("_GrpCol")));
	var dest_subtitle = localStorage.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(localStorage.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(localStorage.getItem("_GrpCol")));
			col[$("select[name=prm_grpcol_grp]").val()] = "#"+hex;
			localStorage.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(localStorage.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();
	$("#prm_grpcol_ind").css('color','rgb(250, 143, 143)');
	$("#prm_grpcol_col").val('#fa8f8f');
	_drawCanvas();
}

function _dlg_make_list(){
	var l=new Object(JSON.parse(localStorage.getItem('_Lists')));
	var d=new Object(JSON.parse(localStorage.getItem('_ListsDeleted')));
	var ls="";
	var ld="";
	var ss="";

	$('#prm_tw').val(localStorage.getItem('_TitleW'));
	$('#prm_switch_name').val(localStorage.getItem('_Name'));
	$('#prm_switch_sub').val(localStorage.getItem('_NameSub'));
 	var phenohash = new Array();
	if(phenotypeFlg) {
		phenoexp = localStorage.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];
  		}
	}
	var convertId = [];
	for (var i=0;i<l.length;i++){
		id = l[i].id;
		name = l[i].name;
		convertId[name] = id;
	}
	for (var i=0;i<l.length;i++){
		if ( Objects.Name == "id" ) {
			ss=l[i].id
		} else {
			ss=l[i].name
			if (ss.length > 15) {
				ss = ss.substr(0,14) + "~";
			}
                }
		if(!phenotypeFlg) {
			phenohash[l[i].id] = "";
		}
		
		if (phenohash[l[i].id] === undefined) {
			var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), l[i].variety.replace(/^\s+|\s+$/g, ""), l[i].grp.replace(/^\s+|\s+$/g, ""), "").replace(/\s/g,"&nbsp;");
			ls=ls+"<option value='"+l[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+l[i].variety.replace(/^\s+|\s+$/g, "")+"|"+l[i].grp.replace(/^\s+|\s+$/g, "")+"|"+""+"'>"+st+"</option>";
		} else {
			//var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), l[i].variety.replace(/^\s+|\s+$/g, ""), l[i].grp.replace(/^\s+|\s+$/g, ""), l[i].origin.replace(/^\s+|\s+$/g, ""), l[i].type.replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;");
			//var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), l[i].variety.replace(/^\s+|\s+$/g, ""), l[i].grp.replace(/^\s+|\s+$/g, ""), l[i].pheno.replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;");
			var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), l[i].variety.replace(/^\s+|\s+$/g, ""), l[i].grp.replace(/^\s+|\s+$/g, ""), phenohash[l[i].name].replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;");
			//ls=ls+"<option value='"+l[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+l[i].variety.replace(/^\s+|\s+$/g, "")+"|"+l[i].grp.replace(/^\s+|\s+$/g, "")+"|"+l[i].origin.replace(/^\s+|\s+$/g, "")+"|"+l[i].type.replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>";
			//ls=ls+"<option value='"+l[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+l[i].variety.replace(/^\s+|\s+$/g, "")+"|"+l[i].grp.replace(/^\s+|\s+$/g, "")+"|"+l[i].pheno.replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>";
			ls=ls+"<option value='"+l[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+l[i].variety.replace(/^\s+|\s+$/g, "")+"|"+l[i].grp.replace(/^\s+|\s+$/g, "")+"|"+phenohash[l[i].name].replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>";
		}
	}
	for (var i=0;i<d.length;i++){
		if ( Objects.Name == "id" ) {
			ld=ld+"<option value='"+d[i].id+"|"+d[i].name.replace(/^\s+|\s+$/g, "")+"|"+d[i].variety.replace(/^\s+|\s+$/g, "")+"|"+d[i].grp.replace(/^\s+|\s+$/g, "")+"|"+d[i].origin.replace(/^\s+|\s+$/g, "")+"|"+d[i].type.replace(/^\s+|\s+$/g, "")+"'>"+d[i].id+"</option>";
		} else {
			ld=ld+"<option class=\"hideqry\" value='"+d[i].id+"|"+d[i].name.replace(/^\s+|\s+$/g, "")+"|"+d[i].variety.replace(/^\s+|\s+$/g, "")+"|"+d[i].grp.replace(/^\s+|\s+$/g, "")+"|"+d[i].origin.replace(/^\s+|\s+$/g, "")+"|"+d[i].type.replace(/^\s+|\s+$/g, "")+"'>"+d[i].name+"</option>";
			//ld=ld+"<option class=\"hideqry\" value='"+ss.replace(/^\s+|\s+$/g, "")+"|"+d[i].id+"|"+d[i].variety.replace(/^\s+|\s+$/g, "")+"|"+d[i].grp.replace(/^\s+|\s+$/g, "")+"|"+d[i].origin.replace(/^\s+|\s+$/g, "")+"|"+d[i].type.replace(/^\s+|\s+$/g, "")+"'>"+d[i].name+"</option>";
		}
	}
	$('#lstBox1').find('option').remove().end().append(ls);
	$('#lstBox2').find('option').remove().end().append(ld);

        if (phenotypeFlg) {
           var strname = localStorage.getItem("_Phenotype");
           var phenoname = "";
           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;
            }
        }
	//button for sorting
	var butSort = "<button class=\"asc\" style=\"width:115px;\" id=\"bSort\"  onClick=\"_sort_accession_list(1,'asc')\" >ID/Name</button>\
		<button class=\"asc\" id=\"bSort2\" style=\"width:115px;\" onClick=\"_sort_accession_list(2,'asc')\">Variety</button>\
		<button class=\"asc\" id=\"bSort3\" style=\"width:115px;\" onClick=\"_sort_accession_list(3,'asc')\">Subvariety</button>\
		<button class=\"asc\" id=\"bSort4\" style=\"width:134px;\" onClick=\"_sort_accession_list(4,'asc')\">"+phenoname+"</button>";
	$('#run_sorting').html(butSort);
	$('button.asc').button({
		icons: {
			secondary: 'ui-icon-triangle-1-n'
		}
	});
	$('button.desc').button({
		icons: {
			secondary: 'ui-icon-triangle-1-s'
		}
	});
	_setClickPhenotypePhyloEvent();
}


//Set accession sorting event

$(document).ready(function() {
	$('#prm_list_init').click(function(e) {
		localStorage.setItem("_Lists",localStorage.getItem("_Lists-origin"));
		localStorage.setItem("_ListsDeleted","[]");
		_showLoading();
		localStorage.removeItem("_ListsTgt");
		FROMSCROLL=false;
		_execCanvas();
		_dlg_make_list();
	});

/*
	if (localStorage.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() {
                if(!($(".phylo_window").hasClass('minimized'))){
                        $(".phylo_window").css('height', $("#mv_dlg").height());
                        $(".phylo_window").css('max-height', $("#mv_dlg").height());
                        $(".phylo_content").css('height', $(".phylo_window").height()-30);
                        $(".phylo_content").css('max-height', $(".phylo_window").height()-30);
		} else {                                        
                        $(".phylo_window").css('top', $("#bottom").offset().top +'px');
                }
        });
        $(window).resize(function() {
                if(!($(".p3_window").hasClass('minimized'))){
                        $('.p3_window').css('height',$("#mv_dlg").height());
                        $('.p3_window').css('max-height',$("#mv_dlg").height());
                        $('.p3_content').css('height',$(".p3_window").height()-30);
                        $('.p3_content').css('max-height',$(".p3_window").height()-30);
                } else {
			$(".p3_window").css('top', $("#bottom").offset().top +'px');
		}
		
        });

        $(window).resize(function() {
                if(!($(".gwas_window").hasClass('minimized'))){
                        $('.gwas_window').css('height',$("#mv_dlg").height());
                        $('.gwas_window').css('max-height',$("#mv_dlg").height());
                        $('.gws_content').css('height',$(".gwas_window").height()-30);
                        $('.gwas_content').css('max-height',$(".gwas_window").height()-30);
                } else {
                        $(".gwas_window").css('top', $("#bottom").offset().top +'px');
                }

        });

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

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

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

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

	$('#btnLeft').click(function(e) {
		var va=new Array();
		var o=new Object(JSON.parse(localStorage.getItem('_Lists-origin')));
                var phenohash = new Array();
                if(phenotypeFlg) {
			phenoexp = localStorage.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];
                	}
		}
		var ls="";
		var ss="";
		var selectedOpts = $('#lstBox2 option:selected');

		if (selectedOpts.length == 0) {
			alert("Nothing to move.");
			e.preventDefault();
		}

		$('#lstBox1').append($(selectedOpts).clone());
		$(selectedOpts).remove();
		e.preventDefault();
		$("#lstBox1 option").each(function () {
			var valAry = $(this).val().split("|");
			va.push(valAry[0]);
		}, null);
		for (var j=0;j<va.length;j++){
			for (var i=0;i<o.length;i++){
				if ( va[j] == o[i].id ) {
					if ( Objects.Name == "id" ) {
						ss=o[i].id
					} else {
						ss=o[i].name
                        			if (ss.length > 15) {
                                			ss = ss.substr(0,14) + "~";
                        			}
					}
					if(!phenotypeFlg) {
						phenohash[ss] = "";
					}
					//var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), o[i].variety.replace(/^\s+|\s+$/g, ""), o[i].grp.replace(/^\s+|\s+$/g, ""), o[i].origin.replace(/^\s+|\s+$/g, ""), o[i].pheno.replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;")
					var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), o[i].variety.replace(/^\s+|\s+$/g, ""), o[i].grp.replace(/^\s+|\s+$/g, ""), phenohash[o[i].name].replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;")
					//ls=ls+"<option value='"+o[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+o[i].variety.replace(/^\s+|\s+$/g, "")+"|"+o[i].grp.replace(/^\s+|\s+$/g, "")+"|"+o[i].origin.replace(/^\s+|\s+$/g, "")+"|"+o[i].pheno.replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>"
					ls=ls+"<option value='"+o[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+o[i].variety.replace(/^\s+|\s+$/g, "")+"|"+o[i].grp.replace(/^\s+|\s+$/g, "")+"|"+phenohash[o[i].name].replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>"
				}
			}
		}
		$('#lstBox1').find('option').remove().end().append(ls);
	});

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

        $('#rmQry').click(function(e) {
                var va=new Array();
                var o=new Object(JSON.parse(localStorage.getItem('_Lists-origin')));
                var ls="";
                var ss="";
                var selectedOpts = $('#tree_qry option:selected');

                if (selectedOpts.length == 0) {
                        alert("Nothing to move.");
                        e.preventDefault();
                }
                $('#idlst').append($(selectedOpts).clone());
                $(selectedOpts).remove();
                e.preventDefault();
                $("#idlst option").each(function () {
                        var valAry = $(this).val().split("|");
                        va.push(valAry[0]);
                }, null);
		var phenohash = new Array();
		if (phenotypeFlg) {
                	phenoexp = localStorage.getItem("_Phenoexp");
                	phenoexps = phenoexp.split("|");
                	//var phenohash = new Array();
                	for(i=0; i<phenoexps.length;i++) {
                	        phenotmp = phenoexps[i].split(",");
                	        phenohash[phenotmp[0]] = phenotmp[1];
                	}
		}
                for (var j=0;j<va.length;j++){
                        for (var i=0;i<o.length;i++){
                                if ( va[j] == o[i].id  || va[j] == o[i].name) {
                                        if ( Objects.Name == "id" ) {
                                                ss=o[i].id
                                        } else {
                                                ss=o[i].name
                        			if (ss.length > 15) {
                                			ss2 = ss.substr(0,14) + "~";
                        			} else {
							ss2 = ss
						}
						ss = ss2;
                                        }
                                         //var st = $.format("%s %s %s %s", ss, o[i].variety, o[i].grp, o[i].pheno).replace(/\s/g,"&nbsp;");
					 var st = "";
                                         if(!phenotypeFlg) {
                                                 phenohash[o[i].id] = "";
                                         }
                                         st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", ss.replace(/^\s+|\s+$/g, ""), o[i].variety.replace(/^\s+|\s+$/g, ""), o[i].grp.replace(/^\s+|\s+$/g, ""), phenohash[o[i].name].replace(/^\s+|\s+$/g, "")).replace(/\s/g,"&nbsp;");
                                         ls=ls+"<option value='"+o[i].id+"|"+ss.replace(/^\s+|\s+$/g, "")+"|"+o[i].variety.replace(/^\s+|\s+$/g, "")+"|"+o[i].grp.replace(/^\s+|\s+$/g, "")+"|"+phenohash[o[i].name].replace(/^\s+|\s+$/g, "")+"'>"+st+"</option>";
                                }
                        }
                }
		var hidelst = $('#tree_qry').html();
		localStorage.setItem("_hidePhylo",hidelst);
                $('#idlst').find('option').remove().end().append(ls);
        });

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

function _sort_accession_phylo(type,order){
        var ls ="";
        var keyAry = new Array();
        var valAry = new Array();
        var prtAry = new Array();
        //select phenotype
	
        if (phenotypeFlg) {
           var strname = localStorage.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 labels = ["ID/Name","Variety", "Sub Variety", "Type"];
        var labels = ["ID/Name","Variety", "Subvariety", phenoname];
        var orderForNext;
        var maxtype=4;
        var butSort ="";

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

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

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

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

        if(order=="asc"){
                if(type==4) {
                        uniqueArray.sort(function(a, b) {
                                return (parseFloat(a) > parseFloat(b)) ? 1 : -1;
                        });
                        orderForNext="desc";
                } else {
                        uniqueArray.sort();
                        orderForNext="desc";
                }
        }else{
                if(type==4) {
                        uniqueArray.sort(function(a, b) {
				console.log("desc");
                                return (parseFloat(a) < parseFloat(b)) ? 1 : -1;
                        });
                        orderForNext="asc";
                } else {
                        uniqueArray.reverse();
                        orderForNext="asc";
                }
        }
        for(var x=0; x<uniqueArray.length; x++){
                var str = uniqueArray[x];
                for(var i=0; i<elm.options.length; i++){
                        var tmpAry = valAry[i].split("|");
                        if(tmpAry[type] == str){
                                prtAry.push(valAry[i]);
                        }
                }
        }
        for(var i=0; i<prtAry.length; i++){
                var str = prtAry[i].split("|");
                var st = $.format("%1$-16s %2$-16s %3$-16s %4$-16s", str[1], str[2], str[3], str[4]).replace(/\s/g,"&nbsp;");
                ls=ls+"<option value='"+str[0]+"|"+str[1]+"|"+str[2]+"|"+str[3]+"|"+str[4]+"'>"+st+"</option>";
        }
        $('#idlst').find('option').remove().end().append(ls);

        for(var i=0; i<maxtype; i++){
                if(type==(i+1)) {
			if(type==1){
                        	butSort=butSort+"<button class=\""+orderForNext+"\" id=\"pSort"+parseInt(i+1)+"\" style=\"width:135px; color: blue;\" onClick=\"_sort_accession_phylo("+parseInt(i+1)+",'"+orderForNext+"')\" >"+labels[i]+"</button> ";
			} else {
                        	butSort=butSort+"<button class=\""+orderForNext+"\" id=\"pSort"+parseInt(i+1)+"\" style=\"width:125px; color: blue;\" onClick=\"_sort_accession_phylo("+parseInt(i+1)+",'"+orderForNext+"')\" >"+labels[i]+"</button> ";
			}
                }else{
			if(i==0){
                       	 	butSort=butSort+"<button class=\"asc\" id=\"pSort"+parseInt(i+1)+"\" style=\"width:135px;\" onClick=\"_sort_accession_phylo("+parseInt(i+1)+",'asc')\" >"+labels[i]+"</button> ";
			} else {
                       	 	butSort=butSort+"<button class=\"asc\" id=\"pSort"+parseInt(i+1)+"\" style=\"width:125px;\" onClick=\"_sort_accession_phylo("+parseInt(i+1)+",'asc')\" >"+labels[i]+"</button> ";
			}
                }
        }
        $('#run_sortings').html(butSort);
        $('button.asc').button({
                icons: {
                        secondary: 'ui-icon-triangle-1-n'
                }
        });
        $('button.desc').button({
                icons: {
                        secondary: 'ui-icon-triangle-1-s'
                }
        });

}


function _sort_accession_list(type,order){
	var ls ="";
	var keyAry = new Array();
	var valAry = new Array();
	var prtAry = new Array();
        //select phenotype
	var phenoname = "";
        if (phenotypeFlg) {
           var strname = localStorage.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;
           }
        }
	//var labels = ["ID/Name","Variety", "Sub Variety", "Type"];
	var labels = ["ID/Name","Variety", "Subvariety", phenoname];
	var orderForNext;
	var maxtype=4;
	var butSort ="";

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

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

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

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

	if(order=="asc"){
		if(type==4) {
			uniqueArray.sort(function(a, b) {
  				return (parseFloat(a) > parseFloat(b))  ? 1 : -1;
			});
			orderForNext="desc";
		} else {
			uniqueArray.sort();
			orderForNext="desc";
		}
	}else{
		if(type==4) {
                        uniqueArray.sort(function(a, b) {
                                return (parseFloat(a) < parseFloat(b)) ? 1 : -1;
                        });
			orderForNext="asc";
                } else {
			uniqueArray.reverse();
			orderForNext="asc";
		}
	}

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

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

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

}

//Sort function for pheno



//Reset accession list

function _reset_accession_lists() {
	var o=new Object(JSON.parse(localStorage.getItem('_Lists-origin')));
	var value1=new Array();
	$("#lstBox1 option").each(function () {
		var valAry = $(this).val().split("|");
		value1.push(valAry[0]);
	}, null);

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


//Search keyword & jump position

function _dialog_go(){
	/*
	$("#dialog_go").dialog({
		autoOpen: true,
		modal: false,
		width: 800,
		ONdraggable: true,
		resizable: true
	});
	*/
	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);
                }
        }

	winFront[winFront.length] = 'search';
        for (var i = 0; i < winFront.length; i++) {
                $("."+winFront[i]+"_window").css('z-index',1000+i);
        }

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

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

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

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

function _jumpPOS(e){
	var spzoom;
	var pzoom;
	c=$('#prm_position_chr').val();
	z=$('#prm_position_zoom').val();
	i=$('#prm_position').val();

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

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

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


//Track manager

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

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

function _changeViewTrack(Obj) {
	var n=Obj.name.split("_");
	var v=Obj.options[Obj.selectedIndex].value;
	var t=new Object(JSON.parse(localStorage.getItem('_Tracks')));
	var cmp = "1";
	if ( v == "off" ) {cmp = "0";}
	var str="[";

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

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

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

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

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


//Help

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


//About

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

//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
	});
}


//Reset to browser

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

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

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


//Variants filter

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

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

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

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


//Options view: block

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

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

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

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

/////////////////////////////////////////////// Change title width
function _changeTitleW(){
	var prewidth=localStorage.getItem("_TitleW");
	var width=$('#prm_tw').val();
	localStorage.setItem("_TitleW", width);
	contentW = $("#content").width() + (width - prewidth);
	$("#track").css('width',contentW);
        $("#content").css('width',contentW);
        $("#content2").css('width',contentW);
        titlew = parseInt(localStorage.getItem("_TitleW"))+parseInt(3);
        titlew2 = parseInt(localStorage.getItem("_TitleW"))+parseInt(1);
        $(".title").css('width',parseInt(titlew));
        $(".title2").css('width',parseInt(titlew2));
	$("#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();
}

/////////////////////////////////////////////// Change title with ID or Name
function _changeTitleID(){
	//var name=$('#prm_switch_name').val();
	localStorage.setItem("_Name",$('#prm_switch_name').val());
	var name = localStorage.getItem("_Name");
	if(name == "id") {
		var prewidth=localStorage.getItem("_TitleW");
		var width=180;
        	localStorage.setItem("_TitleW", width);
        	contentW = $("#content").width() + (width - prewidth);
        	$("#track").css('width',contentW);
        	$("#content").css('width',contentW);
        	$("#content2").css('width',contentW);
        	titlew = parseInt(localStorage.getItem("_TitleW"))+parseInt(3);
        	titlew2 = parseInt(localStorage.getItem("_TitleW"))+parseInt(1);
        	$(".title").css('width',parseInt(titlew));
        	$(".title2").css('width',parseInt(titlew2));
        	//_messageOnScreen("Changing width of title: "+width+" pixel");
        	_drawCanvas();

	} else if (name == "name") {
		var prewidth=localStorage.getItem("_TitleW");
		var width=220;
        	localStorage.setItem("_TitleW", width);
        	contentW = $("#content").width() + (width - prewidth);
        	$("#track").css('width',contentW);
        	$("#content").css('width',contentW);
        	$("#content2").css('width',contentW);
        	titlew = parseInt(localStorage.getItem("_TitleW"))+parseInt(3);
        	titlew2 = parseInt(localStorage.getItem("_TitleW"))+parseInt(1);
        	$(".title").css('width',parseInt(titlew));
        	$(".title2").css('width',parseInt(titlew2));
        	_messageOnScreen("Changing width of title: "+width+" pixel");
        	_drawCanvas();
	}

	_drawCanvas();
	_dlg_make_list();
}

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


//Dialog: Cell information

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


//Dialog: Blocks

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


/////////////////////////////////////////////// Change column(load block)
function _changeBlock(){
	bn = parseInt(localStorage.getItem("_Block"));
	blkw = parseInt(localStorage.getItem("_BlockW"));
	var col=parseInt($('#prm_bn').val());
	localStorage.setItem('_Block', String(col));
        contentW = $("#content").width() + (col - bn) * blkw;
        $("#track").css('width',contentW);
        $("#content").css('width',contentW);
        $("#content2").css('width',contentW);
	if(Objects.Pos+col>_last(Objects.Zoom)) localStorage.setItem('_Pos',String(_last(Objects.Zoom)-col+1));
	titlew = parseInt(localStorage.getItem("_TitleW"))+parseInt(3);
	titlew2 = parseInt(localStorage.getItem("_TitleW"))+parseInt(1);
	$(".title").css('width',parseInt(titlew));
	$(".title2").css('width',parseInt(titlew2));
	plotw = parseInt(blkw) * parseInt(col) + parseInt(32);
	$("#plotcvs").css('width',plotw);
	$("#ind").css({'left':'','top':''});
	_showLoading();
	_messageOnScreen("Changing "+Objects.Block+" to "+col+" blocks");
	FROMSCROLL=false;
	_execCanvas();
}

/////////////////////////////////////////////// Change block width
function _changeBlockW(){
        bn = parseInt(localStorage.getItem("_Block"));
        blkw = parseInt(localStorage.getItem("_BlockW"));
	var width=parseInt($('#prm_bw').val());
	localStorage.setItem("_BlockW", width);
        contentW = $("#content").width() + (width - blkw) * bn;
        $("#track").css('width',contentW);
        $("#content").css('width',contentW);
        $("#content2").css('width',contentW);
        titlew = parseInt(localStorage.getItem("_TitleW"))+parseInt(3);
        titlew2 = parseInt(localStorage.getItem("_TitleW"))+parseInt(1);
        $(".title").css('width',parseInt(titlew));
        $(".title2").css('width',parseInt(titlew2));
        plotw = parseInt(bn) * parseInt(width) + parseInt(32);
        $("#plotcvs").css('width',plotw);
	$("#ind").css({'left':'','top':''});
	_messageOnScreen("Changing width of block: "+width+" pixel");
	setTimeout("_drawCanvas()", 500);
}

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


//Effect level list

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

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

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

	$("#dialog_color_manager").dialog({
		autoOpen: true,
		modal: false,
		width: 650,
		maxHeight: window.innerHeight-15,
		draggable: true,
		resizable: true,
    		position: {
        		of:'body',
        		at:'top',
       	 		my:'center'
    		}
	});

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

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

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

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

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

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

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

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);
                }
        }

        $(".gwas_content").css('height',$("#mv_dlg").height()-43);
        $(".gwas_content").css('max-height',$("#mv_dlg").height()-43);
        $("#dialog_phenotypes").css('height',$("#mv_dlg").height());
        $("#dialog_phenotypes").css('max-height',$("#mv_dlg").height());
        $("#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";
        }

        winFront[winFront.length] = 'gwas';
        for (var i = 0; i < winFront.length; i++) {
                $("."+winFront[i]+"_window").css('z-index',parseInt(1000+i));
        }

	$('#select_phenotype_div').empty();
	$('#choose_pheno').empty();
	var o=new Object(JSON.parse(localStorage.getItem("_Phenotypes")));
        var selected_phenotype = localStorage.getItem("_Phenotype");
	var useragent = localStorage.getItem("_UA");
	var select_phenotype_html = "<table><tr>";
	//if (useragent.toString().indexOf("chrome") > 0) {
		//$('#select_phenotype_div').css({'overflow':'scroll','white-space': 'nowrap','max-width':'550px','max-height':'90px','border':'1px solid black','margin-top':'10px'});
		$('#select_phenotype_div').css({'overflow':'scroll','white-space': 'nowrap','width':'820px','max-height':'90px','border':'1px solid black','margin-top':'10px'});
		for(var i=0;i<o.length;i++){
			select_phenotype_html += "<td><input type=\"radio\" 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+"</td>";
			if(i%4 == 3) {
                                if(i < o.length) {
                                        select_phenotype_html += "</tr><tr>";
                                } else {
                                        select_phenotype_html += "</tr>";
                                }
                        }

/*

			if (i%3 == 2) {
				select_phenotype_html += "</br>";
			} else {
				select_phenotype_html += "&#009;";
			}
*/
		}
		select_phenotype_html += "</table>";
		$('#select_phenotype_div').append(select_phenotype_html);
/*
	} else {
		var select_phenotype_html = "<form><select name=\"phenotype\">";
                for(var i=0;i<o.length;i++){
                        select_phenotype_html += "<option class=\"phenotype_radio\" name=\"select_phenotype\" value=\"" + o[i].phenotype + "\"";
                        if(o[i].phenotype == selected_phenotype){
                                select_phenotype_html += " selected";
                        }
                        select_phenotype_html += ">" + o[i].phenotype + "</option>";
                }
                select_phenotype_html += "</select>";
                $('#select_phenotype_div').append(select_phenotype_html);
	}
*/
	localStorage.setItem("_Sort","Probability");
	make_phenotype_gene_table(selected_phenotype,"Probability");
	_setClickPhenotypeRadioEvent();
	_setClickSnpEffCheckboxEvent();
	//_setClickEffGrpCheckboxEvent();
	_filterEffGrpEvent();
	_setClickCloseEvent();
	var phenotype_png_name = selected_phenotype.replace(/\s+/g, "_");
	$("#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'
                }
	});
*/
}

function make_phenotype_gene_table(selected_phenotype,sort_term){
	if ( $.fn.dataTable.isDataTable("#phenotype_gene_table") ) {
		$('#phenotype_gene_table').DataTable().destroy();
	}
	$('#phenotype_gene_table').empty();
	var phenotype_gene_table_html = '<thead><tr><th>Chr</th><th>Pos</th><th>Probability(-log<sub><small>10</small></sub>)</th><th>Gene ID</th><th>Name</th><th>snpEff Impact level<span onclick="_dialog_list_effect();"><img src="./images/info_label.png" width="11px"></span></th></tr></thead>';
	phenotype_gene_table_html += '<tfoot><tr><th>Chr</th><th>Pos</th><th>Probability(-log<sub><small>10</small></sub>)</th><th>Gene ID</th><th>Name</th><th>snpEff Impact level<span onclick="_dialog_list_effect();"><img src="./images/info_label.png" width="11px"></span></th></tr></tfoot>';
	$("#phenotype_gene_table").append(phenotype_gene_table_html);
/*
	paging = document.getElementsByName("phenotype_gene_table_length")[0].value;
	localStorage.setItem('_Paging',paging);
	if(localStorage.getItem('_Paging') === undefined) {
		localStorage.setItem('_Paging','10');
	}
	var paging = localStorage.getItem('_Paging');
*/
	$('#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.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() {

			}
		}  
	});
}

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=new Object(JSON.parse(localStorage.getItem('_Lists')));
	var paper_array = _getPhenotypePapers(o[i].id, localStorage.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 _SyncExpseq() {
        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);
        $("#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();
}

function _SyncPrimer3() {
        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.selection.value;
        qual = $("#prm_p3_qual").val();
        dp = $("#prm_p3_dp").val();
        $("#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.selection ;
		elements[0].checked = true;
        } else if (Ns==0) {
                _hideVarsite(Ns);
		var element = document.getElementById( "prm_rp3_Ns" ) ;
                var elements = element.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-5)+'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-5)+'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
lementcellDoc.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;
        query = _escapeHTML(query);
        //search chromosome pos//
        if(/:/.test(query)) {
                qpos = query;
                query = "all|";
                var chrpos = qpos.split(":");
                var posinfos = chrpos[1].split("-");
		//validate chr and pos keyword
		$.ajax({
                	url: "./bin/"+_backendSelector("validateChr.php"),
                	type: "POST",
                	cache: false,
                	data: {
				"prm_fa_chr":chrpos[0],
                        	"prm_fa_s":posinfos[0],
                        	"prm_fa_e":posinfos[1],
                        	"prm_blk":localStorage.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*localStorage.getItem("_Block")) +"bp!!";
						} else {
							errstr = "Invalid:the length between start to end is longer than " + parseInt(100000*localStorage.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 {
                			var blks = Math.round(parseInt((posinfos[1]-posinfos[0])/Objects.Block));
					var blksL = String(blks).length - 1;
					var zoomsize = Math.round(blks/Math.pow(10,blksL)) * Math.pow(10,blksL);
                			var optblks;
                			//if (blks > 900) {
                			if (zoomsize > 900) {
					　　
                			    optblks = Math.ceil(zoomsize/1000) + "k";
                			} else {
					    
                			    optblks = parseInt(zoomsize) + "b";
                			}
					
                			p=_checkPos_Chr(posinfos[0],optblks,chrpos[0]);
                			localStorage.setItem("_Chr", chrpos[0]);
                			localStorage.setItem("_Zoom", optblks);
                			localStorage.setItem("_Pos", p);
                			_changeChromosomeSearch(chrpos[0]+":"+posinfos[0]+"bp - "+posinfos[1]+"bp"+" with 100blocks");
				}
			}
		});
        } else {
		$(".search_window").css('display','inline-block');
                document.getElementById("prm_keyword").value=query;
                _dialog_go();
                _preSearchID(1);
        }
}

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>';
        }
}

