<?php
	session_start();
	// include("/home/maarten/config.php");
	include("/home/ccbadmin/mirtargetlink_db/config.php");
	if(isset($_POST['sessionkey'])){
		$sessionkey = $_POST['sessionkey'];
		$qOrder = $_SESSION['qOrder'.$sessionkey];
		$type = $_POST['type'];
	}
	$queries = [];
	foreach($qOrder as $q){
		if(!in_array($_POST[$q.$sessionkey], $queries)){
			array_push($queries, $_POST[$q.$sessionkey]);
		}
	}
	if($type == 'miRNA'){
		if(sizeof($queries)==1){header("refresh: 0; url=result.php?miRNA=".$queries[0]);}
		else{
			$qtype = 'Target_Gene';
			$rtype = 'microRNAs';
			$rqtype = 'genes';
			$trType = "MicroRNA";
			$ninteract = 'don\'t target';
			$interact = 'are targeted by';
			$plu = 'genes that are targeted by';
		}
	}if($type == 'Target_Gene'){
		if(sizeof($queries)==1){header("refresh: 0; url=result.php?Target_Gene=".$queries[0]);}
		else{$qtype = 'miRNA';
			$rtype = 'genes';
			$trType = "Gene";
			$rqtype = 'microRNAs';
			$interact = 'target';
			$ninteract = 'are not targeted by';
			$plu = 'microRNAs that target';
		}
	}
	if(isset($_POST['evidence'.$sessionkey])){
		$evidence = $_POST['evidence'.$sessionkey];
	}
?>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>miRTargetLink Human</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
		<link rel="stylesheet" type="text/css" href="css/mystyle.css">
		<script type="text/javascript" src="vis/4.9.0/package/dist/vis.js"></script>
    	<link href="vis/4.9.0/package/dist/vis.css" rel="stylesheet" type="text/css" />
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
		<?php include_once("include_head.html") ?>
	</head>
	<body>
	<script>
	// $(document).ready(function () {
	//     // Handler for .ready() called.
	//     $('html, body').animate({
	//         scrollTop: $('#networkContainer').offset().top
	//     }, 'slow');
	// });
	</script>
		<br/>
		<div class="container-fluid">
			<div class="row">
				<!-- <div class="col-md-1"></div> -->
				<div class="col-md-12">
					<div class="panel panel-primary">
						<div class="panel-heading">
							<h1 id="miRTargetLink" style="font-size: 4em;">
				            <a href="index.php" title="Home">
				              <img src="img/logo3.png" id="logo">
				            </a>miRTargetLink Human
				          </h1>
						</div>
					</div>
				</div>
				<!-- <div class="col-md-2"></div> -->
			</div>

			
			<div class="row">
				<div class="col-md-12">
					<div class="panel panel-primary">
						<div class="container" style="width:100%;padding:0;">
							<div class="alert alert-danger" role="alert" style="text-align:center;margin:0;">
								This site is deprecated and will soon no longer be available. Please use
								<a href="https://ccb-compute.cs.uni-saarland.de/mirtargetlink2">miRTargetLink 2</a> instead.
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="row">
				<!-- <div class="col-md-1"></div> -->
				<div class="col-md-9">
					<div class="panel panel-primary">
						<div class="panel-body">
							<?php
								function mysqli_result($res,$row=0,$col=0){
									$numrows = mysqli_num_rows($res);
									if ($numrows && $row <= ($numrows-1) && $row >=0){
										mysqli_data_seek($res,$row);
										$resrow = (is_numeric($col)) ? mysqli_fetch_row($res) : mysqli_fetch_assoc($res);
										if (isset($resrow[$col])){
											return $resrow[$col];
										}
									}
									return false;
								}

								function getDistinct($x, $y){
									$z = [];
									foreach($x as $a){
										if(!in_array($a, $y)){
											array_push($z, $a);
										}
									}
									return $z;
								}

								function getConsensus($arrays){
									$check = [];
									$consensus = [];
									$interactionCount = [];
									// foreach($arrays as $key){
									foreach($arrays as $val){
										$name = explode("##", $val)[1];
										if(!in_array($name, $check)){
											array_push($check, $name);
											$interactionCount[$name] = 1;
										}else{
											$interactionCount[$name]++;
											array_push($consensus, $name);
										}
									}
									// }
									return array(array_unique($consensus), $interactionCount);
								}

								$con = mysqli_connect($server, $username, $password, $database);
								// @mysql_select_db($database) or die( "Unable to select database");

								$result = NULL;
								$strongMap = [];
								$weakMap = [];
								// $predMap = [];

								if($type == 'miRNA'){

									foreach($queries as $qval){
										$allMap[$qval] = mysqli_query($con, "SELECT DISTINCT Target_Gene, miRTarBase_ID FROM miRTarBase WHERE miRNA = \"$qval\";");//" AND Support_Type LIKE '%Weak%';");
										$weakMap[$qval] = mysqli_query($con, "SELECT DISTINCT Target_Gene, miRTarBase_ID FROM miRTarBase WHERE miRNA = \"$qval\" AND Support_Type LIKE '%Weak%';");
										$strongMap[$qval] = mysqli_query($con, "SELECT DISTINCT Target_Gene, miRTarBase_ID FROM miRTarBase WHERE miRNA = \"$qval\" AND Support_Type NOT LIKE '%Weak%';");
									}

									// $predMap[$qval] = mysqli_query($con, "SELECT DISTINCT Target_Gene FROM miRanda WHERE miRNA = \"$qval\"");

								}else{

									foreach($queries as $qval){
										$allMap[$qval] = mysqli_query($con, "SELECT DISTINCT miRNA, miRTarBase_ID FROM miRTarBase WHERE Target_Gene = \"$qval\";");// AND Support_Type LIKE '%Weak%';");
										$weakMap[$qval] = mysqli_query($con, "SELECT DISTINCT miRNA, miRTarBase_ID FROM miRTarBase WHERE Target_Gene = \"$qval\" AND Support_Type LIKE '%Weak%';");
										$strongMap[$qval] = mysqli_query($con, "SELECT DISTINCT miRNA, miRTarBase_ID FROM miRTarBase WHERE Target_Gene = \"$qval\" AND Support_Type NOT LIKE '%Weak%';");
										// $predMap[$qval] = mysqli_query($con, "SELECT DISTINCT miRNA FROM miRanda WHERE Target_Gene = \"$qval\"");
									}


								}

								// making array of results
								if($evidence == 'strong'){
									$map = $strongMap;
								}
								elseif($evidence == 'weak'){
									$map = $weakMap;
								}
								else{
									$map = 	$allMap;
								}
								$allResults = [];
								$mti = [];
								foreach ($queries as $key) {
									$res = $map[$key];
									$i = 0;
									$j = mysqli_num_rows($res);
									while($i < $j){
										$result = mysqli_result($res, $i, $qtype);
										$mti[$key."##".$result] = mysqli_result($res, $i, "miRTarBase_ID");
										array_push($allResults, $key."##".$result);
										$i++;
									}
								}
								$allResults = array_unique($allResults);
								$overlap = getConsensus($allResults);
								$consensus =        $overlap[0];
								$interactionCount = $overlap[1];

								$resultStrongArray = [];
								foreach ($queries as $key) {
									$res = $strongMap[$key];
									$i = 0;
									$j = mysqli_num_rows($res);
									while($i < $j){
										$result = mysqli_result($res, $i, $qtype);
										$mti[$result] = mysqli_result($res, $i, "miRTarBase_ID");
										array_push($resultStrongArray, $key."##".$result);
										$i++;
									}
								}
								$resultStrongArray = array_unique($resultStrongArray);

								$rEdges =           [];
								$tarId =            [];
								$resultSize =       sizeOf($consensus);
								$clickInfo =        "<ul><li>Hover over the edges to see the interaction</li><li>Double click to generate interaction landscape<br/>(opens in new tab)</li>";
								$weak =             "<li>Weaker experimental evidence</li>";

								function getCount($arr, $b){
									$count = [];
									foreach($arr as $a){
										$info = explode("##", $a);
										if(in_array($info[1], $b)){
											if(!array_key_exists($info[0], $count)){
												$count[$info[0]] = 1;
											}else{
												$count[$info[0]]++;
											}
										}
									}
									return $count;
								}

								function getOccur($array, $val){
									$count = 0;
									foreach ($array as $item) {
									  if ($item == $val) {
									    $count++;
									  }
									}
									// echo $item." ".$count."<br/>";
									return $count;
								}

								$edgeCount =     getCount($allResults, $consensus);
								$rNodes =        [];
								$qNodes =        [];
								$qId =           [];
								for($i = 0; $i < sizeof($queries); $i++){
									$qId[$queries[$i]] = $i;
								}
								$noEdges =       [];
								$mass =          150;
								$fac =           3.1;
								if($resultSize<50){$fac = 2.5;}
								$mass = $fac*$resultSize;
								$fix =           false;
								$qNodeIds =      [];

								foreach($queries as $qval){
									$edges = $edgeCount[$qval];
									if($edges == 0){
										array_push($noEdges, $qId[$qval]);
									}
									array_push($qNodeIds, $qId[$qval]);
									array_push($rNodes, ["id" => $qId[$qval], "selectable" => false, "label" => $qval, "color" => "#6E3E0B", "font" =>  "16px arial white", "shape" => "box",
									"title" => "<strong>".$qval."</strong><br/>".$edges." shared interactions".$clickInfo, "fixed" => $fix, "mass" => $mass]);
								}

								$qNodeIds = getDistinct($qNodeIds, $noEdges);

								$n = sizeof($rNodes);
								$m = sizeof($rNodes);

								foreach($consensus as $tar){
									$tarId[$tar] = $n;
									$n++;
								}

								$done =          [];
								$download =      [];
								$weakEdges =     [];
								$strongTargets = [];
								$weakTargets =   [];
								$strongNames =   [];

								for ($i = 0; $i < sizeOf($allResults); $i++) {
									$kv = explode('##', $allResults[$i]);
									$base = $kv[0];
									$target = $kv[1];
									if(in_array($target, $consensus)){
										$o = $tarId[$target];
										$l = 10*$fac;
										$s = 0.5;
										$edges = $interactionCount[$target];
										if($edges > 2){
											// $l = $l*3;
											$s = 10;
											$nColour = "#FF8000";
											$tColour = "black";
											$eColour = "#FF4000";
										}else{
											$nColour = "#0431B4";
											$tColour = "white";
											$eColour = "#0431B4";
										}

										if(!in_array($o, $done)){
											array_push($rNodes, ["id" => $o, "label" => $target, "color" => $nColour, "mass" => 1, "font" => "16px arial ".$tColour,
											"shape" => "box", "title" => "<strong>".$target."</strong><br/>validated interaction with ".$edges." ".$rtype."<br/>".$clickInfo]);
											array_push($done, $o);
											array_push($allNodeIds,$o);
										}
										$eTitle = $target." - ".$base;
										if(!in_array($base."##".$target, $resultStrongArray)){
											$eTitle = $eTitle." <br/><strong>Backed up solely by weak evidence</strong>";
											$edge = ["id" => $base.$target,"title" => $eTitle, "from" => $o, "to" => $qId[$base], "color" => $eColour, "width" => 1.1];
											array_push($weakTargets, $o);
											array_push($weakEdges, $base.$target);
											array_push($download, $base.",".$target.","."weak");
										}
										else{
											if($evidence == 'weak'){$eTitle = $eTitle." <br/><strong>Backed up by weak and strong evidence</strong>";}
											else{$eTitle = $eTitle." <br/><strong>Backed up by strong evidence</strong>";}
											$edge = ["title" => $eTitle, "from" => $o, "to" => $qId[$base], "color" => "green", "width" => 1.3];
											array_push($strongTargets, $o);
											array_push($download, $base.",".$target.","."strong");
											array_push($strongNames, $target);
										}
										array_push($rEdges, $edge);
									}
								}

								function array_count_values_of($value, $array) {
								    $counts = array_count_values($array);
								    return $counts[$value];
								}

								$lonelyStrong = [];
								foreach($strongTargets as $st){
									if(array_count_values_of($st, $strongTargets) < 2){
										array_push($lonelyStrong, $st);
									}
								}

								$weakTargets = array_unique($weakTargets);
								$lonelyStrong = array_unique($lonelyStrong);
								$weakTargets = getDistinct($weakTargets, $lonelyStrong);
								// $lonelyStrong = getDistinct($lonelyStrong, $weakTargets);

								function sortNodes($nodes){
									$ret = [];
									for($i=0; $i<sizeof($nodes);$i++){
										foreach($nodes as $node){
											if($node["id"] == $i){
												array_push($ret, $node);
											}
										}
									}
									return $ret;
								}

								$rNodes = sortNodes($rNodes);

								if($resultSize > 0){

								if($evidence == 'both'){$evidence = 'Strong + Weak';}
							?>
							 <h2 class="page-header" id="start">miRTargetLink found <?php echo $resultSize; ?> <?php echo $plu; ?> two or more of the selected <?php echo $rtype; ?> in the '<?php echo $evidence; ?>' category</h2>
							 <ul>
							 	<?php
							 	$link = "http://www.genecards.org/cgi-bin/carddisp.pl?gene=";
							 	$lt = "GeneCards";
							 	if($type == 'miRNA'){
							 		$link = "http://www.mirbase.org/cgi-bin/mirna_entry.pl?acc=";
							 		$lt = "miRBase";
							 	}
							 	foreach($queries as $query){
							 		$c = 0;
							 		if($edgeCount[$query]>0){$c=$edgeCount[$query];}
							 		?>
							 		<li>
							 		<a title="open interaction landscape for <?php echo $query; ?> in a new tab" target="_blank" href="network.php?type=<?php echo $type; ?>&qval=<?php echo $query; ?>"><span class="glyphicon glyphicon-expand"></span></a>
							 		<a title="Open <?php echo $lt; ?> page for <?php echo $query; ?> in a new tab" href="<?php echo $link.$query; ?>" target="_blank"><?php echo $query; ?></a>:
							 		<strong><?php echo $c; ?></strong> shared interactions
									<?php if($c == 0){echo "<strong> (Excluded from network)</strong>";}?>
							 		</li>
							 		<?php
							 	}
							 	?>
							 </ul>
							<div class="panel panel-primary">
								<div class="panel-heading" style="text-align:center;">
									<h4>
									<a data-toggle="collapse" href="#collapseTips" title="Click to expand" style="color:white;">
									<span class="glyphicon glyphicon-th-list"></span> Network tips</a>
									</h4>
								</div>
								<div id="collapseTips" class="panel-collapse collapse">
									<div class="panel panel-body">
										<ul id="zzgraphTips">
											<li>Hover over any node or edge to see more info about the interaction.</li>
											<li>Double click on a gene or microRNA to open its interaction landscape in a new tab.</li>
											<li>Move nodes around by clicking and dragging, select multiple nodes to move a group.</li>
											<li>Right click -> 'save image as...' to download network as png image.</li>
											<li>Click on microRNAs or genes in the table below to open a <a href="http://www.genecards.org/" target="_blank">genecards</a> or <a href="http://www.mirbase.org/" target="_blank">miRBase</a> link in a new tab.</li>
										</ul>
									</div>
								</div>
							</div>
							<div id="networkContainer">
								<div id="networkFrame"></div>
								<div id="loadingBar">
							        <div class="outerBorder">
							            <div id="text">
							            Generating network please wait... 0%
							            </div>
							            <div id="border">
							                <div id="bar"></div>
							            </div>
							        </div>
						    	</div>
							</div>

							<script type="text/javascript">
								var network =    null;
								var weakTargets =    <?php echo json_encode($weakTargets);?>;
								var lonelyStrong =    <?php echo json_encode($lonelyStrong);?>;
								var rNodes =     <?php echo json_encode($rNodes);?>;
								var rEdges =     <?php echo json_encode($rEdges);?>;
								var qedge =  new vis.DataSet(rEdges);
								var qnode = new vis.DataSet(rNodes);
								var vNodes =     new vis.DataSet(rNodes);
								var vEdges =     new vis.DataSet(rEdges);
								var weakEdges =     <?php echo json_encode($weakEdges);?>;
								var type =       <?php echo json_encode($type);?>;
								var emptyNodes = <?php echo json_encode($noEdges);?>;
								var qNodeIds = null;
								var rs = null;
								var sc = null;
								var qn = null;
								var data = null;
								var first = true;
								draw(vEdges, vNodes);

								function draw(e, n){
									qNodeIds = <?php echo json_encode($qNodeIds);?>;
									qn =           <?php echo $m;?>;
									rs =           <?php echo $resultSize;?>;
									var hw =           2.5;
									var ts =           2;
									var it =           200;
									if(qn < hw){hw = qn;}
									if(qn > 2){it = 400;}
									sc = 0.0055;
									if(rs > 100){sc = 0.003}
									var container =    document.getElementById('networkFrame');
									data =         {nodes: n, edges: e};
									var options =      {
										interaction:{
											// hideEdgesOnDrag: true,
											dragNodes: true,
											hover: true,
											multiselect: true,
											navigationButtons: true,
											tooltipDelay: 100
										},
										nodes:{
											shadow: false
										},

										edges:{
											physics:true,
											smooth: {
										      type: "continuous",
										      forceDirection: "none",
										      roundness: 0
										    },

											hoverWidth:hw,
											selectionWidth:hw+1,
	    									width: 0
										},
										physics:{
											solver:'barnesHut',
											timestep: ts,
											stabilization: {
												enabled: true,
												iterations: it*qn,
												fit: true
											},
											barnesHut:{
												springConstant: sc
											}
										},
										layout:{
											improvedLayout: true
										}
									};

									network = new vis.Network(container, data, options);
									network.selectNodes(emptyNodes);
									network.deleteSelected();

									network.on("stabilizationProgress", function(params) {
						                var maxWidth = 496;
						                var minWidth = 20;
						                var widthFactor = params.iterations/params.total;
						                var width = Math.max(minWidth,maxWidth * widthFactor);

						                document.getElementById('bar').style.width = width + 'px';
						                document.getElementById('text').innerHTML = 'Generating network please wait... '+Math.round(widthFactor*100) + '%';
						            });
						            network.once("stabilizationIterationsDone", function() {
						                document.getElementById('text').innerHTML = '100%';
						                document.getElementById('bar').style.width = '496px';
						                document.getElementById('loadingBar').style.opacity = 0;
						                // really clean the dom element
						                setTimeout(function () {document.getElementById('loadingBar').style.display = 'none';}, 500);
						                var postRenderOptions = {
											physics:{enabled:false}
										};
										network.setOptions(postRenderOptions);
										// network.storePositions();
										// if(first == true){
										// 	bEdges = edges;
										// 	bNodes = nodes;
										// 	first = false;
										// }
						            });
									function openNetworkInTab(name, type) {
										window.open("network.php?type="+type+"&qval="+name);
									}
									network.on( 'doubleClick',
										function(properties) {
											if (type == 'Target_Gene'){
												if(properties.nodes < qn){
													window.open("network.php?type=Target_Gene&qval="+rNodes[properties.nodes].label);
												}else{
													window.open("network.php?type=miRNA&qval="+rNodes[properties.nodes].label);
												}
											}if (type == 'miRNA'){
												if(properties.nodes < qn){
													window.open("network.php?type=miRNA&qval="+rNodes[properties.nodes].label);
												}else{
													window.open("network.php?type=Target_Gene&qval="+rNodes[properties.nodes].label);
												}
											}
										}
									);
								}


								// document.getElementById('loading').style.display='none';
								// document.getElementById('networkFrame').style.visibility='visible';

								$(document).ready(function(){
									$('[data-toggle="tooltip"]').tooltip();
								});
								$('[rel=tooltip]').tooltip({container: 'body'});
							</script>

							<h3>Edit network:
							<button onclick="filter('weakEdges'); this.className='btn btn-default disabled';" class="btn btn-danger" data-toggle="tooltip" title="Remove edges that represent interactions in the weaker evidence category (edges that are not green)" data-container="body" id="weakEdges"><span class="glyphicon glyphicon-remove"></span> <strong>Weak edges</strong> </button>
							<button onclick="this.className='btn btn-default disabled'; filter('weakNodes'); " class="btn btn-danger" data-toggle="tooltip" title="Remove nodes with one or less interactions in the strong evidence category" data-container="body" id="weakNodes"><span class="glyphicon glyphicon-remove"></span> <strong>Weak nodes</strong> </button>
							<!-- <button onclick="filter('lonely');" class="btn btn-danger" data-toggle="tooltip" title="Remove nodes without connections" data-container="body" id="lonely"><strong>Lonely nodes</strong></button> -->
							<button onclick="filter('rescale');" class="btn btn-primary" data-toggle="tooltip" title="Recalculate edge-lengths after removing nodes and edges" data-container="body"><span class="glyphicon glyphicon-resize-full"></span> <strong>Rescale</strong> </button>
							<button onclick="filter('stabilize');" class="btn btn-primary" data-toggle="tooltip" title="Recalculate the network layout" data-container="body"><span class="glyphicon glyphicon-cog"></span> <strong>Restabilize</strong> </button>
							<button id="updCol" onclick="filter('updCol');" class="btn btn-default disabled" data-toggle="tooltip" title="Refresh node colour after removing edges" data-container="body"><span class="glyphicon glyphicon-refresh"></span> <strong>Refresh nodes</strong> </button>
							<button id ="reset" onclick="filter('reset');" class="btn btn-default disabled" data-toggle="tooltip" title="Regenerate the original network" data-container="body"><span class="glyphicon glyphicon-refresh"></span> <strong>Restore network</strong> </button>
							</h3>
							<h3>Generate subnetwork for selection:
							<button class="btn btn-primary" onclick="getSelected('network', 'multigene', 'sel')" data-toggle="tooltip" title="Select one or more genes in the network by crtl+clicking, or long clicking them" data-container="body"><span class="glyphicon glyphicon-cog"></span> <strong>Genes</strong></button>
							<button class="btn btn-primary" onclick="getSelected('network','multimir', 'sel')" data-toggle="tooltip" title="Select one or more microRNAs in the network by crtl+clicking, or long clicking them" data-container="body"><span class="glyphicon glyphicon-cog"></span> <strong>MicroRNAs</strong> </button>
							</h3>
							<!-- <p id="demo"></p> -->
							<script type="text/javascript">

							var smooth = false;
							var physics = false;
							var edgeRemoved = false;
							var current = updateCurrent();

							function filter(del){
								var lon = [];
								if(del=='weakEdges'){
									document.getElementById("updCol").className = "btn btn-warning";
									document.getElementById("reset").className = "btn btn-warning";
									network.selectEdges(weakEdges);
									network.deleteSelected();
									edgeRemoved = true;
									filter('lonely');
								}
								if(del=='weakNodes'){
									document.getElementById("weakEdges").className = "btn btn-default disabled";
									document.getElementById("updCol").className = "btn btn-warning";
									document.getElementById("reset").className = "btn btn-warning";
									// network.selectNodes(weakTargets);
									// network.deleteSelected();
									if(edgeRemoved == false){filter('weakEdges');}
									network.selectNodes(lonelyStrong);
									network.deleteSelected();
									filter('lonely');
								}
								if(del=='stabilize'){
									document.getElementById("reset").className = "btn btn-warning";
									var resSize = data['nodes'].length;
									var qno = qNodeIds.length;
									var stabilizeOptions = {
										physics:{enabled: false,
											solver:'barnesHut',
											barnesHut:{
												springConstant: sc,
												springLength:resSize*qn
											}
										}
									};
									network.setOptions(stabilizeOptions);
									network.stabilize(500);

								}
								if(del=='updCol'){
									var nodes = data['nodes'].get();
									for(i=0;i<nodes.length;i++){
										if(qNodeIds.indexOf(nodes[i].id) > -1){var x=0;}
										else{
											if(network.getConnectedEdges(nodes[i].id).length < 3){
												data['nodes'].update({id: nodes[i].id ,color: "#0431B4", font: "16px arial white"});
											}
										}
									}
								}
								if(del=='lonely'){
									var nodes = data['nodes'].get();
									for(i=0;i<nodes.length;i++){
										if(network.getConnectedEdges(nodes[i].id).length < 1){
											lon.push(nodes[i].id);
											if(qNodeIds.indexOf(nodes[i].id) > -1){
												qNodeIds.splice(qNodeIds.indexOf(nodes[i].id),1);
											}
										}
									}
									network.selectNodes(lon);
									network.deleteSelected();
								}
								if(del=='rescale'){
									document.getElementById("reset").className = "btn btn-warning";
									var mass = 150;
									var fac = 3.1;
									var resSize = data['nodes'].length;
									if(resSize < 50){fac = 2.5;}
									for(i=0;i<qNodeIds.length;i++){
										var m = fac*resSize;
										data['nodes'].update({id: qNodeIds[i], mass: m});
									}
									filter('stabilize');
								}
								if(del=='physics'){
									var stabilizeOptions = {
										physics:{
											enabled: physics
										}
									};
									network.setOptions(stabilizeOptions);
									physics = !physics;

								}
								if(del=='smooth'){
									var stabilizeOptions = {
										edges:{
											smooth: smooth
										}
									};
									network.setOptions(stabilizeOptions);
									smooth = !smooth;
									// filter('stabilize');
								}
								if(del=='reset'){
									location.reload();
									// var maxWidth = 496;
					    //             var minWidth = 20;
					    //             var widthFactor = params.iterations/params.total;
					    //             var width = Math.max(minWidth,maxWidth * widthFactor);
									// document.getElementById('bar').style.width = width + 'px';
						   //          document.getElementById('text').innerHTML = 'Generating network please wait... '+Math.round(widthFactor*100) + '%';
						   //          document.getElementById('loadingBar').style.opacity = 1;
									// draw(qedge,qnode);

								}
							 	current = updateCurrent();
							}

							function updateCurrent(){
								current = [];
								var nodes = data['nodes'].get();
								for(i=0;i<nodes.length;i++){
									var label = nodes[i].label;
									if(type == 'miRNA'){
										if(label.substring(0,4) != 'hsa-'){current.push(label);}
									}else{
										if(label.substring(0,4) == 'hsa-'){current.push(label);}
									}
								}
								return current;
							}

							</script>
							<h2 class="page-header"></h2>
							<?php
							$_SESSION['type'.$sessionkey] = $type;
							$_SESSION['qval'.$sessionkey] = "the selected set of ".$rtype;
							$_SESSION['multi'.$sessionkey] = $consensus;
							$_SESSION['multiDownload'.$sessionkey] = $download;
							session_write_close();
							?>
							<div class="panel panel-default">
							<div class="panel-heading">
								<h3 >
								<a href="download.php?session=<?php echo $sessionkey; ?>" target="_blank" style="color:#347AB8;">
									<span class="glyphicon glyphicon-download"></span> <strong>Download interaction data</strong>
								</a>
								</h3>
							</div>
							<?php
							$tablecss = "height:500px;overflow-y:auto;";
							if(sizeof($rEdges) < 13){
								$tablecss = "height:auto;";
							}
							?>

							<div class="panel panel-body" style=<?php echo $tablecss; ?>>
								<table class="table table-striped" >
									<?php
									$tarLink="http://www.genecards.org/cgi-bin/carddisp.pl?gene=";
									$tarTit="\"Go to genecards (opens in new tab)\"";
									$subjLink="http://www.mirbase.org/cgi-bin/mirna_entry.pl?acc=";
									$subjTit="\"Go to miRBase (opens in new tab)\"";
									if($type == 'Target_Gene'){
										$subjLink="http://www.genecards.org/cgi-bin/carddisp.pl?gene=";
										$tarTit="\"Go to miRBase (opens in new tab)\"";
										$tarLink="http://www.mirbase.org/cgi-bin/mirna_entry.pl?acc=";
										$subjTit="\"Go to genecards (opens in new tab)\"";
									}
									$target = 'MicroRNA';
									if($type == 'miRNA'){
										$target = 'Gene';
									}
									?>
									<thead>
										<tr>
											<th><?php echo $trType; ?></th>
											<th><?php echo $target; ?></th>
											<th>Evidence category</th>
											<th>miRTarBase ID</th>
										</tr>
									</thead>
									<tbody class="dikketabel">
									<?php
									if(sizeof($download) > 0){
									foreach($download as $s){
										$sEx = explode(",", $s);
										if($sEx[2] == 'strong'){
											$rowtype = 'Strong';
											$ttip = "e.g. Reporter assay, Western blot, qPCR";
										}if($sEx[2] == 'weak'){
											$rowtype = 'Weak';
											$ttip = "e.g. Microarray, NGS, pSILAC";
										}
										?>
										<tr class='<?php echo $rowtype; ?>'>
											<td>
												<a title="open interaction landscape for <?php echo $sEx[0]; ?> in a new tab" target="_blank" href="network.php?type=<?php echo $type; ?>&qval=<?php echo $sEx[0]; ?>"><span class="glyphicon glyphicon-expand"></span></a>
												<a href=<?php echo $subjLink.$sEx[0]; ?> title=<?php echo $subjTit; ?> target="_blank"><?php echo $sEx[0]; ?></a>
											</td>
											<td>
												<a title="open interaction landscape for <?php echo $sEx[1]; ?> in a new tab" target="_blank" href="network.php?type=<?php echo $qtype; ?>&qval=<?php echo $sEx[1]; ?>"><span class="glyphicon glyphicon-expand"></span></a>
												<a href=<?php echo $tarLink.$sEx[1]; ?> title=<?php echo $tarTit; ?> target="_blank"><?php echo $sEx[1]; ?></a>
											</td>

											<td title="<?php echo $ttip;?>" style="cursor: help;"><span rel="tooltip"><?php echo $rowtype; ?></span></td>
											<td><a target="_blank" href="http://mirtarbase.mbc.nctu.edu.tw/php/detail.php?mirtid=<?php echo $mti[$sEx[0].'##'.$sEx[1]]; ?>" title="open miRTarBase page for [<?php echo $sEx[0].' : '.$sEx[1]; ?>]"><?php echo $mti[$sEx[0].'##'.$sEx[1]]; ?></a></td>
										</tr>
										<?php
									}
									}
									?>
									</tbody>
								</table>
							</div>
						</div>
						<h3>Table filter:
						<button class="btn btn-info" id="showStrongButton">Strong only</button>
						<button class="btn btn-info" id="showWeakButton">Weak only</button>
						<button class="btn btn-info" id="showAll">Show all</button>
						</h3>
						<script>
							var rows = $('tbody.dikketabel tr');
							$('#showStrongButton').click(function() {
							    var strong = rows.filter('.Strong').show();
							    rows.not( strong ).hide();
							});

							$('#showWeakButton').click(function() {
							    var weak = rows.filter('.Weak').show();
							    rows.not( weak ).hide();
							});

							$('#showAll').click(function() {
							    rows.show();
							});
						</script>

							<?php
							}else{
								if($evidence == 'both'){$evidence = 'Strong + Weak';}
								if($type == 'miRNA'){
									$naam = 'multimir';
								}else{
									$naam = 'multigene';
								}
								$val = "";
								foreach ($queries as $key) {
									$val = $val.$key.",";
								}
								?>
								<h2 class="page-header">No shared interactions found in the <?php echo $evidence;?> evidence category.</h2>
								<div class="col-md-12">
									<div class="panel panel-default">
										<div class="panel-heading">
											<form action="multiresult.php" method="POST">
											<input type='hidden' name='<?php echo $naam; ?>' value='<?php echo $val; ?>'></input>
											<button style="width:100%;" class="btn btn-default" type="submit"><strong><span class="glyphicon glyphicon-arrow-left"></span> Back to results</strong></button>
											</form><br/><br/>
											<a href="index.php" title="Home"><span class="glyphicon glyphicon-home"></span> back to main page</a>
										</div>
									</div>
								</div>
								<?php
							}
							?>
						</div>
					</div>
				</div>
				<div class="col-md-3">
					<div class="panel-group" id="fixed">
		                <div class="panel panel-primary">
		                  <div class="panel-head">
		                    <a href="https://www.ccb.uni-saarland.de/" title="CCB" target="_blank">
		                      <center><img src="img/ccb.png" id="CCB"></center>
		                    </a>
		                  </div>
		                </div>
						<div class="panel panel-primary">
							<div class="panel-heading">
								<h4>
								<span class="glyphicon glyphicon-search"></span> <a data-toggle="collapse" data-parent="#fixed" href="#collapse1" title="Click to expand" style="color:white;">Search by microRNA</a>
								</h4>
							</div>
							<div id="collapse1" class="panel-collapse collapse">
								<div class="panel-body">
									<form class="form-inline" role="form" method="post" action="result.php">
	                          			<p><strong>Interaction landscape for a single microRNA:</strong></p>
										<div class="form-group">
											<input class="form-control" name="miRNA" placeholder="Example: hsa-let">
										</div>
										<button type="submit" class="btn btn-info">
											<span class="glyphicon glyphicon-search"></span> <strong>Search</strong>
										</button>
									</form>
									<br/>
									<form class="form-inline" method="POST" action="multiresult.php" id="multimirform">
										<p><strong>Target-gene overlap between multiple microRNAs:</strong></p>
										<div class="form-group">
											<textarea placeholder="Example: let-7,hsa-miR-30,..." name="multimir" form="multimirform"></textarea>
										</div>
										<button type="submit" class="btn btn-info"><span class="glyphicon glyphicon-search"></span> <strong>Search</strong></button>
									</form>
									<p style="color:#013ADF;">To view an example, leave fields empty and click search</p>

								</div>
							</div>
						</div>
						<div class="panel panel-primary">
							<div class="panel-heading">
								<h4>
									<span class="glyphicon glyphicon-search"></span> <a data-toggle="collapse" data-parent="#fixed" href="#collapse2" title="Click to expand" style="color:white;">Search by gene symbol</a>
								</h4>
							</div>
							<div id="collapse2" class="panel-collapse collapse">
								<div class="panel-body">
									<form class="form-inline" role="form" method="post" action="result.php">
	                          			<p><strong>Interaction landscape for a single gene symbol:</strong></p>
										<div class="form-group">
											<input class="form-control" name="Target_Gene" placeholder="Example: NOTCH">
										</div>
										<button type="submit" class="btn btn-info">
											<span class="glyphicon glyphicon-search"></span> <strong>Search</strong>
										</button>
									</form>
									<br/>
									<form class="form-inline" method="POST" action="multiresult.php" id="multigeneform">
										<p><strong>MicroRNA interaction overlap between multiple genes:</strong></p>
										<div class="form-group">
											<textarea placeholder="Example: NOTCH,DICER,..." name="multigene" from="multigeneform"></textarea>
										</div>
										<button type="submit" class="btn btn-info"><span class="glyphicon glyphicon-search"></span> <strong>Search</strong></button>
									</form>
									<p style="color:#013ADF;">To view an example, leave fields empty and click search</p>
								</div>
							</div>
						</div>
						<div class="panel panel-primary">
							<div class="panel-heading">
								<h4>
									<span class="glyphicon glyphicon-play-circle"></span> <a data-toggle="collapse" data-parent="#fixed" href="#collapse4" title="Click to expand" style="color:white;">Over-representation analysis</a>
								</h4>
							</div>
							<div id="collapse4" class="panel-collapse collapse">
								<div class="panel-body">
									<p>Perform Over-representation analysis with <a href="https://genetrail2.bioinf.uni-sb.de/start.html" target="_blank">GeneTrail2</a>,
									a tool for statistical analysis of molecular signatures that was developed in the<a href="https://www.bioinf.uni-sb.de/home" target="_blank"> Chair for Bioinformatics</a>  at the University of Saarland.
									</p>
									<h4>Perform Over-representation analysis for:<h4/>
									<form action="waiting.php" method="POST" target="_blank">
										<button style="width:100%;" type="submit" class="btn btn-info" name="multi" data-toggle="tooltip" title="Perform ORA on all <?php echo $rqtype?> in the original network" value=<?php echo $sessionkey; ?> data-container="body"><strong>All shared <?php echo $rqtype; ?></strong></button>
									</form>
									<button style="width:100%;" class="btn btn-info" onclick="getCurrent()" data-toggle="tooltip" title="Perform ORA on the <?php echo $rqtype?> that are currently present in the network (deleted nodes are excluded)" data-container="body"><strong>Current <?php echo $rqtype; ?></strong></button>
									<button style="width:100%;" class="btn btn-info" onclick="getSelected('cluster')" data-toggle="tooltip" title="Perform ORA on selected <?php echo $rqtype?>. Select one or more <?php echo $rqtype?> in the network by crtl+clicking, or long clicking them" data-container="body"><strong>Selected <?php echo $rqtype; ?></strong></button>

									<script type="text/javascript">
									function getCurrent(){
										if(current.length > 0){
											var names = "";
											for(i=0;i<current.length;i++){
												names = names+current[i]+'#';
											}
											var form = document.createElement("form");
								            form.setAttribute("method", "POST");
								            form.setAttribute("action", "waiting.php");
								            form.setAttribute("target", "_blank");
								            var selectedNodes = document.createElement('input');
								            selectedNodes.type = 'hidden';
								            selectedNodes.name = 'selNodes';
								            selectedNodes.value = names+'#'+"<?php echo $sessionkey;?>";
								            form.appendChild(selectedNodes);
								            document.body.appendChild(form);
								    		form.submit();
										}

									}

									function getSelected(what, who, reqType) {
									    if(what == 'cluster'){
									    	var sel = network.getSelectedNodes();
										    var type = '<?php echo $type; ?>';
									        var names = "";

									        for(i = 0; i < sel.length; i++){
									        	var name = rNodes[sel[i]].label;
									        	if((type == "Target_Gene" && name.substring(0,3) == 'hsa') || (type == 'miRNA' && name.substring(0,3) != 'hsa')){
									        		names = names+name+'#';
									        	}

									        }
									        // document.getElementById("demo").innerHTML = selectable.length;
								        	if(names != ""){
									    		var form = document.createElement("form");
									            form.setAttribute("method", "POST");
									            form.setAttribute("action", "waiting.php");
									            form.setAttribute("target", "_blank");
									            var selectedNodes = document.createElement('input');
									            selectedNodes.type = 'hidden';
									            selectedNodes.name = 'selNodes';
									            selectedNodes.value = names+'#'+"<?php echo $sessionkey;?>";
									            form.appendChild(selectedNodes);
									            document.body.appendChild(form);
									    		form.submit();
									    	}
									    }else{
									    	var sel = network.getSelectedNodes();
										    var type = '<?php echo $type; ?>';
									        var names = "";
									        // var varname = who;
									        // if(type =='miRNA'){varname = 'multigene';}
									        for(i = 0; i < sel.length; i++){
									        	var name = rNodes[sel[i]].label;
									        	if((who == 'multimir' && name.substring(0,3) == 'hsa') || (who == 'multigene' && name.substring(0,3) != 'hsa')){
									        		names = names+name+',';
									        	}

									        }
									        // document.getElementById("demo").innerHTML = selectable.length;
								        	if(names != ""){
									    		var form = document.createElement("form");
									            form.setAttribute("method", "POST");
									            form.setAttribute("action", "multiresult.php");
									            form.setAttribute("target", "_blank");
									            var selectedNodes = document.createElement('input');
									            selectedNodes.type = 'hidden';
									            selectedNodes.name = who;
									            selectedNodes.value = names;
									            form.appendChild(selectedNodes);
									            document.body.appendChild(form);
									    		form.submit();
									    	}
									    }
									}

									</script>
								</div>
							</div>
						</div>
						<div class="panel panel-primary">
							<div class="panel-heading">
								<h4>
									<span class="glyphicon glyphicon-info-sign"></span> <a data-toggle="collapse" data-parent="#fixed" href="#collapse3" title="Click to expand" style="color:white;">Network information</a>
								</h4>
							</div>
							<div id="collapse3" class="panel-collapse collapse">
								<div class="panel-body">
									<p>The colour of the <?php echo $rqtype?> indicates the amount of interactions they are involved in. <mark id="green2">Orange</mark> <?php echo $rqtype?>
									 <?php echo $interact?> three or more <?php echo $rtype?>, <?php echo $rqtype?> that <?php echo $interact?> two
									<?php echo $rtype?> are coloured <mark id="blue2">Blue</mark>. If there are <?php echo $rtype?> that <?php echo $ninteract?>
									any <?php echo $rqtype?> in the overlapping interaction set they are excluded from the graph. <strong>Note that interactions shown here are all experimentally validated</strong>.
									Interactions with strong experimental evidence are depicted by <mark id="green">green</mark> edges, interactions with weaker evidence are depicted by <mark id="blue2">blue</mark> or <mark id="green2">orange</mark> edges.
									</p>
								</div>
							</div>
						</div>
                <div class="panel panel-primary">
                  <div class="panel-heading">
                    <a href="manual.php" class="btn btn-default" target="_blank" id="download"><span class="glyphicon glyphicon-info-sign"></span> <strong>View the manual</strong> (opens in a new tab)</a>
                  </div>
                </div>
					</div>
				</div>
				<!-- <div class="col-md-1"></div> -->
			</div>
		</div>
	</body>
</html>
