<?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");
include_once("sem/lexparser.php");
include_once("transliterator.php");

$qname = $_REQUEST["qname"];

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

$canEdit = $userAuth['canEdit'];
$canDelete = $userAuth['canDelete'];
$userPackageRestricted = $userAuth['userPackageRestricted'];

$typesJson = getElementDirectTypes($qname);
$slotsJson = getAllPossibleInstanceSlotsWithValues($qname);
//print_r($slotsJson);
$generalJson = getElementGeneralData($qname);
$hierarchy = getInstanceFlatHierarchy($qname);

?>
<!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>Content Manager</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/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/ivutils.js"></script>
<script src="js/jquery-ui/development-bundle/ui/jquery.ui.sortable.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">
<?php

foreach ($generalJson[results][bindings] as $value){
	if ($value[s][value] == "http://www.intuview.com/ontology#package"){
		echo "var pack = '" . $value[v][value] . "';"; 
		$package = $value[v][value];
	}
	else if ($value[s][value] == "http://www.w3.org/2000/01/rdf-schema#label"){
		$label = $value[v][value];
	}
}



if ($userPackageRestricted){
	$canEdit = ($canEdit && isUserDefinedPackage($package));
	$canDelete = ($canDelete && isUserDefinedPackage($package));
}

?>

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

// hide new type area
function hideNewType(){
	$( "#newtype" ).hide();
};

// add new type
function addNewType(){
	if($( "#type" ).val().length == 0){
		updateMessageBoard( "Empty type...", "error");
		return;
	}

  $.ajax({
	url: "updateEng.php?queryType=insertnewtype&typeLabel=" + $( "#type" ).val() + "&qname=" + encodeURIComponent(qname) ,
	success: function(data) {
			if (data == 1) {	// success
    			updateMessageBoard( $( "#type" ).val() + " was added successfuly", "success");
    			location.reload(true);
    		}
  		}
  	});
	
	$( "#newtype" ).hide();
};

// delete element
function deleteElement(){

	$.ajax({
	url: "updateEng.php?queryType=deleteelement&qname=" + encodeURIComponent(qname) ,
	success: function(data) {
			if (data == 1) {	// success
				window.history.back();
   			}
  		}
  	});

};

// delete type
function deleteType(typeLabel){

	$.ajax({
  	url: "updateEng.php?queryType=deletetype&qname=" + encodeURIComponent(qname) + "&typeLabel=" + encodeURIComponent(typeLabel) ,
	success: function(data) {
			if (data == 1) {	// success
				updateMessageBoard( typeLabel + " was delete successfuly", "success");
    			location.reload(true);
   			}
  		}
  	});

};

// delete slot value
function deleteSlotValue(slotQName, value, lang){

	$.ajax({
  	url: "updateEng.php?queryType=deleteslotvalue&qname=" + encodeURIComponent(qname) + "&slotQName=" + encodeURIComponent(slotQName) +
  								"&value=" + encodeURIComponent(value) + "&lang=" + encodeURIComponent(lang),
	success: function(data) {
			if (data == 1) {	// success
				updateMessageBoard( "Value was delete successfuly", "success");
    			location.reload(true);
   			}
  		}
  	});

};

function setInputFieldHTML(fieldType, slotQName, value, valueLang){

	// fieldType = string || date || boolean || int || instance
	var slotId = unqualifyName(slotQName);
	var fieldHtml = '<span style="padding=10px 10px 10px 10px; background=yellow;" id="newslotvalue-' + slotId + '">';
	fieldHtml += '<div style="height:20px;"/><div style="height:5px; background: gray;"/>';
	fieldHtml += '<a href="javascript:hideNewSlotValue(\'' + slotId + '\');"><img style="vertical-align:middle;" src="images/exit.png" title="close"/></a>';
	if (fieldType == 'instance'){
		fieldHtml += '<span style="padding: 0px 0px 0px 10px;">type: <i>instance</i></span>';
		fieldHtml += '<span style="width:25px;" id="newslotvalue-' + slotId + '-loading"></span>';
	}
	else if (fieldType == 'string'){
		fieldHtml += '<span style="padding: 0px 0px 0px 10px;">type: <i>text</i></span>'; 
	}
	else if (fieldType == 'boolean'){
		fieldHtml += '<span style="padding: 0px 0px 0px 10px;">type: <i>yes/no</i></span>'; 
	}
	else if (fieldType == 'int'){
		fieldHtml += '<span style="padding: 0px 0px 0px 10px;">type: <i>number</i></span>'; 
	}
	else if (fieldType == 'date'){
		fieldHtml += '<span style="padding: 0px 0px 0px 10px;">type: <i>date</i></span>'; 
	}
	fieldHtml += '<table style="padding=0px 0px 0px 0px; border-right: 0px solid #C1DAD7; border-bottom: 0px solid #C1DAD7;">';
	fieldHtml += '<tr>';
	fieldHtml += '<td style="padding: 0px 0px 0px 0px; border-right: 0px; border-bottom: 0px;">';
	if (fieldType == 'string'){
		fieldHtml += '<input type="text" name="slotvalue-' + slotId + '" id="slotvalue-' + slotId + '"/>';
		fieldHtml += '<select id="newslotvalue_lang-' + slotId + '" name="newslotvalue_lang-' + slotId + '">';
		fieldHtml += '<option value="en">English</option>';
		fieldHtml += '<option value="fr">French</option>';
		fieldHtml += '<option value="es">Spanish</option>';
		fieldHtml += '<option value="ar">Arabic</option>';
		fieldHtml += '<option value="id">Indonesian</option>';
		fieldHtml += '<select>';		
	}
	else if (fieldType == 'instance'){
		fieldHtml += '<input type="text" name="instancevalue-' + slotId + '" id="instancevalue-' + slotId +'"/>';
	}
	else if (fieldType == 'boolean'){
		fieldHtml += '<input type="checkbox" name="bvalue-' + slotId + '" id="bvalue-' + slotId + '"/>';
	}
	else if (fieldType == 'date'){
		fieldHtml += '<input type="text" name="datevalue-' + slotId + '" id="datevalue-' + slotId + '"/>';
		fieldHtml += '<select id="newslotvalue_calendartype-' + slotId + '" name="newslotvalue_calendartype-' + slotId + '">';
		fieldHtml += '<option value="g">Gregorian</option>';
		fieldHtml += '<option value="h">Hijri</option>';
		fieldHtml += '<select>';
	}
	else if (fieldType == 'int'){
		fieldHtml += '<input type="text" name="intvalue-' + slotId + '" id="intvalue-' + slotId + '"/>';
	}
	
	fieldHtml += '</td>';
	fieldHtml += '<input type="hidden" id="newslotvalue_method-' + slotId + '" name="newslotvalue_method-' + slotId + '"/>';
	fieldHtml += '<input type="hidden" id="newslotvalue_slotqname-' + slotId + '" name="newslotvalue_slotqname-' + slotId + '"/>';
	fieldHtml += '<input type="hidden" id="newslotvalue_fieldtype-' + slotId + '" name="newslotvalue_fieldtype-' + slotId + '" value="' + fieldType + '"/>';
	fieldHtml += '<input type="hidden" id="newslotvalue_oldvalue-' + slotId + '" name="newslotvalue_oldvalue-' + slotId + '"/>';
//	fieldHtml += '<td style="padding: 0px 0px 0px 0px; background: white; border-right: 0px; border-bottom: 0px;"><a href="javascript:hideNewSlotValue(\'' + slotId + '\');"><img src="images/cancel.gif"></a></td>';
	fieldHtml += '<td valign="top" style="padding: 0px 0px 0px 0px; border-right: 0px; border-bottom: 0px;"><a href="javascript:newSlotValue(\'' + slotId + '\');"><img style="vertical-align:middle;" src="images/search-but.png"></a></td>';
	fieldHtml += '</tr>';
	fieldHtml += '</table>';
	fieldHtml += '<div style="height:5px; background: gray;"/><div style="height:20px;"/>';
	fieldHtml += '</span>';
	
	setFieldHTML(fieldHtml, slotId);
	
	if (fieldType == 'string'){
		if (value != null){
			$("#slotvalue-" + slotId ).val(value);
			$("#newslotvalue_lang-" + slotId).attr('disabled', 'disabled');
			if (valueLang.length > 0)
				$("#newslotvalue_lang-" + slotId).val(valueLang);
		}
		$("#slotvalue-" + slotId).prop("disabled",false);
		$("#newslotvalue_fieldtype-" + slotId).val("string");
	}
	else if (fieldType == 'boolean'){
		if (value != null)
			$("#bvalue-" + slotId).attr('checked', true);
		else
			$("#bvalue-" + slotId).attr('checked', false);
		$("#newslotvalue_fieldtype").val("boolean");
	}
	else if (fieldType == 'date'){
		$("#newslotvalue_fieldtype-" + slotId).val("date");
		$("#datevalue-" + slotId).datepicker({
			changeMonth: true,
			changeYear: true
		});
		if (value != null){
			var n = value.indexOf(" ");
			var dateStr = value;
			var calendarType = "g";
			if (n > -1){
				dateStr = value.substring(0, n);
				calendarType = value.substring(n + 1, value.length);
			}
			$("#datevalue-" + slotId).val(dateStr);
			$("#newslotvalue_calendartype-" + slotId).val(calendarType);
		}
		else{
			$("#newslotvalue_calendartype-" + slotId).val("g");
		}
	}
	else if (fieldType == 'instance'){
		$("#newslotvalue_fieldtype-" + slotId).val("instance");
		if (value != null){
			$("#instancevalue-" + slotId).val(value);
		}
	}
	
	$("#newslotvalue_slotqname-" + slotId).val(slotQName);
	if (value != null){
		$("#newslotvalue_oldvalue-" + slotId).val(value);
	}
	return slotId;
}

function setFieldHTML(fieldHtml, slotId){
	$("#" + slotId + "-valueTd").append(fieldHtml);
}

// prepare new slot value field
function prepareSlotValueSpan(slotQName, value, valueLang, method){
	//alert(value);
	$.ajax({
  	url: "queryEng.php?qname=" + encodeURIComponent(slotQName) + "&queryType=propertyrange",
	success: function(data) {
			var obj = jQuery.parseJSON(data);
			var range = new Array();
			for (i = 0; i < obj.results.bindings.length; i = i + 1) {
				var x = obj.results.bindings[i];
				range.push(x.r.value);
			}
			var slotId = "";
			if (range.length == 0){
				return;
			}
			if (range[0] == "http://www.w3.org/2001/XMLSchema#string"){
				slotId = setInputFieldHTML("string", slotQName, value, valueLang);
			}
			else if (range[0] == "http://www.w3.org/2001/XMLSchema#boolean"){
				slotId = setInputFieldHTML("boolean", slotQName, value, valueLang);
			}
			else if (range[0] == "http://www.w3.org/2001/XMLSchema#integer"){
				slotId = setInputFieldHTML("int", slotQName, value, valueLang);
			}
			else if (range[0] == "http://www.intuview.com/ontology#datetype"){
				slotId = setInputFieldHTML("date", slotQName, value, valueLang);
			}
			else{
				// instance type
				slotId = setInputFieldHTML("instance", slotQName, value, valueLang);
				$("#instancevalue-" + slotId).autocomplete({  
  					source: function(req, add){
  						
  						$("#instancevalue-" + slotId + "-loading").html(ajax_load);
  						var types = "";
  						for (i = 0; i < range.length; i = i + 1) {
  							types += range[i] + ";";
  						}
  	                	$.getJSON("autoCompEng.php?type=instance&limit=50&concepts=" + encodeURIComponent(types) + "&callback=?", req, function(data) {  
  	                		
  	                		//$("#instancevalue-" + slotId + "-loading").html("");
  	                		var suggestions = [];  
  	                		$.each(data, function(i, val){  
                    			suggestions.push(val.label);  
                			});  
  		            		add(suggestions);  
        	    		});  
        			},  
         			select: function(e, ui) {  
            			//alert(ui.item.value);
         				},  
  					change: function() {  
 	 
	        	    	}  
    		    });
			}
			
			$("#newslotvalue_method-" + slotId).val(method);
  		}
  	});
};

// prepare edit slot value field
function prepareEditSlotValueSpan(slotQName, value, label, lang){
	//alert("prepareEditSlotValueSpan:" + label);
	if (label.length > 0)
		prepareSlotValueSpan(slotQName, label, lang, "edit");
	else
		prepareSlotValueSpan(slotQName, value, lang, "edit");
};

// prepare new slot value field
function prepareNewSlotValueSpan(slotQName){
	prepareSlotValueSpan(slotQName, null, "", "new");
	//$("#newslotvalue_method").val("new");
};

function newSlotValue(slotId){
	
	var fieldType = $("#newslotvalue_fieldtype-" + slotId).val();
	var value = "";
	var label = "";
	var lang = "";
	//var lang = $("#newslotvalue_lang").val();
	if (fieldType == "boolean"){
		value = $("#bvalue-" + slotId).is(':checked');
//		lang = "";
	}
	else if (fieldType == "string"){
		value = $("#slotvalue-" + slotId).val();
		lang = $("#newslotvalue_lang-" + slotId).val();
	}
	else if (fieldType == "date"){
		var calendarStr = $("#newslotvalue_calendartype-" + slotId).val();
		//alert(calendarStr);
		value = $("#datevalue-" + slotId).val();
		if (value.length == 0){
			value = "00/00/0000";
		}
		value = value + " " + calendarStr;
	}
	else if (fieldType == "instance"){
		label = $("#instancevalue-" + slotId).val();
	}
	
	if(value.length == 0 && label.length == 0){
		updateMessageBoard( "Empty value...", "error");
		return;
	}
	var slotQName = $("#newslotvalue_slotqname-" + slotId).val();
	var method = $("#newslotvalue_method-" + slotId).val();
	//alert(method);
	var oldValue = $("#newslotvalue_oldvalue-" + slotId).val();
	
	if (method == "new"){
		$.ajax({
  		url: "updateEng.php?queryType=insertslotvalue&qname=" + encodeURIComponent(qname) + "&slotQName=" + encodeURIComponent(slotQName) +
  					"&value=" + encodeURIComponent(value) + "&label=" + encodeURIComponent(label) + "&lang=" + lang,
		success: function(data) {
				if (data == 1) {	// success
					updateMessageBoard( "the value was updated successfuly", "success");
    				location.reload(true);
   				}else{
   					updateMessageBoard(data, "warning");
   				}
  			}
  		});
  	}
  	else if (method == "edit"){
  		var val = "oldValue";
  		if (fieldType == "instance")
  			val = "oldLabel";
  		$.ajax({
  		url: "updateEng.php?queryType=editslotvalue&qname=" + encodeURIComponent(qname) + "&slotQName=" + encodeURIComponent(slotQName) +
  					"&newValue=" + encodeURIComponent(value) + "&label=" + encodeURIComponent(label) + "&lang=" + lang + "&" + val + "=" + encodeURIComponent(oldValue),
		success: function(data) {
				if (data == 1) {	// success
					updateMessageBoard( "the value was updated successfuly", "success");
    				location.reload(true);
   				}
   				else{
   					updateMessageBoard(data, "warning");
   				}
  			}
  		});
  	}

};

// prepare the editor for lex entry
function prepareLexSpan(){
	$("#lexentry").show();
	$("#lexentry_description").val("");
}

// prepare the lex editor for editing an entry 
function prepareEditLexSpan(lexQName, lang, description){
	prepareLexSpan(lang, description);
	$("#lexentry_method").val("edit");
	$("#lexentry_oldvalue").val(description);
	$("#lexentry_lang").val(lang);
	$("#lexentry_lang").attr('disabled', 'disabled');
	$("#lexentry_description").val(description);
	$("#lexentry_qname").val(lexQName);
}

// prepare the editor for a new entry
function prepareNewLexSpan(){
	prepareLexSpan();
	$("#lexentry_method").val("new");
	$("#lexentry_lang").removeAttr('disabled');
}

// adding new slot value
function newLexEntry(){
	
	var desc = $("#lexentry_description").val();
	if(desc.length == 0){
		updateMessageBoard( "Empty value...", "error");
		return;
	}
	var method = $("#lexentry_method").val();
	var lexQName = $("#lexentry_qname").val();
	var oldDesc = $("#lexentry_oldvalue").val();
	var lang = $("#lexentry_lang").val();
	
	if (method == "new"){
		$.ajax({
  		url: "updateEng.php?queryType=insertlexentry&instance=" + encodeURIComponent(qname) + "&description=" + encodeURIComponent(desc) +
  				"&lang=" + lang + "&package=" + pack,
		success: function(data) {
				if (data == 1) {	// success
					updateMessageBoard( "the new entry was added successfuly", "success");
    				location.reload(true);
   				}else{
   					updateMessageBoard(data, "warning");
   				}
  			}
  		});
  	}
  	else if (method == "edit"){
  		$.ajax({
  		url: "updateEng.php?queryType=editlexentrydescription&qname=" + encodeURIComponent(lexQName) + "&description=" + encodeURIComponent(desc),
		success: function(data) {
				if (data == 1) {	// success
					updateMessageBoard( "the entry was updated successfuly", "success");
    				location.reload(true);
   				}else{
   					updateMessageBoard(data, "warning");
   				}
  			}
  		});
  	}

};

function deleteLexEntry(lexQName){
	$.ajax({
  		url: "updateEng.php?queryType=deleteelement&qname=" + encodeURIComponent(lexQName),
	success: function(data) {
			if (data == 1) {	// success
				updateMessageBoard( "The lexicon entry was delete successfuly", "success");
    			location.reload(true);
   			}
  		}
  	});
}

function goToLabel(label){
	$.ajax({
  		url: "queryEng.php?queryType=label2qname&label=" + encodeURIComponent(label),
	success: function(data) {
			// trimming...
			data = data.replace(/^\s+|\s+$/g, "");
			//alert(data + "X" + data.length);
			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");
   			}
  		}
  	});
}

// updating message board
function updateMessageBoard(msg, type){
	showMessage(msg, type);
};

// showing the confirmation board for deleting the entire element 
function showConfirmBoard(yesActions, msg){
	var tmp = '<div class="article" id="confirmBoard" style="font-color: white;">' + msg +
  			'<button type="button" onclick="' + yesActions + '">Yes</button>' +
			'<button type="button" onclick="hideAllMessagesWithAnimation();">No</button>' +
      	'</div>';
	showInputYesNoMessage(tmp, "info");
};

/*// hiding the confirmation board for deleting the entire element 
function hideConfirmationBoard(){
	$("#confirmBoard").remove();
};

// showing the confirmation board for deleting a slot value 
function showDeleteSlotValueConfirmBoard(){
	$("#deleteSlotValueConfirmBoard").show();
};

// hiding the confirmation board for deleting a slot value
function hideDeleteSlotValueConfirmBoard(){
	$("#deleteSlotValueConfirmBoard").hide();
};*/

// showing lexicon editor 
function showLexEntrySpan(){
	$("#lexentry").show();
};

// hiding the lexicon editor
function hideLexEntrySpan(){
	$("#lexentry").hide();
};

// hiding the new slot value field
function hideNewSlotValue(slotId){
	$("#newslotvalue-" + slotId).remove();
};

// language to a two letters code
function lang2code(lang){
	if (lang == "arabic")
		return "ar";
	else if (lang == "english")
		return "en";
	else if (lang == "french")
		return "fr";
	else if (lang == "spanish")
		return "es";
	else if (lang == "indonesian")
		return "id";
	else if (lang == "urdu")
		return "ur";
}

function formatEntryToLocation(description, lang, location){
	$.ajax({
	url: "queryEng.php?queryType=formatentry&desc=" + encodeURIComponent(description) + "&lang=" + lang,
	success: function(data) {
			$("#" + location).val(data);
  		}
  	});
}

function localLexParse(description, location){
	$.ajax({
	url: "queryEng.php?queryType=locallexparse&desc=" + encodeURIComponent(description) ,
	success: function(data) {
			try{
				var obj = jQuery.parseJSON(data);
				$("#" + location).css("background-color", "#CCFFCC");
				updateMessageBoard( "Well formed :)", "success");
			}
			catch(exception){
				$("#" + location).css("background-color", "#FFCCCC");
				updateMessageBoard( "Not well formed: " + data, "error");
			}
  		}
  	});
}

function toggleTransliteration(index){
	var newVal = $("#trans_" + index).val();
	//alert(newVal);
	var old = $("#desc_" + index).html();
	//alert(old);
	$("#trans_" + index).val(old);
	$("#desc_" + index).html(newVal);
}

// messages
var myMessages = ['info','warning','error','success'];
function hideAllMessages() {
	var messagesHeights = new Array();
	for (i=0; i<myMessages.length; i++){
		messagesHeights[i] = $('.' + myMessages[i]).outerHeight(); // fill array
		$('.' + myMessages[i]).css('top', -messagesHeights[i]); //move element outside viewport	  
	}
}

function showMessage(msg, type){
	hideAllMessages();
	$('.'+type).html(msg);
	setTimeout("hideAllMessagesWithAnimation();",3000);
	$('.'+type).animate({top:"0"}, 500);	
}

function showInputYesNoMessage(msg, type){
	hideAllMessages();
	$('.'+type).html(msg);
	$('.'+type).animate({top:"0"}, 500);	
}

function hideAllMessagesWithAnimation(){
	for (i=0; i<myMessages.length; i++){
		$('.' + myMessages[i]).animate({top: -$('.' + myMessages[i]).outerHeight()}, 500);	  
	}
}


  $(function(){
  		var cache = {},
			lastXhr;
  		function runEffect(element) {
			var options = {};
			element.show( "blind", options, 500, function(){ } );
		};
		
		// top messages
		hideAllMessages();
		 
		$('.message').click(function(){			  
			$(this).animate({top: -$(this).outerHeight()}, 500);
		});

	   $( "#addtypebut" ).click(function() {
	   		if($("#newtype").is(":visible") == false){
				runEffect($("#newtype"));
			}
			return false;
		});
		$( "#addlexentrybut" ).click(function() {
	   		if($("#newtype").is(":visible") == false){
				runEffect($("#newtype"));
			}
			return false;
		});
		
		// hiding things
		$( "#newtype" ).hide();
//		$("#newslotvalue").hide();
		$("#deleteSlotValueConfirmBoard").hide();
		$("#lexentry").hide();
		
		//attach autocomplete  
        $("#type").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() {  
  
            }  
        });
        
        $("#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() {  
  
            }  
        });
        
        $( ".column" ).sortable({
			connectWith: ".column"
		});

		$( ".portlet" )
			.find( ".portlet-header" )
				.addClass( "ui-portlet-header ui-corner-all" )
				.prepend( "<span class='ui-icon ui-icon-minusthick'></span>")
				.end()
			.find( ".portlet-content" );

		$( ".portlet-header .ui-icon" ).click(function() {
			$( this ).toggleClass( "ui-icon-minusthick" ).toggleClass( "ui-icon-plusthick" );
			$( this ).parents( ".portlet:first" ).find( ".portlet-content" ).toggle();
		});

  });

</script>
</head>

<body>
<div class="info message"></div>
<div class="error message"></div>
<div class="warning message"></div>
<div class="success message"></div>

<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 $_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 
      	//$menuActive = "Home";
      	//include('top-menu.php'); 
      	include('general-toolbar.php'); 
      ?>
      <div class="clr"></div>
    </div>
    <div class="clr"></div>
  </div>
  <div class="content">
      <div class="mainbar" id="mainbar">
        <div class="article">
<?php 

// title
echo "<h3><b>$label</b></h3>";
echo "<p><i>$qname</i></p>";
echo "<p class=\"package\">$package</p>";

echo "<table><tr>";
if ($canDelete){
	echo "<td><a href=\"javascript:showConfirmBoard('deleteElement();', 'Are you sure?');\"><img src=\"images/delete-off.gif\" 
					onmouseover=\"this.src='images/delete.gif'\" onmouseout=\"this.src='images/delete-off.gif'\" 
					title=\"Delete Element\"/></a></td>";
}
echo "</tr></table>";

?>
		
		</div>
		<div class="article">
<?php
// direct types
echo "<h2>Direct Types</h2>";
echo "<table><tr>";
if ($canEdit){
	echo "<td><a id=\"addtypebut\" href=\"\"><img style=\"width: 16px;\" src=\"images/add.png\" onmouseover=\"this.src='images/add-off.png';\"
					onmouseout=\"this.src='images/add.png';\" title=\"Add New Type\"></a>";
?>
<span id="newtype">
		<table style="border:0px;">
			<tr>
				<td style="padding: 0px 0px 0px 0px; border-right: 0px; border-bottom: 0px;"><input type="text" name="type" id="type" /></td>
				<td style="padding: 0px 0px 0px 0px; border-right: 0px; border-bottom: 0px;"><a href="javascript:addNewType();">
							<img onmouseover="this.src='images/search-but-light.png';" onmouseout="this.src='images/search-but.png';" src="images/search-but.png"></a></td>
				<td style="padding: 0px 0px 0px 0px; border-right: 0px; border-bottom: 0px;"><a href="javascript:hideNewType();"><img title="close" src="images/exit.png"></a></td>
			</tr>
		</table>
</span>

<?php
echo "</td>";
}
echo "</tr>";
echo "</table>";
echo "<div style=\"height:10px;\"></div>";
echo "<div>";

//counting
$directTypeAmount = count($typesJson[results][bindings]);

foreach ($typesJson[results][bindings] as $value){
	//if ($value[s][value] == "http://www.intuview.com/ontology#direct-type"){
	echo "<div>";
	if ($canDelete && $directTypeAmount > 1){
		echo "<a href=\"javascript:showConfirmBoard('deleteType(\'" . $value[tl][value] . "\');', 
							'Are you sure you want to delete this type?');\">
				<img style=\"vertical-align:middle;\" src=\"images/delete-off.gif\" onmouseover=\"this.src='images/delete.gif'\"
					onmouseout=\"this.src='images/delete-off.gif'\" title=\"Delete Type\"/></a>";
	}
	echo "<a href=\"editConceptPage.php?qname=" . urlencode($value[t][value]) . "\">" . $value[tl][value] . "</a></div>";
		
	//}
}
echo "</div>";
echo "</div>";
// properties

// aggregate values
$properties = array();
//print_r($json);

// ?s ?l ?t ?tl ?v ?vl
foreach ($slotsJson[results][bindings] as $value){
	
	$lang = $value[v]['xml:lang'];
	$val = $value[v][value];
	$valLabel = $value[vl][value];
	$slot = $value[s][value];
	$slotLabel = $value[l][value];
	$type = $value[t][value];
	$typeLabel = $value[tl][value];
	
	if (!array_key_exists($slot, $properties)){
		$properties[$slot] = array("label" => $slotLabel, "qname"=>$slot, "values"=>array(), "domain"=>array(), "count"=>0);
	}
	$properties[$slot][domain][] = $typeLabel;
	if (!array_key_exists($lang, $properties[$slot][values])){
		$properties[$slot]['values'][$lang] = array();
	}
	
	if (!array_key_exists($val, $properties[$slot][values][$lang])){
		$properties[$slot][values][$lang][$val] = array("value"=>$val, "label"=>$valLabel, "lang" => $lang);
		if (strlen($val) > 0)
			$properties[$slot]['count'] = ($properties[$slot]['count'] + 1);
	}
}
//print_r($properties);

$propertiesByTypes = array();
$revHierarchy = array_reverse($hierarchy);
for ($i = 0; $i < count($revHierarchy); $i = $i + 1){
	$propertiesByTypes[$revHierarchy[$i]] = array();
}
foreach ($properties as $slotKey => $slotNode){
	foreach ($slotNode['domain'] as $domain){
		$propertiesByTypes[$domain][] = $slotNode;
	}
}
//print_r($propertiesByTypes); echo "<br>";
?>
<div class="article">
<h2>Properties</h2>
<div class="column">
<?php

// remembering the slots so they won't be added twice (by two different types in the hierarchy)
$usedSlots = array();
$currType = "";
$initTypeBlock = false;
$emptySlot = false;
foreach ($propertiesByTypes as $typeLabel => $slots){
	
	foreach ($slots as $value){
		//if ($value['count'] == 0)
		//	continue;
		$emptySlot = false;
		if ($value['count'] == 0)
			$emptySlot = true;
		
		if (in_array($value['qname'], $usedSlots))
			continue;
		$usedSlots[] = $value['qname'];
		if (strlen($currType) == 0 || $typeLabel != $currType){
			echo "<div class=\"portlet\">";
			echo "<div class=\"portlet-header\">$typeLabel</div>";
			echo "<div class=\"portlet-content\">";
			echo "<table class=\"\">";
			$currType = $typeLabel;
			$initTypeBlock = true;
		}
		
		$slotId = unqualifyName($value[qname]);
		echo "<tr id=\"" . $slotId . "\">";
		echo "<td title=\"" . $value[qname] . "\" style=\"width:200px;\">";
		if ($emptySlot == false){
			echo "<b>";
		}
		echo $value[label];
		if ($emptySlot == false){
			echo "</b>";
		}
		echo "</td>";
		echo "<td id=\"" . $slotId . "-valueTd\" name=\"" . $slotId . "-valueTd\" style=\"width:200px;";
		if ($emptySlot)
			echo " background-color:white; padding: 0px 0px 0px 0px;";
		echo "\">";
		if ($value['count'] > 1){
			// for slots with multiple values
			echo "<table>";
			//for ($i = 0; $i < count($value['values']); $i = $i + 1){
			foreach ($value[values] as $langArray){
				foreach ($langArray as $currVal){
					echo "<tr><td valign=\"top\">";
					if (strlen($currVal[label]) > 0){
						echo "<a title=\"" . $currVal[value] . "\" href=\"editPage.php?qname=" . urlencode($currVal[value]) . "\">" . 
								$currVal[label] . "</a>";
					}
					else{
						if (strlen($currVal[lang]) > 0){
							echo "<span><img style=\"vertical-align:middle;\" src=\"images/" . $currVal[lang] . ".gif\"/></span>";
						}
						echo "<span>" . $currVal[value] . "</span>";
					}
					echo "</td>";
					// value tool bar
					if ($canEdit){
						echo "<td><a href=\"javascript:prepareEditSlotValueSpan('" . $value[qname] . "', '" . $currVal[value] . "', ";
						if (strlen($currVal[label]) > 0)
							echo "'" . $currVal[label] . "'";
						else
							echo "''";
						echo ", '" . $currVal[lang] . "');\">
								<img src=\"images/edit-off.gif\" onmouseover=\"this.src='images/edit.gif';\"
									onmouseout=\"this.src='images/edit-off.gif';\" title=\"Edit\"></a></td>";
					}
					if ($canDelete){
						echo "<td><a href=\"javascript:showConfirmBoard('deleteSlotValue(\'" . $value[qname] . "\', \'" . $currVal[value] . "\', \'" . $currVal[lang] . "\');', 
							'Are you sure you want to delete this value?'); \"><img src=\"images/delete-off.gif\" 
								onmouseover=\"this.src='images/delete.gif';\"
								onmouseout=\"this.src='images/delete-off.gif';\" title=\"Delete\"></a></td>";
					}
			
					echo "</tr>";
				}
			}
			echo "</table>";

			echo "</td>";
			if ($canEdit){
				echo "<td><a href=\"javascript:prepareNewSlotValueSpan('" . $value[qname] . "');\"><img style=\"width: 16px;\" src=\"images/add.png\" onmouseover=\"this.src='images/add-off.png';\"
								onmouseout=\"this.src='images/add.png';\" title=\"Add\"></a></td>";
			}
		}
		else{
		
			// single value slot
			foreach ($value['values'] as $i => $iv){
				foreach ($iv as $l => $lv){
					$currVal = $lv;
				}
			}
		
			if ($value['count'] > 0){
				if (strlen($currVal[label]) > 0)
					echo "<a title=\"" . $currVal[value] . "\" href=\"editPage.php?qname=" . urlencode($currVal[value]) . "\">" . 
							$currVal[label] . "</a>";
				else{
					if (strlen($currVal[lang]) > 0){
						echo "<span><img src=\"images/" . $currVal[lang] . ".gif\"/></span>";
					}
					echo "<span>" . $currVal[value] . "</span>";
				}
			}
			echo "</td>";
		
			if ($canEdit){
				if ($emptySlot == false){
					echo "<td><a href=\"javascript:prepareEditSlotValueSpan('" . $value[qname] . "', '" . $currVal[value] . "', ";
					if (strlen($currVal[label]) > 0)
							echo "'" . $currVal[label] . "'";
					else
						echo "''";
					echo ", '" . $currVal[lang] . "');\">
							<img src=\"images/edit-off.gif\" onmouseover=\"this.src='images/edit.gif';\"
								onmouseout=\"this.src='images/edit-off.gif';\" title=\"Edit\"></a></td>";
				}
				echo "<td><a href=\"javascript:prepareNewSlotValueSpan('" . $value[qname] . "');\"><img style=\"width: 16px;\" src=\"images/add.png\" onmouseover=\"this.src='images/add-off.png';\"
							onmouseout=\"this.src='images/add.png';\" title=\"Add\"></a></td>";
			}
			if ($canDelete && $emptySlot == false){
				echo "<td><a href=\"javascript:showConfirmBoard('deleteSlotValue(\'" . $value[qname] . "\', \'" . $currVal[value] . "\', \'" . $currVal[lang] . "\');', 
					'Are you sure you want to delete this value?');\"><img src=\"images/delete-off.gif\" 
					onmouseover=\"this.src='images/delete.gif';\"
						onmouseout=\"this.src='images/delete-off.gif';\" title=\"Delete\"></a></td>";
			}
		}
		echo "</tr>";
	}
	if ($initTypeBlock == true){
		$initTypeBlock = false;
		echo "</table>";
		echo "</div>";
		echo "</div>";
	}
}
echo "</div>";
echo "</div>";


// Lexicon Entries

$query = "select distinct ?l ?d ?s where {
			{{?l ivlex:instance <$qname> }
			UNION
			{?l ivlex:default-instance <$qname> }}
			?l ivlex:description ?d .
			?l ivlex:section ?s .
		} ORDER BY ?s";

$query = buildBasicSparql($query);
$json = executeSparqlOnService($query, "ont");
//print_r($json);
echo "<div class=\"article\">";
echo "<h2>Lexicon Entries</h2>";
?>

<?php
if ($canEdit){
	echo "<table><tr>";
	echo "<td><a href=\"javascript:prepareNewLexSpan();\"\"><img style=\"width: 16px;\" src=\"images/add.png\" onmouseover=\"this.src='images/add-off.png';\"
					onmouseout=\"this.src='images/add.png';\" title=\"Add New Lexicon Entry\"></a>";
	echo "</tr></table>";
}
?>
<span id="lexentry">
		<table style="border:0px;">
			<table>
				<tr>
					<td>
						<table>
							<tr>
								<td>
									<select id="lexentry_lang" name="lexentry_lang">
										<option value="english">English</option>
										<option value="french">French</option>
										<option value="spanish">Spanish</option>
										<option value="arabic">Arabic</option>
										<option value="indonesian">Indonesian</option>
										<option value="urdu">Urdu</option>
									<select>
								</td>
							</tr>
							<tr>
								<td style="padding=0px 0px 0px 0px; border-right: 1px; border-bottom: 1px;">
									<textarea style="width:300px;" name="lexentry_description" id="lexentry_description"></textarea>
								</td>
							</tr>

						</table>
					</td>
					<td>
						<table>
							<tr>
								<td><a href="javascript:formatEntryToLocation( $('#lexentry_description').val(), 
									$('#lexentry_lang').val(), 'lexentry_description');">Format entry</a></td>
							</tr>
							<tr>
								<td><a href="javascript:localLexParse( $('#lexentry_description').val(), 'lexentry_description');">Validate well-formed</a></td>
							</tr>
							<tr>
								<td style="padding=0px 0px 0px 0px; border-right: 0px; border-bottom: 0px;"><a href="javascript:newLexEntry();"><img src="images/search-but.png" onmouseover="this.src='images/search-but-light.png';"
								onmouseout="this.src='images/search-but.png';"></a></td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
			
						<tr>
				<input type="hidden" id="lexentry_method" name="lexentry_method"/>
				<input type="hidden" id="lexentry_oldvalue" name="lexentry_oldvalue"/>
				<input type="hidden" id="lexentry_qname" name="lexentry_qname"/>
				
				<!--<td style="padding=0px 0px 0px 0px; border-right: 0px; border-bottom: 0px;"><a href="javascript:hideLexEntrySpan();">
						<img title="close" src="images/exit.png"></a></td>-->
			</tr>
		</table>
</span>
<?php
echo "<table class=\"\">";
$index = 1;
foreach ($json[results][bindings] as $value){

	echo "<tr>";
	echo "<td><img style=\"vertical-align:middle;\" src=\"images/" . lang2code($value[s][value]) . ".gif\"/></td>";
	echo "<td style=\"width: 300px;\" title=\"" . $value[l][value] . "\"><a href=\"editLexPage.php?qname=" . $value[l][value] . "\">";
	echo "<span id=\"desc_$index\" style=\"font-size:14px;\">" . $value[d][value] . "</span></a></td>";
	
	if ($canEdit){
		echo "<td><a href=\"javascript:prepareEditLexSpan('" . $value[l][value] . "', '" . $value[s][value] . "', '" . str_replace("'", "\\'", $value[d][value]) . "');\">
						<img src=\"images/edit-off.gif\" onmouseover=\"this.src='images/edit.gif';\"
						onmouseout=\"this.src='images/edit-off.gif';\" title=\"Edit\"></a></td>";
	}
	if ($canDelete){
		echo "<td><a href=\"javascript:showConfirmBoard('deleteLexEntry(\'" . $value[l][value] . "\');', 'Are you sure?');\">
					<img src=\"images/delete-off.gif\" onmouseover=\"this.src='images/delete.gif';\"
						onmouseout=\"this.src='images/delete-off.gif';\" title=\"Delete\"></a></td>";
	}
	if ($value[s][value] == "arabic" || $value[s][value] == "urdu"){
		$trans = backTransliterateDescription($value[d][value], $value[s][value]);
		echo "<input type=\"hidden\" id=\"trans_$index\" value=\"$trans\"/>";
		echo "<td><a href=\"javascript:toggleTransliteration('$index');\">
					<img style=\"width:16px;\" src=\"images/transliterate-bw.png\" onmouseover=\"this.src='images/transliterate.png';\"
						onmouseout=\"this.src='images/transliterate-bw.png';\" title=\"Toggle transliteration\"></a></td>";
	}
	echo "</tr>";
	$index++;
}
echo "</table>";
	
echo "</div>";
?>
        </div>
      </div>
      <div class="sidebar">
        <div class="gadget">
        	<span style="vertical-align:middle;">
        		<span style="vertical-align:middle;"><img style="vertical-align:middle;" src="images/fast.png"><i>Quick Reference</i></img></span>
        		<span style="width:25px;" id="searchVal-loading"></span>
      			<input style="width:180px;" type="text" id="searchVal" name="searchVal"/>
      			<a href="javascript:goToLabel(document.getElementById('searchVal').value);">
      			<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';"/></a>
        	</span>
        </div>
        <div class="gadget">
        	<?php include("printHierarchy.php"); ?> 
        </div>
      </div>
      <div class="clr"></div>
  </div>

  
</div>
<div class="footer">
    <div class="footer_resize">
      <p class="lf">Version 1.0</p>
      <p class="rf">IVContent Manager</a></p>
      <div class="clr"></div>
    </div>
  </div>
</body>

</html>