/*jslint node: true */
/*global angular */
'use strict';

function infoPageReady()
{
	information_initializePage([], "Guest", 1);
}


var infoDataHander;
var docPagePrefix = "PageLoader.php?PageName=document&dcid=";
var cmHost;
function information_initializePage(request, userName, groupId)
{
	$("#hiUser").text("HI, " + userName);
	$.getJSON("informationEng.php", request, infoDataHander);
}

infoDataHander = function(data){
		$("#searchSpan").text(data.search);
		$("#numDocsPercentageTd").text(data.numberDocument  + " documents (" + data.precentage + "%)");
		$("#numOccurrencesTd").text(data.numberOccurrences);
		cmHost = data.isDemo? "demo.intuview.com" : data.rdfstoreCmHost;
		if (data.personCoRef)
		{
			var i = 0;
			$.each(data.personCoRef, function(key, val) {
				if (i++ < data.numberOfLines)
					appendInstance($("#perDiv"), key, val);
			});
			$("#per").text(i);
		}
		i = 0;
		if (data.org)
		{
			var i = 0;
			$.each(data.org, function(key, val) {
				if (i++ < data.numberOfLines)
					appendInstance($("#orgDiv"), key, val);
			});
			$("#org").text(i);
		}
		i = 0;
		if (data.place)
		{
			$.each(data.place, function(key, val) {
				if (i++ < data.numberOfLines)
					appendInstance($("#placeDiv"), key, val);
			});
			$("#place").text(i);
		}
		i = 0;
		if (data.theatre)
		{
			$.each(data.theatre, function(key, val) {
				var ontUrl = data.place[key]? data.place[key].ontUrl : "";
				if (i++ < data.numberOfLines)
					appendInstance($("#theaterDiv"), key, {"ontUr": ontUrl, "val": val});
			});
			$("#theater").text(i);
		}
		
		if (data.pos)
		{
			$("#posIdSpan").text("(" + data.posId + " documents)");
			var posStrArr = Array();
			$.each(data.pos, function(key, value) {
				posStrArr.push(value + " (<a href=\"" + docPagePrefix + key + "\" target=\"_blank\">" + key + "</a>)");
			});
			$("#positiveDiv").html(posStrArr.join("<b>;</b>"));
		}
		
		if (data.neg)
		{
			$("#negIdSpan").text("(" + data.negId + " documents)");
			var negStrArr = Array();
			$.each(data.neg, function(key, value) {
				negStrArr.push(value + " (<a href=\"" + docPagePrefix + key + "\" target=\"_blank\">" + key + "</a>)");
			});
			$("#negativeDiv").html(negStrArr.join("<b>;</b>"));
		}
		if (data.relations)
		{
			$("#relationsTable").show();
			var entitiesDocs = {};
			for (var entitiesType in data.relations) {
				for (var entityTable in data.relations[entitiesType])
				{
					var entityClass = entityTable;
					var indexOfHash = entityClass.indexOf("_");
					if (indexOfHash > 0) entityClass = entityClass.substring(0, indexOfHash);
					if (entityClass && entityClass.length)
						entityClass = entityClass[0].toUpperCase() + entityClass.slice(1);
					else
						entityClass = "Miscellaneous";
					if (!entitiesDocs[entityClass])
						entitiesDocs[entityClass] = {};
					
					for (var entity in data.relations[entitiesType][entityTable])
					{
						for (var relType in data.relations[entitiesType][entityTable][entity])
						{
							for (var docIdIndex = 0; docIdIndex < data.relations[entitiesType][entityTable][entity][relType].length; docIdIndex++)
							{
								var docId = data.relations[entitiesType][entityTable][entity][relType][docIdIndex];
								if (!entitiesDocs[entityClass][entity])
									entitiesDocs[entityClass][entity] = {};
								
								entitiesDocs[entityClass][entity][docId] = true;
							}
						}
					}
				}
			}
			for (var entityClass in entitiesDocs)
			{
				var newRow = $("<tr/>").insertAfter($("#relationsTable tr:last"));
				newRow.append($("<td style='border:0'/>").text(entityClass + ":"));
				var tdHtml = "";
				var entitiesByProminence = Object.keys(entitiesDocs[entityClass]).sort(function(a,b){Object.keys(entitiesDocs[entityClass][b]).length-Object.keys(entitiesDocs[entityClass][a]).length;});
				for (var entityIndex = 0; entityIndex < entitiesByProminence.length; entityIndex++)
				{
					var entity = entitiesByProminence[entityIndex];
					tdHtml += $('<div/>').text(entity).html(); //html-escape entity
					tdHtml += ": (";
					var first = true;
					for (var docId in entitiesDocs[entityClass][entity])
					{
						if (!first) tdHtml += ", ";
						first = false;
						tdHtml += '<a href="javascript:gotoPage(&quot;document&quot;, {dcid: ' + docId + '})">' + docId + "</a>";
					}
					tdHtml += ")<BR/>\r\n";						
				}
				newRow.append($("<td style='border:0'/>").html(tdHtml));
				
			}
		}
		if (data.kbSlots)
		{
			$("#kbInfoTable").show();
			for (var key in data.kbSlots) {
				var newRow = $("<tr/>").insertAfter($("#kbInfoTable tr:last"));
				newRow.append($("<td style='border:0'/>").text(key + ":"));
				newRow.append($("<td style='border:0'/>").text(data.kbSlots[key]));
			}
		}
		if (data.dbSlots)
		{
			$("#dbInfoTable").show();
			for (var key in data.dbSlots) {
				var newRow = $("<tr/>").insertAfter($("#dbInfoTable tr:last"));
				newRow.append($("<td style='border:0'/>").text(key + ":"));
				newRow.append($("<td style='border:0'/>").text(data.dbSlots[key]));
			}			
		}
		$("#loadingDiv").hide();
		$("#mainbar").show();
};


if (typeof angular == 'undefined')
$(document).ready(infoPageReady);

function appendInstance(parentDiv, key, val){
	var ontUrl = val.ontUrl;
	var name = $('<div/>').text(key).html(); //html-escape key
	if (false)
	if (!!ontUrl)
	{
		var hashIndex = ontUrl.indexOf("#");
		var namePair = hashIndex > 0? "qname=" + escape("http://www.intuview.com/ontology#" + ontUrl.substring(hashIndex+1))
				: "label=" + ontUrl; //in case ontUrl is not a qualified name - assume it's the label of the ontology instance
		name = "<a href=\"http://" + cmHost + "/ivcontentm/editPage.php?displayMode=true&" + namePair + "\" target=\"_blank\">" +
		name + "</a>";
	}
	var searchType = parentDiv.attr('id').indexOf("per") === 0? "searchPerson" : parentDiv.attr('id').indexOf("org") === 0? "searchOrganization" : "searchPlaces";
	name = '<a href="javascript:gotoTemplate(&quot;information&quot;, {' + searchType + ': &quot;' + name + '&quot;})">' +
			name + "</a>";
	var suffix = val.val? "(" + val.val + ") <br>" :
		" (" + val.occurrences + " in " + val.doc + " documents) <br>";
	//
	parentDiv.append(name + suffix);
}



function toggle(div) {
	var ele = document.getElementById(div);		
	if(ele.style.display == "block")
    	ele.style.display = "none";
	else
		ele.style.display = "block";
	//changeLable();
};


/**
 * @ngdoc function
 * @name ivlawApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the ivlawApp
 */
if (typeof angular != 'undefined')
angular.module('ivlawApp')
    .controller('InformationController', [ 'APIService', 'APIMock', '$location', function (APIService, APIMock, $location) {
        var self = this;
		
			if (APIMock.infoFields == null)
				return;
			
			docPagePrefix = "#/ivdocument/";
			
			var infoFields = {
					searchPerson: APIMock.infoFields.searchPerson.value,
					searchPlaces: APIMock.infoFields.searchPlaces.value, 
					searchOrganization: APIMock.infoFields.searchOrganization.value };
			
		    APIService.information(infoFields).then(function (result) {
                infoDataHander(result.data);

            }, function (reason) {
                console.error(reason);
            });


    }]);
