<?php

session_start();

include_once("config.php");
//include("loginCheckPoint.php");
//include_once("sem/updates.php");
include_once("sem/queries.php");
include_once("bsw/utils.php");
include_once("authorizations.php");

$wlDeleted = $_REQUEST["wlDeleted"];
if (!empty($wlDeleted))
{	
    $success = deleteWatchList($wlDeleted,$ivEntityMatcherService);
	if (!$success)
		$deleteWatchListStatus = "Delete Watchlist failed: $errormsg ($errorcode)";
}
$concept = $_REQUEST["concepts"];
$package = $_REQUEST["package"];
$uploadWatchListStatus = $_REQUEST["uploadWatchListStatus"];
$watchListName = $_REQUEST["watchListName"];

//$userdetails = fetchUserDetails($_SESSION['username']);
//print_r($userdetails);
global $AUTH;
//print_r($AUTH);
//$userAuth = $AUTH[$userdetails['Group_ID']];
//print_r($userAuth);
$canAddInstance = $userAuth['canAddInstance'];
$canAddConcept = $userAuth['canAddConcept'];
$canAddPackage = $userAuth['canAddPackage'];
$userPackageRestricted = ($userAuth['userPackageRestricted'] == 1)?1:0;
//echo $userPackageRestricted;
//$packages = getAllPackages($userPackageRestricted);
//print_r($packages);
if (count($packages) == 0){
	$canAddInstance = false;
	$canAddConcept = false;
}

?>
<!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>Entity Matcher - Manage Target List</title>
<link rel="stylesheet" href="js/jquery-ui/development-bundle/themes/base/jquery.ui.all.css">
<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.tabs.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>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.core.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.widget.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.position.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.autocomplete.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.mouse.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.sortable.js"></script>
<script src="js/ivutils.js"></script>
<link href="style.css" rel="stylesheet" type="text/css" />
<!--<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>-->
<script type="text/javascript">

var qname = <?php echo "'" . $qname . "'" ?>;
var ajax_load = "<img style='vertical-align:middle;' id='removeImg' src='images/loader.gif' alt='loading...' />";

  $(function(){
		
		$("#type").change(function () {
        	arrangeFor($('#type').val());
        })
        .change();
		
		$("#searchVal").autocomplete({  
  
            //define callback to format results  
            source: function(req, add){  
  			
  				$("#searchVal-loading").html(ajax_load);					
                //pass request to server  
                $.getJSON("autoCompEng.php?type=concept;property;instance&limit=150&callback=?", req, function(data) {  
  
  					$("#searchVal-loading").html("");
                    //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() {  
  
            }  
        });
		
        $("#concept").autocomplete({  
  
            //define callback to format results  
            source: function(req, add){  
  
  				$("#concept-loading").html(ajax_load);					
                
                //pass request to server  
                $.getJSON("autoCompEng.php?type=concept&limit=50&callback=?", req, function(data) {  
  
  					$("#concept-loading").html("");
  					
                    //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 arrangeFor(type){
	if (type == 'package'){
		$('#conceptRow').hide();
		$('#packageRow').hide();
	}else{
		$('#conceptRow').show();
		$('#packageRow').show();
	}
}
  
function validateForm(){
	var valid = true;
	if (!validateConcept())
		valid = false;
	if (!checkLabel())
		valid = false;
	return valid;
}

function validateConcept(){
	var valid = true;
	if (!$("#concept").val()){
		$("#conceptMsg").html("* required");
		valid = false;
	}
	return valid;
}

function goToLabel(label){
	$.ajax({
  		url: "queryEng.php?queryType=label2qname&label=" + encodeURIComponent(label),
	success: function(data) {
			// trimming...
			data = data.replace(/^\s+|\s+$/g, "");
			if (data.length > 0) {	// success
				window.location.replace('editPage.php?qname=' + encodeURIComponent(data));
   			}
   			else{
   				updateMessageBoard( "The label " + label + " does not refer to a correct element", "error");
   			}
  		}
  	});
}

function validateLabel(){
	var valid = false;
	if (!$("#label").val()){
		$("#labelMsg").html("* required");
	}
	else{
		if ($("#type").val() == "instance"){
			if (!validateInstanceLabel($("#label").val())){
				$("#labelMsg").html("invalid");
				$("#labelValid").html("");
			}
			else{
				$("#labelValid").html("<image src=\"images/ok.gif\" style=\"vertical-align: middle;\"/>");
				$("#labelMsg").html("");
				valid = true;
			}
		}
		else if ($("#type").val() == "concept"){
			if (!validateConceptLabel($("#label").val())){
				$("#labelMsg").html("invalid");
				$("#labelValid").html("");
			}
			else{
				$("#labelValid").html("<image src=\"images/ok.gif\" style=\"vertical-align: middle;\"/>");
				$("#labelMsg").html("");
				valid = true;
			}
		}
		else if ($("#type").val() == "package"){
			if (!validatePackageLabel($("#label").val())){
				$("#labelMsg").html("invalid");
				$("#labelValid").html("");
			}
			else{
				$("#labelValid").html("<image src=\"images/ok.gif\" style=\"vertical-align: middle;\"/>");
				$("#labelMsg").html("");
				valid = true;
			}
		}
	}
	return valid;
}

function checkLabel(){
	if (!validateLabel())
		return false;
	if ($("#type").val() == "package"){
<?php
	echo "if ($userPackageRestricted && $(\"#label\").val().substring(0, 1) != '@'){
			var tmp = \"@\" + $(\"#label\").val();
			$(\"#label\").val(tmp);
			}";
?>
		//alert($("#label").val());
		return true;
	}
		
	$.ajax({
	url: "queryEng.php?queryType=label2qname&label=" + $( "#label" ).val(),
	success: function(data) {
			if (data.length > 2){
				$("#labelMsg").html("occupied");
				$("#labelValid").html("");
			}
  		}
  	});
	return true;
}

function addElement(){
	// if adding package - move to another method
	if ($("#type").val() == "package")
		return addPackage();

	if (!validateForm())
		return;
	
	$("#insertForm").append(ajax_load);
	$("#addBut").attr("disabled", "disabled");
	$.ajax({
	url: "updateEng.php?queryType=insertelement&label=" + $( "#label" ).val() + "&typeLabel=" + $("#concept").val() + "&elementType=" + $("#type").val() + "&package=" + $("#package").val(),
	success: function(data) {
			//alert(data);
			if (data == 1){
				updateMessageBoard("The element was added successfully");
				$.ajax({
				//	url: "queryEng.php?queryType=label2qname&label=" + $.trim(encodeURIComponent($( "#label" ).val())),
					url: "queryEng.php?queryType=label2qname&label=" + $.trim(encodeURIComponent($( "#label" ).val())),
					success: function(data) {
						window.location = 'editPage.php?qname=' +  encodeURIComponent($.trim(data));
					}
  				});
			}
			else{
				$("#addBut").removeAttr("disabled");
				$("#removeImg").remove();
				updateMessageBoard(data);
			}
  		}
  	});
}

function addPackage(){
	if (!checkLabel())
		return;
	$("#insertForm").append(ajax_load);
	$("#addBut").attr("disabled", "disabled");
	$.ajax({
	url: "updateEng.php?queryType=insertpackage&label=" + $( "#label" ).val(),
	success: function(data) {
			//alert(data);
			if (data == 1){
				updateMessageBoard("The package was added successfully");
				location.reload(true);
			}
			else{
				$("#addBut").removeAttr("disabled");
				$("#removeImg").remove();
				updateMessageBoard(data);
			}
  		}
  	});
}

// updating message board
function updateMessageBoard(msg){	
	//$("#mainbar").prepend('<div class="article" id="messageBoard" style="background: #3BB9FF; font-color: white;"></div>');
	messageBoardVis("");
	$("#messageBoardContent").html(msg);
	//setTimeout("$(\"#messageBoard\").remove()",3000);
};
function messageBoardVis(vis){	
	//$("#messageBoard")
	document.getElementById("messageBoard").style.visibility = vis;
};


function deleteWL(){			
	window.location = 'insertPage.php?wlDeleted=' + document.getElementById("wl").value;// 'editPage.php?qname=' +  encodeURIComponent($.trim(data));	
};


</script>
</head>

<body>
<div class="main">
 <div class="top-banner">
	 <a href="home.php"><img style="padding:5px 5px 5px 5px; border:0px 0px 0px 0px;" src="images/contentm-logo-ffffff.png"/></a>
	 <p style="padding:0 10px 10px 10px; float:right;"><b>version 1</b></p>
	 <p style="padding:0 10px 10px 10px; float:right;">Hi, <?php echo "Guest" ?></p>	 
 </div>
  <div class="header">
    <div class="header_block">
     
      <div class="clr"></div>
      <?php
      	include('general-toolbar.php'); 
      ?>
      <div class="clr"></div>
    </div>
    <div class="clr"></div>
  </div>
  <div class="content">
	  <table class="article" id="messageBoard" style="background: #3BB9FF; font-color: white;visibility:hidden"><tr><td id="messageBoardContent" style="background: #3BB9FF; font-color: white;width:100%">This should be hidden</td><td><a href="javascript:messageBoardVis('hidden')">X</a></td></tr></table>
      <div class="mainbar" id="mainbar">
        <div class="article">
			<h2>Load Target List</h2>			
			<form name="insertForm" action="insertList.php"  method="post" enctype="multipart/form-data">	
				<script language="JavaScript" type="text/javascript">
									//function HandleBrowseClick()
									//{
									//    var fileinput = document.getElementById("browse");
									//    fileinput.click();
									//}
									//function Handlechange()
									//{
									//	var fileinput = document.getElementById("browse");
									//	var textinput = document.getElementById("filename");
									//	textinput.value = fileinput.value.replace(/^.*[\\\/]/, '');									
									//}
									function loadFile()
									{										
										document.insertForm.submit();
									}
				</script>
          		<br>
          		<span>
          			<span style="vertical-align: middle;">
          				<input type="file" name="file" id="file">
          				<input type="hidden" name="performingUpload" value="yes"/>
          				<br><br>
          				<input type="submit" name="submitButton" value="Upload List" onclick="loadFile()">
          			<!--   
          					<input type="button" value="Select List of Entity file" id="fakeBrowse" onclick="HandleBrowseClick();"/>
							<input type="file" id="browse" name="fileupload" style="display: none" onChange="Handlechange();"/>
							
									
																											
									
							<a href="javascript:loadFile();"><img style="vertical-align:middle;" src="images/search-but.png" onmouseover="this.src='images/search-but-light.png'"
			        								onmouseout="this.src='images/search-but.png'" id="searchBut"/></a> -->
			    		<!-- <br> <input type="text" style="border: none; width:300px;" id="filename"  readonly="true"/> -->
			    		<br><br>
			    		<?php
			    			if ($uploadWatchListStatus)
				    			echo '<script language="javascript">updateMessageBoard(' . json_encode($uploadWatchListStatus) . ');</script>';
				    		#if ($uploadWatchListStatus == 1)			
	      					#	echo "Watch list: ". $watchListName. " uploaded";
				    		#else if (!empty($updateMessageBoard))
				    		#	echo "Upload Watch list failed";
			    			if ($deleteWatchListStatus)
				    			echo '<script language="javascript">updateMessageBoard(' . json_encode($deleteWatchListStatus) . ');</script>';
      					?>
			         </span>          				
          		</span>
			</form>
        </div>
        <div class="article">
        	<h2>Delete Target List</h2>
        	</br>
          	<span style="vertical-align: middle;">
          		<table>
	          		<tr>
	          			<td>
			          		<select style="width: 200px; 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>
						</td>
						<td>
							<a href="javascript:deleteWL();"><img style="vertical-align:middle;" src="images/search-but.png" onmouseover="this.src='images/search-but-light.png'"
		          								onmouseout="this.src='images/search-but.png'" id="deleteBut"/></a>
		          		</td>
	          		</tr>
          		</table>
          	</span>           	
        	<div id="results"></div>
        </div>  		
        </div>
          
      </div>
      <br>
        
      
      
      <div class="clr"></div>
  </div>

  
</div>
</body>

</html>