<!DOCTYPE html>
<html>


<head>
	<link rel="stylesheet" href='static/js/jquery-ui-1.11.4/jquery-ui.min.css'>
	<link rel="stylesheet" href="static/css/bootstrap.min.css">
	<link rel="stylesheet" href="static/css/grapetree.css">
</head>
<body>
<!--metadata div-->
<link rel="stylesheet" href="static/js/SlickGrid/slick.grid.css" type="text/css"/>
<link rel="stylesheet" href="static/js/SlickGrid/examples/examples.css" type="text/css"/>

<script src="static/js/SlickGrid/lib/firebugx.js"></script>

<script src="static/js/SlickGrid/lib/jquery-1.11.2.min.js"></script>
<script src="static/js/SlickGrid/lib/jquery-ui-1.11.3.min.js"></script>
<script src="static/js/SlickGrid/lib/jquery.event.drag-2.3.0.js"></script>


<script src="static/js/SlickGrid/slick.core.js"></script>
<script src="static/js/SlickGrid/plugins/slick.cellrangedecorator.js"></script>
<script src="static/js/SlickGrid/plugins/slick.cellrangeselector.js"></script>
<script src="static/js/SlickGrid/plugins/slick.cellselectionmodel.js"></script>
<script src="static/js/SlickGrid/slick.formatters.js"></script>
<script src="static/js/SlickGrid/slick.editors.js"></script>
<script src="static/js/SlickGrid/slick.grid.js"></script>
<script src="static/js/SlickGrid/slick.dataview.js"></script>

<script src= "static/js/tree/context.js?version={{config['JAVASCRIPT_VERSION']}}"></script>

<script src="static/js/tree/grid.js?version={{config['JAVASCRIPT_VERSION']}}"></script>

<script src="static/js/tree/help.js?version={{config['JAVASCRIPT_VERSION']}}"></script>


<!--information divs-->
<div id = 'welcome-div' style='background:white;padding:10px'>
<span id= 'welcome-div-close' class="glyphicon glyphicon-remove" style="float:right;margin-right:5px;zoom:1.5;display:none" onclick="$('#welcome-div').hide()"></span>
<div id='welcome-div-text'>
</div>
</div>

<div id ='information-div' class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content modal-sm">
      <div id ="modal-header" class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <p align='center'><img id ='waiting-image'style = 'display:none' src= 'static/js/img/ms_failed_1.png'></img></p>
	<span id = 'modal-title'></span>
      </div>
      <div class="modal-body">
        <p id ='waiting-information'></p>
		<div  id ='param-panel' style = 'display:none'>
		   <label>Method</label>
		   <select id ='method-select'>
			   <option class='show-tooltip' title='MSTreeV2 uses a directed graph to handle missing data' value='MSTreeV2'>MSTreeV2</option>
			   <option class='show-tooltip' title='A traditional Minimum spanning tree + eBurst weighting' value='MSTree'>MSTree</option>
			   <option class='show-tooltip' title='FastME V2.0 is implemented for Neighbor-Joining phylogeny.' value='NJ'>Neighbour Joining</option>
		   </select>
		   <label><input id ='check-memory' type="checkbox" checked /> Check memory usage</label>
	   </div>
      </div>
      <div class="modal-footer">
        <button id ="modal-ok-button" type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<div id='sidebar'>
	<div>
		<a class='show-tooltip' title="EnteroBase" href="https://enterobase.warwick.ac.uk" target = '_blank'><img src="static/js/img/enterobase.png" alt="Enterobase" style="width:40px;height:45px;"></a>&nbsp;&nbsp;|&nbsp;&nbsp;
		<a class='show-tooltip' title='GrapeTree GitHub repository' href="https://github.com/martinSergeant/EnteroMSTree" target = '_blank'><img src="static/js/img/GrapeTree.PNG" alt="GrapeTree" style="width:40px;height:50px;"></a>&nbsp;&nbsp;|&nbsp;&nbsp;
		<a class='show-tooltip' title='Help' href="https://bitbucket.org/enterobase/enterobase-web/wiki/GrapeTree" target = '_blank'><span class="glyphicon glyphicon-question-sign" style="font-size:30px;height:50px;margin-right:5px;top:10px"></span></a>
		<h3 id="headertag" style="font-family: times, serif; font-size:12pt; font-style:italic">GrapeTree</h3>
	</div>
	<br>
	<div id='input-output-panel' class='panel panel-default'>
		<div class ='panel-heading mst-menu-title' id= 'file-menu'> <b id='input-output-title'>Inputs/Outputs</b><span id = 'file-menu-icon' class='glyphicon glyphicon-menu-down'> </span></div>
		<div class = "panel-body" id ='file-menu-panel'>
		<div id ='load-panel'>
			<button title='Handles trees, profiles and metadata files' id = 'button-files' class = 'show-tooltip'> Load Files</button>
			<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:5px" onclick="getHelpBox('load_files');"></span>
			<hr>
		</div>
			<div id='save-panel'>
					<button id ="save-tree-json">Save GrapeTree</button>
					<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:5px" onclick="getHelpBox('save_grapetree');"></span><br>
					<button id ="save-tree-nwk">Save as Newick Tree</button><br>
					<button id ="mst-download-svg">Download SVG</button><br>
			</div>
		</div>
	</div>
	<div class='panel panel-default'>
		<div class ='panel-heading mst-menu-title' id= 'tree-menu'> <b id>Tree Layout</b><span id = 'tree-menu-icon' class='glyphicon glyphicon-menu-right'> </span></div>
		<div class = "panel-body" id ='tree-menu-panel' style='padding:0px;' ><br>
			<button id = 'button-goback' style='margin-left:15px;' onclick='loadMSTree(tree_raw);if(current_metadata_file) {loadMetadataText(current_metadata_file[0], current_metadata_file[1]);}'> Original tree</button>
			<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:15px" onclick="getHelpBox('tree_layout');"></span>
			<br>
			<button id = 'button-refresh' style='margin-left:15px;' > Static Redraw </button>
			<br>
			<button id ="center-graph-button" style='margin-left:15px;' >Centre Tree</button>
			<br>
			<label><input id ='show-node-tooltip' style='margin-left:15px;'  type="checkbox" checked  /> Show Tooltips</label>
			<hr>
			<p align = 'center'>
				<label> Drag Icon to Rotate:&nbsp;</label>
				<span id="rotation-icon" class="glyphicon glyphicon-refresh"></span>
				<br>
				<label>Zoom:&nbsp;</label>
				<span onclick= "javascript:the_tree.setScale(1.1,true)" class=' zoom-icon glyphicon glyphicon-zoom-in'></span>
				<span onclick= "javascript:the_tree.setScale(0.9,true)"class='zoom-icon glyphicon glyphicon-zoom-out'></span>
			</p>
			<div class='panel panel-default sub-panel'>
				<div class ='panel-heading mst-menu-title' id= 'mst-node-menu'> <b id>Node Style</b><span id = 'mst-node-menu-icon' class="glyphicon glyphicon-menu-right"></span></div>
				<div class = "panel-body" id ='mst-node-menu-panel' >
					<label>Colour By:</label>
					<br>
					<select style="width:160px" id= 'metadata-select'>
					<option value='nothing'>No category</option></select>
					<hr>
					<label><input id ='show-node-labels'type="checkbox" checked /> Show Labels</label>
					<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:5px" onclick="getHelpBox('show_labels');"></span>
					<select style='width:160px' id = 'node-label-text'></select>
					<br>
					<label>Font Size:</label>
					<br>
					<div id = "slider-node-fontsize" class = "slider-class"></div><input type='text' style='width:20px;height:15px' id ='spinner-node-fontsize' class='spin-group'><br>
					<hr>
					<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:5px" onclick="getHelpBox('node_size');"></span>
					<div >
						<span onclick="$('#spinner-nodesize').spinner('value', 100)" class='glyphicon glyphicon-fast-backward'></span><label>&nbsp;&nbsp;Node Size (%)</label><br>
						<div id = "slider-nodesize" class ="slider-class"></div><input type='text'  id ='spinner-nodesize' class='spin-group'>
					</div>
					
					<div class="show-tooltip" title="Node size relative to number of strains">
						<span onclick="$('#spinner-relative-nodesize').spinner('value', 100)" class='glyphicon glyphicon-fast-backward'></span><label>&nbsp;&nbsp;Kurtosis (%)</label><br>
						<div id = "slider-relative-nodesize" class ="slider-class"></div><input type='text'  id ='spinner-relative-nodesize' class='spin-group'>
					</div>
					<hr>
					<label>Highlight Label</label>
					<br>
					<input size="11" id ='search-metadata-input'><span id ='search-metadata-icon' class='add-data-icon glyphicon glyphicon-search'></span>
					<br>
					<label><input id ='show-individual-segments' type="checkbox" /> Show Pie Chart</label>
					<br>			
				</div>
			</div>			
			<div class='panel panel-default  sub-panel'>
				<div class ='panel-heading mst-menu-title' id= 'mst-link-menu'> <b id>Branch Style</b><span id = 'mst-link-menu-icon' class='glyphicon glyphicon-menu-right'> </span></div>
				<div class = "panel-body" id ='mst-link-menu-panel'>
					<label><input id ='show-link-labels'type="checkbox" /> Show Labels</label>
					<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:5px" onclick="getHelpBox('branch_labels');"></span>
					<br>
					<label>Font Size:</label>
					<br>
					<div id = "slider-linkfontsize" class = "slider-class"></div><input type='text' style='width:20px;height:15px' id ='spinner-linkfontsize' class='spin-group'>
					<br>
					<div>
						<span onclick="$('#spinner-linklength').spinner('value', 100)" class='glyphicon glyphicon-fast-backward'></span><label>&nbsp;&nbsp;Scaling (%)</label><br>
						<div id = "slider-linklength" class ="slider-class">  </div><input type='text'  id ='spinner-linklength' class='spin-group'>
					</div>
					
					<div class="show-tooltip" title="Collapse branches below a certain value">
						<span onclick="$('#spinner-collapse-nodes').spinner('value', 0)" class='glyphicon glyphicon-fast-backward'></span><label>&nbsp;&nbsp;Collapse Branches</label><br>
						<div id = "slider-collapse-nodes" class ="slider-class"></div><input type='text'  id ='spinner-collapse-nodes' class='spin-group'>
					</div>
					<label><input id ='link-log-scale'type="checkbox" />Log Scale</label>
					<hr>
					<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:5px" onclick="getHelpBox('branch_cutoffs');"></span>
					<label>For branches <br> longer than:<input type='text' id ='spinner-hide-link-length' class='spin-group'></label>
					<table><tbody><tr>
					<td>
						<div style="opacity: 1;"><input type="radio" id="handle-long-branch-display" name="handle-long-branch" value="display" checked="" style="opacity: 1;">Display</div>
					</td>
					<td style="padding-left:10px">
						<div style="opacity: 1;"><input type="radio" id="handle-long-branch-hide" name="handle-long-branch" value="hide" style="opacity: 1;">Hide</div>
					</td>
					<td style="padding-left:10px">
						<div style="opacity: 1;"><input type="radio" id="handle-long-branch-cap" name="handle-long-branch" value="cap" style="opacity: 1;">Shorten</div>
					</td>
					</tr></tbody></table>
				</div>		
			</div>
		</div>
	</div>


	<div class='panel panel-default'>	
		<div class ='panel-heading mst-menu-title' id= 'mst-layout-menu'> <b id>Rendering</b><span id = 'mst-layout-menu-icon' class="glyphicon glyphicon-menu-right"></span></div>
		<div class = "panel-body" id ='mst-layout-menu-panel'>
			<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:5px" onclick="getHelpBox('rendering');"></span>
			<div><input type='radio' name='render-method' class='render-method' value='automatic'/><b>Dynamic</b></div>
			<div style='margin-left:20px;font-size:90%'><input id ='render-selected-only' type="checkbox" checked /> Selected Only</div>
			
			<div style="margin-top:20px"><input type='radio' name='render-method' class='render-method' value='static' checked /><b>Static</b></div>
			<div style='margin-left:20px;font-size:90%'><input id ='correct_link_length' type="checkbox" checked /> Real Branch Length</div>
		</div>		
	</div>
	<div class='panel panel-default'>
		<div class ='panel-heading mst-menu-title' id= 'right-menu'> <b id>Context Menu</b><span id = 'right-menu-icon' class='glyphicon glyphicon-menu-right'> </span></div>
		<div class = "panel-body" id ='right-menu-panel'>
			<span class="glyphicon glyphicon-question-sign" style="float:right;margin-right:5px" onclick="getHelpBox('context_menu');"></span>
			<div class='open-context' id='mst-svg-x' style='font-size:110%;margin:10px'>GrapeTree</div>
			<div class='open-context' id='myGrid-x' style='font-size:110%;margin:10px'>Metadata</div>
			<div class='open-context' id='legend-svg-x' style='font-size:110%;margin:10px'>Figure Legend</div>
		</div>
		
	</div>
</div>

<div id = "graph-div" class="graph-overlay"></div>





<script src ="static/js/main/bootstrap.min.js"></script>
<script charset="utf-8" src="static/js/main/d3.min.js"></script>
<script charset="utf-8" src="static/js/main/spin.min.js"></script>
<script charset="utf-8" src="static/js/tree/base_tree.js?version={{config['JAVASCRIPT_VERSION']}}"></script>
<script charset="utf-8" src="static/js/tree/d3_m_tree.js?version={{config['JAVASCRIPT_VERSION']}}"></script>
<script charset="utf-8" src="static/js/tree/grapetree_fileHandler.js?version={{config['JAVASCRIPT_VERSION']}}"></script>
<script> var tree_id = null</script>

<!--
{% if tree_id%}
{% include 'ms_tree/enterobase_generic_tree.html' %}
{%endif %}
-->
<script charset="utf-8">
	getHelpBox('load_files')
        MSFileChooser.prototype = Object.create(null);
        MSFileChooser.prototype.constructor= MSFileChooser;

        function MSFileChooser(filter){
                var self = this;
                this.fileInput = $("<input>").attr("type","file").hide();
                this.callback=null;
                this.fileInput.attr("accept",filter);
                $('<body>').append(this.fileInput);
                this.fileInput.change(function(event){
                        self.callback(event.target.files);

                });

        }
        MSFileChooser.prototype.setFilter=function(filter){
                this.fileInput.attr("accept", filter);
        }
        MSFileChooser.prototype.showOpenDialog=function(callback){
                this.callback=callback;
                this.fileInput.trigger("click");
        }
	function displayErrorMessage(msg){
		Enterobase.modalAlert(msg);
	}


	function getHelpBox(help_item){
	if (help_item in help_text){
		document.getElementById("welcome-div-text").innerHTML = help_text[help_item];
	}else {
		document.getElementById("welcome-div-text").innerHTML = "<b>No Help text available for this feature</b>";
	}
	$('#welcome-div').toggle();
	
	}

	function getSuffix(name){
		var arr = name.split(".");
		return arr[arr.length-1];

	}
	
	var all_files=null;
	var metatdata_file_name;
	var waiting_spinner= null;
	var waitingDialog = null;
	var metadata_categories={};
	var context_menu=null;
	var metadata_grid=null;
	var the_tree = null;
	
	var tree_name="";

	var cannot_connect=false;

	var default_control_panel_values={
		max_link_scale:500,
		base_node_size:10,
		max_link_length:"",
		size_power:0.5,
		log_link_scale:false,
		show_individual_segments:false,
		link_font_size:14,
		show_link_labels:false,
		show_node_labels:false,
		node_font_size:12,
		hide_link_length:"",
		node_collapsed_value:0
	};

        var tooltip_div =d3.select("body")
							.append("div")
							.attr("class", "tooltip")
							.style("opacity", 0)
							.style("z-index", 9)

        var legend_colour_chooser = $("<input>")
                                        .on("change",function(e){
                                                var cc  = $(this);
                                                the_tree.setColour(cc.data("category"),cc.data("value"),cc.val());
                                                the_tree.changeCategory(cc.data("category"));

                                        })
                                        .attr("type","color").hide();

        $("body").append(legend_colour_chooser);

        //a map of group to another map of name to label
	var metadata_options={};
	var new_metadata_fields=[];
	
	var locus_label ="";
	var file_chooser = new MSFileChooser(".nwk");
	var current_metadata_file = null;
	var all_files=null;
	var metadata_file_name = null;
        function downloadMetadata(){
                var lines= [];
                lines.push("Barcode\tName");
                for (var id in the_tree.metadata){
                        var item = the_tree.metadata[id];
                        var barcode = Enterobase.encodeBarcode(id,db_code);
                        lines.push(barcode+"\t"+item["Name"]);
                }
                var text= lines.join("\n");
                Enterobase.showSaveDialog(text,"tree.json");
        }

	//update all the select options
        function addMetadataOptions(options){
		
		var fields = Object.keys(options).sort(function(m, n) {return m==='nothing' ? -1 : n === 'nothing' ? 1 : ((m < n) ? -1 : 1)});
		for (var fld_id in fields) {
			var value = fields[fld_id];
			var obj =options[value];
			var category = null;
			var label = ""
			if (typeof obj === 'object'){
				label =obj['label'];
				category = obj['category'];
				
			}
			else{
				label=obj;
			}
			var append_to_1 = $("#metadata-select");
			var append_to_2=  $("#node-label-text")
			if (category){
				if (!metadata_categories[category]){
					metadata_categories[category]=true;
					append_to_1 =$("<optgroup>").attr("label",category);
					append_to_2=$("<optgroup>").attr("label",category);
					$("#metadata-select").append(append_to_1);
					$("#node-label-text").append(append_to_2);
				}
				else{
					var to_find = "[label='"+category+"']";
					append_to_1 = $("#metadata-select").find(to_find);
					append_to_2 = $("#node-label-text").find(to_find);
				
				}
			
			}		
			append_to_1.append($("<option>").attr("value",value).text(label));
			append_to_2.append($("<option>").attr("value",value).text(label));
			//$("#add-new-values-select").append($("<option>").attr("value",value).text(label));			
		}	
        }
	
	
	
	
	function deleteMetadataCategory(){
		var category = $("#add-new-values-select").val();
		the_tree.removeCategory(category);
		$("#metadata-select option[value='"+category+"']").remove();
		$("#node-label-text option[value='"+category+"']").remove();
		$("#add-new-values-select option[value='"+category+"']").remove();
		delete metadata_options[category];
	
	}


        function showToolTip(msg, e){
						if (!e) {e=d3.event;}
                        tooltip_div.transition()
							.duration(200)
							.style("opacity", .9);
						tooltip_div.html(msg)
							.style("left", (e.pageX) + "px")
							.style("top", (e.pageY - 28) + "px")
							.style("height", "auto");
						setTimeout(hideToolTip, 2000);
        }

        function hideToolTip(){
                        tooltip_div.transition()
                        .duration(500)
                        .style("opacity", 0);
        }
	

        function addNewValues(){
                var value = $("#add-new-values-input").val();
                if (! value){
                        return;
                }
                var ids = the_tree.getSelectedIDs();
                var len = ids.length;
                if (len ===0){
                        return;

                }
                var field = $("#add-new-values-select").val();

                var meta = {};
                for (var i in ids){
                        var id = ids[i];
                        var obj={}
                        obj[field]=value;
                        meta[id]=obj;

                }
                the_tree.addMetadata(meta);
                the_tree.changeCategory(field);
		the_tree.clearSelection();
		
        }


        function addExtraField(){
                var name = $("#add-extra-field-input").val();
                if (!name){
                        return;
                }
                addMetadataOptions(name,name);
                $("#metadata-select").val(name);
                $("#add-new-values-select").val(name);
                the_tree.changeCategory(name);
		metadata_grid.updateMetadataTable();
        }

        function treeLoaded(tree){
		//add the extra functionality
		metadata_grid = new D3MSMetadataTable(tree);
		if (tree_id){
			metadata_grid.setAddColumnFunction(function(name){
				addCustomColumn(name);
			})
		}
		context_menu= new D3MSTreeContextMenu(tree,metadata_grid);
		metadata_grid.updateMetadataTable();
		//add the ability to show/hide grid, 
	
		//update the dropdowns if new options added
		tree.addTreeChangedListener(function(type,data){
			if (type === 'metadata_options_altered'){
				addMetadataOptions(data);
			}
			else if (type === 'nodes_collapased'){
				$( "#spinner-collapse-nodes" ).val(data);
				var v = parseFloat(data);
				$("#slider-collapse-nodes").slider('value', Math.log(v)*1000);
			}
		});
		
		tree.addDisplayChangedListener(function(type,data){
			if (type==='category_changed'){
				$("#metadata-select").val(data);
			}
		
		});

		tree.legendItemClicked = function(data){
			legend_colour_chooser
			.css({"left":0,"top":0})
			.val(data.colour)
			.data({"value":data.value.split("  [")[0],"category":data.category})
			.trigger("click");
                };

		$("#spinner-hide-link-length").spinner({
			min: 0,
			max: tree.max_link_distance,
				step:(tree.max_link_distance/1000.0).toPrecision(1)
			});
		$( "#spinner-collapse-nodes" ).spinner({
			min: 0,
			max: tree.max_link_distance,
			value: tree.node_collapsed_value,
			step: 0.000001,
		});

		$( "#slider-collapse-nodes" ).slider({
			min:Math.log(1e-7)*1000,
			max: Math.log(tree.max_link_distance+0.01)*1000,
			value: Math.log(tree.node_collapsed_value)*1000,
		});
		tree.centerGraph();
		$(waiting_spinner.el).hide();
                 $("#waiting-information").text("Complete. Tree has "+tree.force_nodes.length+" nodes");
                $("#waiting-image").attr("src","static/js/img/ms_complete_1.png").show();
               // legend_colour_chooser.hide();
		$("#information-div").modal("hide");

        }

        function treeLoading(tree,msg){
                if (msg==='complete'){
                        treeLoaded(tree);
                }
                else{

                        $("#waiting-information").text(msg)

                }

        }


    function loadFailed(msg){
		$("#information-div").modal("show");
		$(waiting_spinner.el).hide();
                $("#waiting-image").attr("src","static/js/img/ms_failed_1.png").show();
                $("#waiting-information").text(msg);
        }

	function setControlPanel(data){
		$("#slider-linklength").slider("value",Math.log(data['max_link_scale']/5.)*1000.0);
		$("#spinner-linklength").val(data['max_link_scale']/5.);

		$("#slider-nodesize").slider("value",data['base_node_size']*10);
		$("#spinner-nodesize").val(data['base_node_size']*10);

		if (data['max_link_length']){
			$("#spinner-hide-link-length").val(data['max_link_length']);
			$("#handle-long-branch-hide").prop("checked", true);
		} else if (data['hide_link_length']){
			$("#spinner-hide-link-length").val(data['hide-link-length']);
			$("#handle-long-branch-cap").prop("checked", true);
		}

		if (data['size_power']){
			$("#slider-relative-nodesize").slider("value",data['size_power']*200.0);
			$("#spinner-relative-nodesize").val(data['size_power']*200.0);
		}

		if (data['log_link_scale']){
			$('#link-log-scale').prop('checked', true);
		}
		if (data['show_individual_segments']){
			$("#show-individual-segments").prop("checked",true);
		}
		if (data['link_font_size']){
			$("#slider-linkfontsize").slider("value",data['link_font_size']);
			$("#spinner-linkfontsize").spinner("value",data['link_font_size']);
		}
		var sll =true;
		if (data['show_link_labels']===false){
			sll= false;
		}

		$("#show-link-labels").prop("checked",sll);
		$("#show-node-labels").prop("checked",data['show_node_labels']);
		if (data['node_font_size']){
			$("#slider-node-fontsize").slider("value",data['node_font_size']);
			$("#spinner-node-fontsize").spinner("value",data['node_font_size']);
		}
		var col_value = data['node_collapsed_value']?data['node_collapsed_value']:0;
		$( "#slider-collapse-nodes" ).slider("value",Math.log(col_value)*1000);
		$("#spinner-collapse-nodes").val(col_value);
	}



	function loadMSTree(data){
		metadata_options = {};
		if (the_tree) {
			the_tree.svg.remove();
			the_tree.legend_div[0].remove();
			//resetGridColumns();
			$("#metadata-select").find("option").remove();
			$("#node-label-text").find("option").remove();
			$("#metadata-div").remove();
			$("#context-menu").remove();
		}
		$("#waiting-information").text("Loading Data");
		the_tree = null;
		the_tree = new D3MSTree(
        "graph-div",JSON.parse(JSON.stringify(data)),function(tree,msg){
				treeLoading(tree,msg);

		});
		
		the_tree.addSegmentOverListener(function(d){
				if ($("#show-node-tooltip").prop("checked")){
						if (the_tree.display_category === 'nothing') {
							var node_ids = the_tree.grouped_nodes[d.data.idx];
							var value = $.map(node_ids, function(idx) {return the_tree.metadata[idx].Name ? the_tree.metadata[idx].Name : the_tree.metadata[idx].ID}).join('<br>');
							showToolTip(value);
						} else {
							var display = d.data.type;
							showToolTip(display+"("+d.data.value+")");
						}
				}
		});
		the_tree.addSegmentOutListener(function(d){
				 hideToolTip();
		});
		the_tree.addLinkOverListener(function(d){
				if ($("#show-node-tooltip").prop("checked")){
						showToolTip("length:"+d.value);
				}

		});
		the_tree.addLinkOutListener(function(d){
				hideToolTip();
		});
		the_tree.resize();

		if (the_tree.metadata_info){
				addMetadataOptions(the_tree.metadata_info);
		}
		$("#metadata-select").val('nothing');
		$("#node-label-text").val('ID');
		
		if (data['initial_category']){
			$("#metadata-select").val(data['initial_category']);
		}
		if (data['layout_data'] && data['layout_data']['nodes_links']){
			setControlPanel(data['layout_data']['nodes_links'])
		}
		else{
			setControlPanel(default_control_panel_values);
		}
		if (current_metadata_file) {
			loadMetadataText(current_metadata_file[0], current_metadata_file[1]);
		} else {
			//updateMetadataTable();
		}
		$("#rotation-icon").draggable({
		  containment: "#sidebar",
		  scroll: false,
		  start: function(e) {
			the_tree._dragStarted(the_tree.force_nodes[0], [$("#rotation-icon").position().left, $("#rotation-icon").position().top]);
		  },
		  drag: function(e) {
			the_tree._dragging(the_tree.force_nodes[0], [e.clientX, e.clientY]);
		  },
		  stop: function(e) {
			the_tree._dragEnded(the_tree.force_nodes[0], [e.clientX, e.clientY]);
		  },
		  revert: true,
		  revertDuration: 10,
		  helper: function() {return $("<div style='cursor:none'><label id='angle-text'></label></div>")},
		});
		$("#rotation-icon").on("drag", function(event, ui) {
			var x_dif = ui.helper.position().left - $("#rotation-icon").position().left;
			var y_dif = $("#rotation-icon").position().top - ui.helper.position().top;
			var angle = y_dif !== 0 ? Math.atan(x_dif/y_dif)/Math.PI * 180 : (x_dif === 0 ? 0 : (x_dif > 0 ? 90 : -90));
			if (y_dif < 0 ) {
				angle = 180 + angle;
			} else if (x_dif < 0) {
				angle = 360 + angle;
			}
			ui.helper.select('.angle-text').text(Math.round(angle) + '\xB0').css({
				'font-size':'1.2em',
				'font-style':'bold',
			}) ;

		});

		$('.panel-default').find('input, textarea, button, select, div, span').css("opacity", 1.0).prop('disabled',false);
	}


 function initiateLoading(msg){
	$("#welcome-div-close").show();
	$("#welcome-div").draggable().css({position:'relative', border:'1px solid black', margin:'10px', 'z-index':9999}).hide();
	$("#graph-div").empty();
	$("#metadata-select").empty();
	$("#add-new-values-select").empty();
	metadata_options={};
	showWaitingDialog(msg);
 }

function showModalForParams(){
	$("#information-div").modal("show");
	$("#param-panel").show();
}

tree_raw = {};
 function processProfileFile(profile){
	if ($("#check-memory").prop('checked')) {
		profile2check(profile);
	} else {
		profile2tree(profile);
	}
 };
 
function profile2check(profile) {
	  try{
		$.ajax({
				method: "POST",
				url: "/maketree",
				data: {
				profile:profile,
				method:$("#method-select").val(),
				checkEnv:1,
			},
			startTime : new Date(),
		}).done(function(result){
				$("#information-div").modal("hide");
				var sys_info = JSON.parse(result);
				var diag = $('<div id="send-to-tree" title="Estimated memory / time usage"></div>').appendTo($("body"));

				diag.append("<p><label>Memory (MB): </label>"+Math.round(sys_info.memory/1024/1024) + "</p>");
				var deltaTime = new Date() - this.startTime;
				diag.append("<p><label>Time (minutes): </label>"+Math.round((sys_info.time+deltaTime/1000)/6)/10 + "</p>");
				diag.append("<p>Numbers are raw estimates and may be different from your system. </p>");
				if (! sys_info.affordable) {
					diag.append("<p><label style='font-color:red'>WARNING: More memory are required than you current have. The tree may still be calculated because some system can automatically compress the memory. However the calculation will take more time and may crash! </label></p>");
				}
				diag.append("<p><label>Calculate the tree? </label></p>");
				
				diag.dialog({
					width: 400,
					resizable: false,
					height: "auto",
					modal: true,
					close : function(e) {
						diag.dialog('destroy').remove();
					}, 
					buttons: {
						Yes: function(){
							profile2tree(profile);
							$(this).dialog("close");
						},
						No: function() {
							$(this).dialog("close");
						}
					}
				});
	   }).fail(function( jqXHR, textStatus){
				if (jqXHR.status == 405 || jqXHR.status == 404) {
					loadFailed("Cannot reach the backend. Please download a FREE standalone version from https://github.com/martinSergeant/EnteroMSTree/");
				} else {
					console.log(textStatus);
					loadFailed("There server returned an error. Is the profile file in the right format?");
				}
	   });
	   }catch(e){
				loadFailed("The server could not be contacted");
	   }
		$("#waiting-information").text("Estimating memory / time usage...");
}
 
 function profile2tree(profile) {
 $("#information-div").modal("show");
              try{
                $.ajax({
                        method: "POST",
                        url: "/maketree",
                        data: {
						profile:profile,
						method:$("#method-select").val(),
						checkEnv: 0,
				}
                }).done(function(result){
						tree_raw = {"nwk":result,"layout_algorithm":$("#layout-select").val()};
						$("#headertag").text( $("#headertag").text() + ' (' + $("#method-select").val() + ')' );
						loadMSTree(tree_raw);
               }).fail(function( jqXHR, textStatus){
						if (jqXHR.status == 405 || jqXHR.status == 404) {
							loadFailed("Cannot reach the backend. Please download a FREE standalone version from https://github.com/martinSergeant/EnteroMSTree/");
						} else {
							console.log(textStatus);
							loadFailed("There server returned an error. Is the profile file in the right format?");
						}
               });
               }catch(e){
                        loadFailed("The server could not be contacted");
               }
                $("#waiting-information").text("Computing Tree");
 }

 function showWaitingDialog(msg){
	$("#information-div").modal("show");
	$("#waiting-image").hide();
	$(waiting_spinner.el).show();
	$("#waiting-information").text(msg).show();
 }



		
 



window.onload = function (){
	$(document).on('show-help', function(e, ui) {
		getHelpBox(ui.id);
	});
	$("#mst-svg-x").on('click', function(e) {
		context_menu._trigger_context("mst-svg", e);
	});
	$("#myGrid-x").on("click", function(e) {
		context_menu._trigger_context("myGrid", e);
	});
	$("#legend-svg-x").on("click", function(e) {
		context_menu._trigger_context("legend-svg", e);
	});

	$(".show-tooltip").on('mouseenter', function(e){
		showToolTip($(this).attr('title'), {
			pageX:$(this).offset().left + $(this).width() + 10, 
			pageY:$(this).offset().top + $(this).height()/2+10
		});
	}).on('mouseleave', function(e) {
		setTimeout(hideToolTip, 200);
	});

        //allow dragging and dropping files
        $("#graph-div").on('dragover',function(e) {
                e.preventDefault();
                e.stopPropagation();
            }
        )
        .on('dragenter',function(e) {
                e.preventDefault();
                e.stopPropagation();
                }
        )
        .on("drop",function(e){
                e.originalEvent.stopPropagation();
                e.originalEvent.preventDefault();
                var files = e.originalEvent.dataTransfer.files;
                filesDropped(files);
        });
		
		$(".render-method").on("change", function(e) {
			if (this.value == 'static') {
				the_tree.fixAllNodes( document.getElementById("correct_link_length").checked );
			} else if (this.value == 'automatic') {
				the_tree.unfixSelectedNodes(! $("#render-selected-only").is(":checked"));
			}
		});
		$("#handle-long-branch-display, #handle-long-branch-hide, #handle-long-branch-cap").on("change", function(e) {
			var max = $("#spinner-hide-link-length").val();
			if (!max) {
				max = the_tree.max_link_distance+1;
			}
			if (this.value == 'hide') {
				the_tree.setMaxLinkLength(the_tree.max_link_distance+1);
				the_tree.setHideLinkLength(max);
			} else if (this.value == 'cap') {
				the_tree.setHideLinkLength(the_tree.max_link_distance+1);
				the_tree.setMaxLinkLength(max);
			} else {
				the_tree.setMaxLinkLength(the_tree.max_link_distance+1);
				the_tree.setHideLinkLength(the_tree.max_link_distance+1);
			}
		});
		$("#spinner-hide-link-length").on('change', function(e) {
			var max = $("#spinner-hide-link-length").val();
			if (!max) {
				max = the_tree.max_link_distance+1;
			}
			var method = null;
			if ($("#handle-long-branch-hide").prop("checked")) {
				method = 'hide';
			} else if ($("#handle-long-branch-cap").prop("checked")) {
				method = 'cap';
			}
			if (method == 'hide') {
				the_tree.setMaxLinkLength(the_tree.max_link_distance+1);
				the_tree.setHideLinkLength(max);
			} else if (method == 'cap') {
				the_tree.setHideLinkLength(the_tree.max_link_distance+1);
				the_tree.setMaxLinkLength(max);
			}
		});

        $("#upload-metadata-icon").click(function(e){
                if (!metadata_options['Custom Fields']){
                        Enterobase.modalAlert("Please add a custom field before uplaoding a file containing values for this field");
                        return;
                }
                var i = Enterobase.makeCustomFileInput("fileupload",function(file){
                        uploadMetadata(file);
                });
                i.trigger("click");
        });

        $("#metadata-select").on("change",function(e){
                the_tree.changeCategory($(this).val());
        });
        $("#node-label-text").change(function(e){
               the_tree.setNodeText($(this).val());
        });

        $("#mst-download-svg").click(function(e){
			saveTextAsFile(the_tree.getSVG(),"MSTree.svg");
        });

        $(".panel-body").hide();

        $( "#slider-linklength" ).on("change", function(e) {
					var brlen = Math.exp($(this).slider("value")/1000.0);
					$("#spinner-linklength").spinner('value', brlen);
		})
		.slider({
                orientation: "horizontal",
                min: 1609,
                max: 9903,
                value: 4605,
        });
		
		$("#spinner-linklength").on("change", function (e){
				var brlen = parseInt($(this).val());
				$( "#slider-linklength" ).slider('value', Math.log(brlen)*1000.0);
				the_tree.setLinkLength(brlen*5.0);
		})
		.spinner({
			min: 5,
			max: 20000,
			value: 100,
			step: 1,
		});
		$(".slider-class").slider({
			slide: function(e) {
				$(this).trigger('change');
			},
			change: function(e) {
				if (e.originalEvent) {
					$(this).trigger('change');
				}
			}
		});
		$(".spin-group").spinner({
			spin: function(e, ui) {
				$(this).spinner("value", ui.value);
			},
			change: function(e) {
				$(this).trigger('change');
			}
		}).keypress(function(e){
			if (e.which === 13) {
				$(this).spinner("value", $(this).val());
			}
		});

        $( "#slider-nodesize" ).on("change", function(e) {
			$( "#spinner-nodesize" ).spinner("value", $(this).slider("value"));
		})
		.slider({
                orientation: "horizontal",
                min:20,
                max:500,
                value: 100,
        });
        $( "#spinner-nodesize" ).on('change', function(){
						the_tree.setNodeSize(parseInt($(this).val())/10.);
						$( "#slider-nodesize" ).slider("value", parseInt($(this).val()));
					})
		.spinner({
                min:20,
                max:500,
                value: 100,
        });


        $( "#slider-relative-nodesize" ).on("change", function(e) {
			$( "#spinner-relative-nodesize" ).spinner("value", $(this).slider("value"));
		})
		.slider({
                orientation: "horizontal",
                min:30,
                max:150,
                value: 100,
                step:1,
        })
		$( "#spinner-relative-nodesize" ).on("change", function(e){
			the_tree.setRelativeNodeSize(parseInt($(this).val())/200.0);
			$( "#slider-relative-nodesize" ).slider("value", parseInt($(this).val()));
		})
		.spinner({
                min:30,
                max:150,
                value: 100,
                step:1,
        });

        $( "#slider-node-fontsize" ).on("change", function(e) {
			$("#spinner-node-fontsize").spinner('value', $(this).slider("value"));
		})
		.slider({
                orientation: "horizontal",
                min:6,
                max: 30,
                value: 12,
        });
		$("#spinner-node-fontsize").on("change", function(e) {
				$( "#slider-node-fontsize" ).slider('value', parseInt($(this).val()));
				the_tree.setNodeFontSize(parseInt($(this).val()));
		})
		.spinner({
			min: 6,
			max: 30,
			value: 12,
		});

        $( "#slider-linkfontsize" ).on("change", function(e) {
			$("#spinner-linkfontsize").spinner('value', $("#slider-linkfontsize").slider("value"));
		})
		.slider({
                orientation: "horizontal",
                min:6,
                max: 30,
                value: 14,
        });
		$("#spinner-linkfontsize").on("change", function(e) {
				$( "#slider-linkfontsize" ).slider('value', parseInt($(this).val()));
				the_tree.setLinkFontSize(parseInt($(this).val()));
		})
		.spinner({
			min: 6,
			max: 30,
			value: 14,
		});


        $( "#slider-charge" ).on("change", function(e) {
        	the_tree.alterCharge($("#slider-charge").slider("value"));
			$(this).prop("title", $(this).slider("value"));
		})
		.slider({
			orientation: "horizontal",
			min:0,
			max: 30,
        });

        $("#node-label-text").change(function(e){
                var val = $(this).val();
                if (val ==="cat"){
                        val = the_tree.display_category;
                }
                the_tree.setNodeText(val);
        });


        $("#button-refresh").click(function(){
		showWaitingDialog("Refreshing The Tree");
		setTimeout(function(){
			the_tree.refreshGraph();
			$("#information-div").modal("hide");
		},500)

        });
        $("#show-link-labels").click(function(e){
                the_tree.showLinkLabels($(this).is(":checked"))
        });
        $("#show-node-labels").click(function(e){
                the_tree.showNodeLabels($(this).is(":checked"));
        });
        $("#show-individual-segments").click(function(e){
                the_tree.showIndividualSegments($(this).is(":checked"));
        });

        $("#show-node-tooltip").click(function(e){
                show_node_tooltips = $(this).is(":checked");
        });

        $("#link-log-scale").click(function(e){
                the_tree.setLogLinkScale($(this).is(":checked"));
        });

		$("#button-files").click(function(e) {
				var diag = $('<div id="read-text" title="Paste or read files"></div>').appendTo($('body'))
								.append("<p><label>Paste a tree, profile or metadata here: </label></p>")
								.append("<textarea id='paste-text' rows='10' cols='100'>")
								.append("<p><label>Or load the files directly: </label></p>")
								.append("<button title='Handles trees, profiles and metadata files' id = 'button-load-nwk' class = 'show-tooltip'> Load Files</button>");
				$("#button-load-nwk").click(function(e){
						file_chooser.setFilter("");
						file_chooser.showOpenDialog(function(files){
								filesDropped(files);
								diag.dialog("close");
						});
				});
				
				diag.dialog({
					width: "auto",
					resizable: false,
					height: "auto",
					modal: false,
					close: function() {
						$("#read-text").dialog('destroy').remove();
					},
					buttons: {
						Confirm: function(){
							distributeFile($("#paste-text").val(), '');
							$(this).dialog("close");
						},
						Cancel: function() {
							$(this).dialog("close");
						}
					}
				});
		});
		

         $( "#slider-collapse-nodes" ).on("change", function(e) {
			var val = Math.exp($(this).slider('value')/1000);
			$("#spinner-collapse-nodes").spinner('value', val);
		 })
		 .slider({
			orientation: "horizontal",
			min:0,
			max: 100,
			value: 0,
        });

	$( "#spinner-collapse-nodes" ).on("change", function(e) {
		var v = parseFloat($(this).spinner('value'));
		if (v != $(this).data.v) {
			$(this).data.v = v;
			$("#slider-collapse-nodes").slider('value', Math.log(v)*1000);
			the_tree.collapseNodes(v);
		}
	})
	.spinner({
		min:0,
		value: 0
	});

	$("#save-tree-json").click(function(e){
			saveTextAsFile(JSON.stringify(the_tree.getTreeAsObject()),"ms_tree.json");
	});

	$("#save-tree-nwk").click(function(e){
			saveTextAsFile(the_tree.getTreeAsNewick(),"ms_tree.nwk");
	});

	$("#center-graph-button").click(function(e){
		 the_tree.centerGraph();

	});

	$("#search-metadata-icon").click(function(e){
		var keyword= $("#search-metadata-input").val();
		if (!keyword){
			return;
		}
		var ids = the_tree.searchMetadata(keyword, $("#node-label-text").val());
		the_tree.highlightNodes(ids);
	});

	$("#modal-ok-button").click(function(e){
		var profile_file =  $(this).data("profile_file")
		if (profile_file){
			processProfileFile(profile_file);
			$(this).data("profile_file",null);
			$("#modal-ok-button").html("Close");
			$("#param-panel").hide();
			e.stopImmediatePropagation();
			$("#modal-title").hide();
			showWaitingDialog("Processing Profiles");
		}
	});

        $("#method-select").change(function(e) {
			if ($(this).val() == "MSTree") $("#MST-option").show();
			else $("#MST-option").hide();
		})

        $("#matrix-select").change(function(e) {
			if ($(this).val() == "symmetric") $("#symmetric-option").show();
			else $("#symmetric-option").hide();
		})

		$("#graph-div").on('dblclick', function(e){
		    if (the_tree) the_tree.clearSelection();
       })
	
	var target = document.getElementById('modal-header');
	waiting_spinner= new Spinner({color:'black', lines: 12,top:"13%"}).spin(target);


	$('.panel-default').find('input, textarea, button, select, span, div').css("opacity", 0.3).prop('disabled',true);
	if (! tree_id){
		$("#file-menu-panel").css("opacity", 1.0).addClass("open-menu-panel").show();
		$("#button-files").parent().css('opacity', 1.0);
		$("#button-files").css("opacity", 1.0).prop("disabled", false).trigger('mouseenter');
	}

	window.addEventListener("beforeunload", function (e) {
		if (the_tree) {
			var confirmationMessage = 'All the modifications will lost if you have not saved the GrapeTree as a local file.';
			(e || window.event).returnValue = confirmationMessage;
			return confirmationMessage;
		}
	});
	if (tree_id){
		setupEnterobasePanel();
		initiateLoading("Waiting");
		getRemoteData();
	}
	 $(".mst-menu-title").click(function(e){
				if($(this).prop("disabled") === true) {
					return;
				}
		var id = $(this).attr("id");
		var this_panel =  $("#"+id+"-panel");
		var icon = $("#"+id+"-icon");
		if  (this_panel.hasClass("open-menu-panel")){
			this_panel.toggle("50");
			this_panel.removeClass("open-menu-panel");
			icon.attr("class","glyphicon glyphicon-menu-right");
		}
		else{
			this_panel.toggle("50");
			this_panel.addClass("open-menu-panel");
			icon.attr("class","glyphicon glyphicon-menu-down");
			
		}
	});
	try_backend();
	loadNetFiles();
};

function try_backend(){
  try{
	$.ajax({
			method: "POST",
			url: "/maketree",
	}).done(function(result){})
	.fail(function( jqXHR, textStatus){
		if (jqXHR.status != 406) {
			cannot_connect=true;
		}
    });
   }catch(e){
		cannot_connect=true;
   }
 };
</script>
</body>
</html>
