<?php	
	if(!isset($_SESSION)) session_start();
	include("loginCheckPoint.php");
	require_once("demosettings.php");

	include_once 'write_log.php';

	$userdetails = fetchUserDetails($_SESSION['username']);	
// 	global $AUTH;
	$AUTH = getGroupsAuth();
	$userAuth = $AUTH[$userdetails['Group_ID']]['permissions'];

	$canAnalyzeFolder = $userAuth['canAnalyzeFolder'];
	
	$dcid =  $_REQUEST["dcid"] ?? $_REQUEST["docId"];
	$freetext = $_REQUEST["freetext"];	
	$text = "";
	$spanDom = new DOMDocument();
	$xpathDom = null;
	$port = "2020";
	
	$directory = "$metadata_path".DIRECTORY_SEPARATOR . $dcid;
	$usersNotes = $_REQUEST["usersNotes"];
	if (strlen($usersNotes) > 0){
		$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
		$res = $mysqli->query("SELECT user_notes FROM files where id=" . $dcid);
		if(!empty($res)){
			$row = $res->fetch_object();
			$user_notes_db = $row->user_notes;
			$str = $user_notes_db ."<br><b>" . $userdetails['Username'] . "</b>: " . $usersNotes;
			$str = $mysqli->real_escape_string($str);
			
			$query = "UPDATE files
								   SET user_notes=\"$str\"
								   WHERE id=" . $dcid;
			
			$res = $mysqli->query($query);			
		}
		$usersNotes = $str;
	}
	
	$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);
	$res = $mysqli->query("SELECT user_notes FROM files where id=" . $dcid);
	if(!empty($res)){
		$row = $res->fetch_object();
		$usersNotes = $row->user_notes;			
	}	
	
	
	
	
	include 'sparql.php';

	// loading
	$mysqli = new mysqli($databaseHost, $databaseUser, $databasePass, $databaseName);

		
	$menuColorStyle = base64_decode(file_get_contents($directory . $folderSeparator . "m_$dcid.txt"));
	$digestJson = base64_decode(file_get_contents($directory . $folderSeparator . "d_$dcid.txt"));
	$newText = base64_decode(file_get_contents($directory . $folderSeparator . "n_$dcid.txt"));
	$textDir = base64_decode(file_get_contents($directory . $folderSeparator . "t_$dcid.txt"));
	$report = base64_decode(file_get_contents($directory . $folderSeparator . "r_$dcid.txt"));
	
	$sql = "UPDATE files
			SET results=\"\" 
			WHERE id=$dcid";			
									
	$res = $mysqli->query($sql);	
	sqlClose($mysqli, 'document');
	
	$a = 1;	
	
	function formTextAsHTML($text){
  	$tmp = str_replace("\n", "<br>", $text);
  	return $tmp;
  }

  function getFirstCDATAChildText($element){
  	$node = $element->firstChild;
  	while($node != null && $node->nodeType != XML_CDATA_SECTION_NODE){
  		$node = $node->nextSibling;
  	}
  	if($node != null){
  		return $node->wholeText;
  	}
  	return "";
  }

?>
<!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>
<title>IntuScan Station</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<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="jquery-ui/js/jquery-1.7.1.min.js"></script>
<!--<script type="text/javascript" src="js/script.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>

 <script src="jquery/jquery.js" type="text/javascript"></script>
  <script src="jquery/jquery-ui.custom.js" type="text/javascript"></script>
  <script src="jquery/jquery.cookie.js" type="text/javascript"></script>
  <script src="jquery-ui/development-bundle/ui/jquery.ui.tabs.js"></script>

<link type="text/css" href="jquery-ui/css/ui-lightness/jquery-ui-1.8.17.custom.css" rel="stylesheet" />

<script type="text/javascript" src="jquery-ui/js/jquery-ui-1.8.17.custom.min.js"></script>

  <link href="src/skin/ui.dynatree.css" rel="stylesheet" type="text/css" id="skinSheet">
  <script src="src/jquery.dynatree.js" type="text/javascript"></script>
  <style>
  <?php echo $menuColorStyle ?>
  </style>

<script type="text/javascript">
var treeData = <?php echo $digestJson ?>;
var doc = <?php echo $dcid ?>;
var ajax_load = "<p align=center><img src='images/loader.gif' alt='loading...' /></p>";
function showElement(id){
	$("#ontElement").html(ajax_load).load("fetchOntElement.php?id=" + id + "&doc=" + doc, function(){

  		var icons = {
				header: "ui-icon-circle-arrow-e",
				headerSelected: "ui-icon-circle-arrow-s"
			};
			$( "#accordion" ).accordion({
				icons: icons
			});
			$( "#toggle" ).button().toggle(function() {
				$( "#accordion" ).accordion( "option", "icons", false );
				}, function() {
					$( "#accordion" ).accordion( "option", "icons", icons );
				});
  		});		
};

 $(function(){
  	$(".none").click(function(){
  		showElement($(this).attr("id"));  		
  	});
    $( "#tabs" ).tabs({
			ajaxOptions: {
				error: function( xhr, status, index, anchor ) {
					$( anchor.hash ).html(
						"Couldn't load this tab. We'll try to fix this as soon as possible.");
				}
			}
		});
    $("#entities-tree").dynatree({
      checkbox: true,
      selectMode: 3,
      children: treeData,
      onSelect: function(select, node) {
      	var leaves = node.getLeaves();
      	var first = false;
      	for(var i = 0 ; i < leaves.length ; i++){
      		var tmp = "#" + leaves[i].data.key;
      		var folderNode = leaves[i].getFirstFolderParent();
      		if(first == false && select && $(tmp).offset() != null){
      			$("#tabs-1").scrollTop($(tmp).offset().top);
      			first = true;
      		}
      		//alert(folderNode.data.key);
      		if(select){
      			$(tmp).addClass(folderNode.data.key);
      		}
      		else{
      			$(tmp).removeClass(folderNode.data.key);
      		}
      	}
      	goToScroll(node.data.key);
    },
    onDblClick: function(node, event) {
    	node.toggleSelect();
    },
    onClick: function(node, event) {
    	if(!node.data.isFolder){
    		showElement(node.data.key);    			
    	}
    },
    onKeydown: function(node, event) {
		if( event.which == 32 ) {
          node.toggleSelect();
          return false;
        }
    },
      // The following options are only required, if we have more than one tree on one page:
//        initId: "treeData",
      cookieId: "dynatree-Cb3",
      idPrefix: "dynatree-Cb3-"
    });
  });
  function FindNext() {	  
         var str = document.getElementById ("findInput").value;
         if (str == "") {
             alert ("Please enter some text to search!");
             return;
         }
         
         if (window.find) {        // Firefox, Google Chrome, Safari
             var found = window.find (str);
             if (!found) {
                 alert ("The following text was not found:\n" + str);
             }             
         }
         else {
             alert ("Your browser does not support free text search!");
         }
    }
  function goToScroll(id){
  	document.getElementById(id).scrollIntoView();
  }

  function AddComment(){	  
	  document.getElementById("userNotesForm").submit();	  	  
  }
</script>
</head>
<body>
<div class="main">
<div class="top-banner">
	 <a href="home.php"><img src="images/intuscan-img.png" style="border:0;"/></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 $_SESSION["username"] ?></p>
	 <p style="padding:0 10px 10px 10px; float:right;"><a style="color:red;" href="logoff.php">logoff</a></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">
      <div class="mainbar">
        <div class="article">
        	<div class="ann1">
					<div id="tabs">						
						<ul>
							<li><a href="#tabs-1" style="font-size:12px;">Text</a></li>
							<li><a href="#tabs-2" style="font-size:12px;">Report</a></li>
						</ul>
						<div class="entity-source">
						<?php
							echo "<div dir=\"" . $textDir . "\" id=\"tabs-1\" style=\"width:100%; height: 500px;overflow: scroll;padding: 8px;\">";
						?>
						<?php echo formTextAsHTML($newText) ?></div></div>
						<div class="entity-source" dir="ltr"><div id="tabs-2" style="width:100%; height: 500px;overflow: scroll;padding: 8px; font-size:12px;"><?php echo $report ?></div></div>
					</div>
			</div>
        </div>
        <form id="userNotesForm" action="document.php?dcid=<?php echo $dcid;?>" method="post">
        	<input type="hidden" id="dcid" name="dcid" value="<?php echo $dcid; ?>"> 
	         <div class="gadget">
	         	User Notes: 
	         	 <label id="userNotesLabel"><?php echo nl2br($usersNotes); ?></label>
	         	<br></br> 
	         	<table> 
		         	<tr>    
			         	<td>   	
			         		<textarea id="usersNotes" name="usersNotes" style="width:300px; height:50px;"></textarea>
			         	</td>
			         	<td>
		         			<button onclick="AddComment();">Add Comment</button>
		         		</td>
		         	</tr>
	         	</table>
	        </div>
        </form>
      </div>
      
      <div>
      <h2 class="star"><span>Free text search</span></h2>	
      <input type="text" id="findInput" value="<?php echo $freetext;?>" size="20" />
 	  <button onclick="FindNext();">Find Next</button>
 	  </div>
      <div class="sidebar">
        <div class="gadget" >        
          <h2 class="star"><span>Key Concepts</span></h2>
          <div class="clr"></div>
			
			<div class="widget" id="entities-tree" style=height:500px;overflow:scroll;></div>			
          </div>
         
         
        <div class="gadget" id="ontElement">
        </div>
      </div>
      <div class="clr"></div>
  </div>
</div>

  </div>
</body>
</html>
<?php if (!empty($freetext)){
	echo "<script type=\"text/javascript\">";
	echo "FindNext();";
	echo "</script>";
}?>
