<?php
session_start();
include("config.php");
//include("loginCheckPoint.php");
include("sem/queries.php");
include_once("bsw/utils.php");

$concept = $_REQUEST['concept'];
$searchTitle = $_REQUEST['title'];

if (strlen($concept) > 0)
	$conceptQName = label2QName($concept);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; Charset=UTF-8"  /> 
<title>Name Matcher - Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="js/jquery-ui/development-bundle/themes/base/jquery.ui.all.css">
<link rel="stylesheet" href="css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
<script src="js/jquery/jquery.js" type="text/javascript"></script>
<script src="js/jquery/jquery-ui.custom.js" type="text/javascript"></script>
<script src="js/jquery/jquery.cookie.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/jquery.ui.autocomplete.css">
<script src="js/jquery/jquery.js" type="text/javascript"></script>
<script src="js/jquery/jquery-ui.custom.js" type="text/javascript"></script>
<script src="js/jquery/jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery-ui/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui/js/jquery-ui-1.8.17.custom.min.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.autocomplete.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.effects.core.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.effects.blind.js"></script>

<!-- CuFon: Enables smooth pretty custom font rendering. 100% SEO friendly. To disable, remove this section -->
<!--<script type="text/javascript" src="js/cufon-yui.js"></script>
<script type="text/javascript" src="js/arial.js"></script>
<script type="text/javascript" src="js/cuf_run.js"></script>-->
<!-- CuFon ends -->
<script type="text/javascript">
var ajax_load = "<p align=center><img src='images/loader.gif' alt='loading...' /></p>";

	<?php 
		//$conceptQName = label2QName($concept);
		if (strlen($conceptQName) > 0)
			echo "var concept='<" . urlencode($conceptQName) . ">';"; 
		else
			echo "var concept='';";
	?>

  $(function(){
  		$("#typesPnl").hide();
        $("#newType").autocomplete({  
  
            //define callback to format results  
            source: function(req, add){  
  
                //pass request to server  
                $.getJSON("autoCompEng.php?type=concept&limit=50&callback=?", req, function(data) {  
  
                    //create array for response objects  
                    var suggestions = [];  
  
                    //process response  
                    $.each(data, function(i, val){  
                    	suggestions.push(val.label);  
                	});  
  
                //pass array to callback  
                add(suggestions);  
            });  
        },  
         //define select handler  
        select: function(e, ui) {  
            //alert(ui.item.value);
         },  
  
            //define select handler  
            change: function() {  
  
            }  
        });
  });
	 
function search(page, resultsNum, textorfile){
	var wl = <?php 
		if (empty($_REQUEST["wlSelectedList"]))
			echo "\"\";";
		else 
			echo "\"" .$_REQUEST["wlSelectedList"] . "\";";
		;?>	
	var wlSelectedList;
	if (wl)
		wlSelectedList = wl;
	else
		wlSelectedList = document.getElementById("wl").value;	
	//if (wlSelectedList)
	{
		var searchtext = textorfile? document.getElementById("searchtext").value : "";
		var sourcefile = textorfile? "" : document.getElementById("filename").value;
		if (searchtext.length == 0 && sourcefile.length == 0){
			$("#searchtext").css({'background-color' : 'pink'});
			return;
		}else{
			$("#searchtext").css({'background-color' : 'white'});
		}
		var ontology = true;
		var lexicon = false;
		var casesense = false;
		var wholeword = false;
		var concept = "";
		var limit = "unlimited";
		$("#results").html(ajax_load).load("searchEng.php?searchtext=" + encodeURIComponent(searchtext) +
													"&sourcefile=" + encodeURIComponent(sourcefile) +
													"&ontology=" + ontology +
													"&concept=" + "" +
													"&lexicon=" + lexicon +
													"&casesense=" + casesense +
													"&wholeword=" + wholeword +
													"&limit=" + limit + 
													"&page=" + page +
													"&rperpage=20" +
													"&results=" + resultsNum, 
													"&wlSelected=" + wlSelectedList,																																				
										function(ret){

											console.log(ret);
											
										});
	}
	/*
	else	
		alert("You need to upload Targetlist");
	*/
};

function analyzefile(filename){			
	$("#results").html(ajax_load).load("searchEng.php?analyzeFile=true" + 
									"&sourcefile=" + encodeURIComponent(filename),																																				
	function(){});
};

function analyzeName(name,resultIndex, inputIndex){	
	//name = name.replace("%","'");
	toggle(resultIndex);	
	$("#div"+resultIndex).html(ajax_load).load("searchEng.php?searchtext=" + encodeURIComponent(name) +												
												"&analyze=yes", 
										function() {FilterNAByConfidence(resultIndex, inputIndex)});
};

//This function is a hack for displaying only NAs with maximum confidence
//but it is disable by default
function FilterNAByConfidence(resultIndex, inputIndex){
	//comment out this line for activating the function
	return;

	//this function should operate only on the results, so for the input NAs (inputIndex=-1) - exit
	if (inputIndex < 0)
		return;

	//iterate NA table of input name
	//for each NA create NA holder - which includes HTML rows, rows count, and NA key-value pairs
	var NAsHolder = [];
	var objInd = -1;
	var count = 0;
	var prevRow = null;
	var iRows = $("tr", "#div"+inputIndex);
	iRows.each(function(index){
		//first TD (cell) is the key (GN/FN/...) and the second is the value
		var td1 = $($(this).find("td")[0]);
		var td1Text = td1.text();
		var td2 = $($(this).find("td")[1]);
		var td2Text = td2.text();
		//if key is NA title (i.e. start of NA)
		if (td1Text.indexOf("Name Alternative")>=0)
		{
			//if this is not the first NA
			if (prevRow)
			{
				//remember last row of prev NA, and rows count
				NAsHolder[objInd]["rows"].push(prevRow);
				NAsHolder[objInd]["count"] = count;
			}
			//advance NA index and create a new NA holder
			objInd++;
			NAsHolder[objInd] = {};
			NAsHolder[objInd]["NA"] = {};
			NAsHolder[objInd]["rows"] = [];
			NAsHolder[objInd]["rows"].push($(this));
			count = 0;
		}
		//for any other key (GN/FN/...)
		else if (td1Text.length > 0 && td2Text.length > 0)
		{
			//remember key-value pair of NA
			NAsHolder[objInd]["NA"][td1Text] = td2Text;
			//advance NA rows count and remember the TR (for deleting later, if necessary)
			count++;
			NAsHolder[objInd]["rows"].push($(this));
			//if last row of last NA - remember count
			if (index == iRows.length-1)
			{
				NAsHolder[objInd]["count"] = count;
			}
			//remember previous row
			else prevRow = $(this);
		}
	});

	//remember the input NAs holder
	var inputNAsHolder = NAsHolder;
	var maxConf = 0;

	//now do the same for the result NA - plus calculate maximal confidence of matching any input NA to any result NA
	NAsHolder = [];
	objInd = -1;
	count = 0;
	prevRow = null;
	iRows = $("tr", "#div"+resultIndex);
	iRows.each(function(index){
		var td1 = $($(this).find("td")[0]);
		var td1Text = td1.text();
		var td2 = $($(this).find("td")[1]);
		var td2Text = td2.text();
		if (td1Text.indexOf("Name Alternative")>=0)
		{
			if (prevRow)
			{
				NAsHolder[objInd]["rows"].push(prevRow);
				NAsHolder[objInd]["count"] = count;
				//result NA completed - now match NA to all input NAs to find max confidence 
				var conf = calcConf(inputNAsHolder, NAsHolder[objInd]);
				if (conf > maxConf) maxConf = conf;
			}
			objInd++;
			NAsHolder[objInd] = {};
			NAsHolder[objInd]["NA"] = {};
			NAsHolder[objInd]["rows"] = [];
			NAsHolder[objInd]["rows"].push($(this));
			count = 0;
		}
		else
		if (td1Text.length > 0 && td2Text.length > 0)
		{
			NAsHolder[objInd]["NA"][td1Text] = td2Text;
			count++;
			NAsHolder[objInd]["rows"].push($(this));
			if (index == iRows.length-1)
			{
				NAsHolder[objInd]["count"] = count;
				//last result NA completed - now match NA to all input NAs to find max confidence 
				var conf = calcConf(inputNAsHolder, NAsHolder[objInd]);
				if (conf > maxConf) maxConf = conf;
			}
			else prevRow = $(this);
		}
		else td2.html(td1Text);
	});

	//remember result NAs
	var resultNAsHolder = NAsHolder;
	//filter results NAs according to max conf
	if (maxConf > 0)
	{
		//iterate results NAs
		for (var i =0; i < resultNAsHolder.length; i++){
			var resultNAHolder = resultNAsHolder[i];
			//if NA equals to max conf - add the confidence row
			if (resultNAHolder["confidence"] == maxConf)
			{
				resultNAHolder["rows"][resultNAHolder["rows"].length-1].after("<tr><td>Confidence</td><td>" + maxConf + "</td></tr>")
			}
			else
				//if NA has lesser confidence - hide all its rows
				for (var j = 0; j <resultNAHolder["rows"].length; j++)
					resultNAHolder["rows"][j].css("display","none");
				
		}
	}
}
//calculate max confidence of matching a result NA to all input NAs
function calcConf(inputNAsHolder, NAHolder)
{
	var maxConf = 0;
	//iterate input NAs
	for (var i =0; i < inputNAsHolder.length; i++){
		var inputNAHolder = inputNAsHolder[i];
		//count key-value pair matches
		var conf = 0;
		for( key in NAHolder["NA"] ) {
			if (inputNAHolder["NA"][key] == NAHolder["NA"][key])
				conf++;
		}
		//calc conf percent - which is the numbe of matched pairs (conf), divided by sum of matched ans un-matched pairs
		conf = 100 * conf /
			(inputNAHolder["count"] + NAHolder["count"] - conf); //matched pairs are counted twice (both in input and result rows count), so we need to subtract it once
		//update max conf
		if (conf > maxConf)
			maxConf = conf;
	};
	//round max conf and remember in NA holder
	maxConf = Math.round(maxConf);
	NAHolder["confidence"] = maxConf;
	return maxConf;
}

function toggleInputName(name,i){
	//name = name.replace("%","'");
	analyzeName(name,i, -1);	
	toggle(i+1);
};

function showTypes(){
	if($("#typesPnl").is(":visible") == false){
		runEffect($("#typesPnl"));
	}
	$("#moreLessText").remove();
	$("#more").prepend('<span id=\"moreLessText\"><a href=\"#\" onclick=\"hideTypes();\">close</a></span>');
}

function hideTypes(){
	$("#moreLessText").remove();
	$("#more").prepend('<span id=\"moreLessText\"><a href=\"#\" onclick=\"showTypes();\">open</a></span>');
	$("#typesPnl").hide();
}

function runEffect(element) {
	var options = {};
	element.show( "blind", options, 500, function(){ } );
};

function insertConcepts(){
	
	var vals = $("#conceptPool").val();
	for (var i in vals) {
  		$("#concepts").append(new Option(vals[i], vals[i]));
	}
	$('#conceptPool :selected').remove();

	if ($("#newType").val().length > 0){
		$.ajax({
			url: "queryEng.php?queryType=label2qname&label=" + encodeURIComponent($("#newType").val()) ,
			success: function(data) {
				if (data.length == 2){
					$("#newType").css({'background-color' : 'pink'});
   				}
   				else{
   					$("#newType").css({'background-color' : 'white'});
   					$("#conceptPool option[value='" + $("#newType").val() + "']").remove();
   					$("#concepts option[value='" + $("#newType").val() + "']").remove();
   					$("#concepts").append(new Option($("#newType").val(), $("#newType").val()));
   					$("#newType").val("");
   				}
  			}
  		});
	}
}

function removeConcepts(){
	
	var vals = $("#concepts").val();
	for (var i in vals) {
  		$("#conceptPool").append(new Option(vals[i], vals[i]));
	}
	$('#concepts :selected').remove();

}

</script>
<style>
td {
	border-right: 0px solid #C1DAD7;
	border-bottom: 0px solid #C1DAD7;
	background: #fff;
	padding: 6px 6px 6px 12px;
	color: black;
}
</style>
</head>


<body>


<div class="row mt-3" style="margin:0">


	<div class="col-md-6" style="height: 98vh;overflow-y: scroll;">
			<a href="searchPage.php" class="btn btn-primary">Search</a>
			<a href="insertPage.php" class="btn btn-primary">Manage Target List</a>
			<br>
			<br>
      <div>

			<div class="card mb-2">
			  <div class="card-body">


			<div class="form-group">
				 <label>Select Target List</label>
      	 	<input type="hidden" id="wlSelected"></input>
	      	<select class="form-control" name="selectWL"; id="wl">
			<!--<option value="1">All List</option>-->			
				<?php	
				$arr = getListOfWatchList($ivEntityMatcherService);																										
					foreach ($arr as $val) 
					{
						echo "<option>";											
						echo $val;
						echo "</option>";
					}
				?>														    
			</select>
		</div>
		</div>
		</div>
		<div class="card  mb-2">
			  <div class="card-body">
					<div class="form-group">
					
					<label>
					
					<?php
							if (strlen($searchTitle) > 0){
								echo $searchTitle;
							}else{
								echo "Search Name";
							}
						?>
					
					</label>
					
							<input class="form-control" type="text" value="" name="searchtext" id="searchtext" onkeydown="if (event.keyCode == 13) document.getElementById('searchBut').click()"/><br />
							<a href="javascript:search(1, -1, true);" class="btn btn-success">search</a>
					</div>

					</div>
		</div>
		<div class="card  mb-2">
			  <div class="card-body">
        	<div class="form-group">
				<label>Search List of Names	</label>
        	
		        		<script language="JavaScript" type="text/javascript">
									function HandleBrowseClick()
									{
									    var fileinput = document.getElementById("fileupload");									    									    							
									    fileinput.click();
									}
									function Handlechange()
									{																															
										var fileinput = document.getElementById("fileupload");
										var textinput = document.getElementById("filename");									
										textinput.value = fileinput.value.replace(/^.*[\\\/]/, '');
									}
									function hideDiv(i)
									{
										document.getElementById("div0").style.visibility = 'visible';
										//document.getElementById("div0").innerHTML = "show";
									}

									function toggle(i) {
											var ele = document.getElementById("div"+i);											
											if(ele.style.display == "block") {
										    		ele.style.display = "none";												
										  	}
											else {
												ele.style.display = "block";												
											}
								        } 
								        
								    function filterInputId(inputId)
								    {
										var elements = (document.all) ? document.all : document.getElementsByTagName("*");
										
										var resultTables = {};
										for (var l=0, ll=elements.length; l<ll;l+=1)
										{
											var node = elements[l];
											if (node.id.indexOf("inputId-") > 0)
											{
												var inId = "inputId-" + inputId;
												var ind = node.id.indexOf(inId);
												var visible = ind > 0 && node.id.length == ind + inId.length;
												node.style.display = visible ? "" : "none";
												//alert(node.parentNode.parentNode.parentNode.id + " - true");
												if (visible)
													resultTables[node.parentNode.parentNode.parentNode.id]++;
											}
											else if (node.className == "resultsTable")
											{
												//alert(node.parentNode.id);
												if (resultTables[node.parentNode.id] == null)
													resultTables[node.parentNode.id] = 0;
											}
										}
										//display only rules what at least one visible result
										for (var id in resultTables) {
											var div = document.getElementById(id);
											//alert("1" + div.id);
											var parent = div.parentNode;
											//alert(parent);
											if (parent != null) parent = parent.parentNode;
											//alert(parent);
											if (parent == null) continue;
											//alert("hello" + div.id);
											//display or hide the table row of the rule results
											var tr = parent;
											//alert(tr + resultTables[id]);
											tr.style.display = resultTables[id]>0 ? "" : "none";
											//display or hide the previous row - which displays the rule name
											tr = tr.parentNode.parentNode.rows[tr.rowIndex-1];
											tr.style.display = resultTables[id]>0 ? "" : "none";
										}
								    }

								    function befoeSubmit()
								    {
											console.log('befoeSubmit');
											
								    	document.getElementById("wlSelectedList").value = document.getElementById("wl").value;								    	
								    	document.searchListForm.submit();
								    }
						</script>

          						<form name="searchListForm" action="searchPage.php" method="post" enctype="multipart/form-data">
          							<input type="button" class="btn btn-success" value="Select List of Names file" id="fakeBrowse" onclick="HandleBrowseClick();" style="display: none"/>
									<input type="file" id="fileupload" name="fileupload" onChange="Handlechange();"/>
									<a href="javascript:befoeSubmit();" class="btn btn-success mr-3">search</a>
									<label><input type="checkbox" name="analyzeFile" value="true">Analyse only</label>		          								


			          				<input type="hidden" id="filename" name="filename" readonly="true"/>
			          				<input type="hidden" name="wlSelectedList" id="wlSelectedList">	          				
			          			</form>
          			
        	
        </div>
        </div>
        </div>
    


		
				<div class="card  mb-2">
			  <div class="card-body">
          	<h2><span>Search Results</span></h2>
          	<div class="clr"></div>
        	<div id="results"></div>
        </div>   
      </div>
      </div>
   
  </div>
  



	<!-- dark blue #30384f -->
<div class="col-md-6" style="background-color:#aadaff;">


										<?php include("shaymap.php"); ?>


	</div>

</div>


<?php

//if search list file uploaded - invoke search on that file
if ($_FILES["fileupload"]["error"] > 0)
{
	echo "File upload error: " . $_FILES["fileupload"]["error"] . "<br>";
}
else if (!empty($_FILES["fileupload"]["tmp_name"]))
{

    $filePath = __DIR__ . DIRECTORY_SEPARATOR . "upload_file".DIRECTORY_SEPARATOR;	
	if (move_uploaded_file($_FILES["fileupload"]["tmp_name"], $filePath. $_FILES["fileupload"]["name"]))
	{		
		if ($_REQUEST['analyzeFile'] == "true"){
			echo "\t\n<script language='javascript'>\r\n";			
			echo "window.onload = analyzefile(\"" . $_FILES["fileupload"]["name"] . "\");\r\n";	
			echo"</script>\r\n";
		}
		else{				
			echo "\t\n<script language='javascript'>\r\n";
			echo "document.getElementById(\"filename\").value = '" . $_FILES["fileupload"]["name"] . "';\r\n";
			echo "window.onload = search(1, -1, false);\r\n";
			echo"</script>\r\n";
		}
	}
	else echo "Upload failed";
}

?>

</body>
</html>
