ontos.DetailsFactsPanel = function(cfg){
	cfg = cfg || {};
	Ext.apply(cfg, {id:'ekbfactspanel', title:ontos.locale.facts_tab,layout:'border',bodyBorder:false,border:false,shim:true,animCollapse:false,constrainHeader:true});
	cfg.items = [
		{region:'west', bodyStyle:'padding:5px', bodyBorder: false, border: false, autoScroll:true, width:200, split:true, html:'<div id=ekbfactsleft></div>'},
		{region:'center', bodyStyle:'padding:5px', bodyBorder: false, border: false, autoScroll:true, html:'<div id=ekbfactsright></div>'}
	];
	
	this.module = cfg.module;
	this._subject = null;
	
	ontos.DetailsFactsPanel.superclass.constructor.call(this, cfg);
	
	// init datastore
	this.initDataStore();
    
	this.addEvents({
        "entitySelected" : true,
        "relationSelected" : true
    });
    
    this.on("activate", function() {
		this._activated = true;
		this.update();
	}, this);
	
	this.on("deactivate", function() {
		this._activated = false;
	}, this);
	
	this.selectedObject=null;
};

Ext.extend(ontos.DetailsFactsPanel, ontos.ContentPanel, {
	_cache: 'OFF',
	src: 'doc',
	initDataStore: function() {
	    this.dataStore = new Ext.data.Store({
	    	proxy: new Ext.data.HttpProxy({method:"POST", url: "data",timeout: 3000000}),
	        // create reader that reads the Topic records
	        reader: new Ext.data.JsonReader({
	            root: 'ds', 
	            totalProperty: 'size',
	            id: 'post_id'
	        }, [
	            {name: 'relationType', mapping: 'relationType'},
	            {name: 'toEntity', mapping: 'toEntity'},
	            {name: 'toEntityLabel', mapping: 'toEntityLabel'},
	            {name: 'toEntityType', mapping: 'toEntityType'}
	        ])
	    });
		this.dataStore.addListener("load",this.onDataReady,this);
	},
	update : function() {
		this._invalidated = this._invalidated || 
			(this._subject != null && (this.selectedObject != this._subject.id || this.src != this._subject.src));
	    if (this._initialized && this._invalidated && this._activated) {
			this.loadData();
			this._invalidated = false;
		}
	},
	createMarkup : function() {
		this._leftElem = Ext.get('ekbfactsleft');
		this._rightElem = Ext.get('ekbfactsright');
		this._leftTable =  Ext.DomHelper.append(this._leftElem,
			{tag:"table", id:'relations-list',cellpadding:0,cellspacing:0,border:0,width:'100%'}, true);
		this._rightTable =  Ext.DomHelper.append(this._rightElem,
			{tag:"table", id:'entities-list',cellpadding:0,cellspacing:0,border:0,width:'100%'}, true);
	},
    loadData : function() {
    	this.selectedObject = this._subject.id;
    	this.src = this._subject.src;
    	this.maskState = true;
		if (this.autoSize) this.autoSize();
		this.updateLoadMask();
		this.dataStore.load({params:{mode:"json", query:"facts", module:"TryPage", cache:'ON|OFF', limit:1000, src:this._subject.src, subjid: this.selectedObject, ontology: ontos.currentOntology}});
	},
    renderData : function() {
    	if (this.dataStore){
    		if (!this._leftElem) this.createMarkup();
    		
    		this.rlsdt = []; this.rset={}; var pos = 0;
    		for (var i = 0;i<this.dataStore.getCount();i++){
				var theRecord = this.dataStore.getAt(i).json;
				var theRelationType = theRecord.relationType.split("#")[1];
    				
    			var p = this.rset[theRelationType];
    			if (!p && p != 0) {
    				this.rset[theRelationType]=pos; p = pos;
    				this.rlsdt[pos]={fr: theRecord.relationType, r: theRelationType, es:{}, eids:{}};
    				++pos;
    			}
    			var eid = this.rlsdt[p].eids[theRecord.toEntity];
    			var skip = false;
    			if (eid) {
    				if (eid.label.length < theRecord.toEntityLabel.length) {
    					delete this.rlsdt[p].es[eid.label];
    					eid.label = theRecord.toEntityLabel;
    				} else {
    					skip = true;
    				}
    			}
    			if (!skip) {
    				this.rlsdt[p].eids[theRecord.toEntity] = {label: theRecord.toEntityLabel};
    				this.rlsdt[p].es[theRecord.toEntityLabel] = {v:theRecord.toEntity, t:theRecord.toEntityType};
    			}
    		}
    		
    		if (this.page1content) {
				this.page1content.remove();
				this.page1content = null;
			}
			if (this.page2content) {
				this.page2content.remove();
				this.page2content = null;
			}
			var html = "";
			Ext.each(this.rlsdt, function(e) {
				html += "<tr><td nowrap='nowrap' id=\"_" + encodeURIComponent(e.r) + "\"><a href='#'>" + e.r.replace(/_/g, " ") + "</a></td></tr>";
			}, this);
			html += "<tr><td height='100%'></td></tr>";
			this.prevSelRel = null;
			this.prevSelEnt = null;
			this.page1content = this._leftTable.insertHtml("afterBegin",html,true);
			Ext.each(this.rlsdt, function(e) {
				Ext.get("_" + encodeURIComponent(e.r)).on("click", function(elem, h, opt) {
					this.renderEntities(e.r);
					if (this.prevSelRel) {
						Ext.get(this.prevSelRel).toggleClass("rel-selected");
					}
					this.prevSelRel = "_" + encodeURIComponent(e.r);
					Ext.get(this.prevSelRel).toggleClass("rel-selected");
					this.prevSelEnt = null;
					this.doFireEvent("relationSelected", opt);
				}, this, {entityType: e.fr, entityLabel: e.r.replace(/_/g, " ")});
			}, this);
			
    	}
    },
    renderEntities : function(rel) {
    	var p = this.rset[rel];
		var r = this.rlsdt[p];
		if (this.page2content) {
			this.page2content.remove();
			this.page2content = null;
		}
    	var theBody =  this._rightTable.child("tbody");
		if (!theBody) theBody = Ext.DomHelper.append(this._rightTable,{tag:"tbody"},true);
	   	for (var e in r.es) {
    		var theID = r.es[e].v.split("#")[1];
	   		// skip douples
	   		if (Ext.get("__" + encodeURIComponent(theID)))	
	   			continue;
    		var theTR = Ext.DomHelper.append(theBody,{tag:"tr"},true);
    		var theTD = Ext.DomHelper.append(theTR,{tag:"td",id:"__"+encodeURIComponent(theID)},true);
    		var theObject = new ontos.widgets.EntityObject(r.es[e].v,e,r.es[e].t);
			theObject.render(theTD);
			theObject.on("click",function(anObject){
				window.top._dispatcher.fireEvent('objectSelected', {id: anObject.entityID, label: anObject.entityLabel, type: anObject.entityType, src: this._subject.src});
				anObject.relationType = r.fr;
				this.doFireEvent("entitySelected", anObject);
			},this);
		};
		this.page2content = theBody;
		for (var e in r.es) {
    		var theID = r.es[e].v.split("#")[1];			
			Ext.get("__" + encodeURIComponent(theID)).on("click", function(elem, h, opt) {
				if (this.prevSelEnt) {
					Ext.get(this.prevSelEnt).toggleClass("ent-selected");
				}
				this.prevSelEnt = "__" + encodeURIComponent(opt.entityID.split("#")[1]);
				Ext.get(this.prevSelEnt).toggleClass("ent-selected");
				//this.doFireEvent("entitySelected", opt);
				
			}, this, {entityID: r.es[e].v, entityLabel: e, entityType: r.es[e].t});
		}
    },
    initialize : function(){
		this._initialized = true;
		this.update();
		
		this.module.on("subjectSelected", function(s) {
			this._subject = s;
			this.update();
			//var actobj = Ext.getCmp('ekbnlpexportact');
			//if (actobj) actobj.setDisabled(!this._subject);
			//actobj = Ext.getCmp('ekbsummaryact');
			//if (actobj) actobj.setDisabled(!this._subject);
			
		}, this);
		
		this.module.on("onSearch", function(s) {
			this._subject = s;
			this.update();
		}, this);
    },
    onDataReady : function(aStore,aRecords,anOptions){
    	this.renderData();
    	this.maskState = false;
        this.updateLoadMask();
    }
});

ontos.DetailsDiagramPanel = function(cfg){
	cfg = cfg || {};
	Ext.apply(cfg, {id:'ekbdiagrampanel', title: ontos.locale.diagram, layout:'fit',bodyBorder:false,border:false,shim:true,animCollapse:false,constrainHeader:true});
	cfg.html = '<div id=ekbdiagrampanel2 style=\'height:100%\'></div>';
	//cfg.items = {bodyStyle:'padding:5px', bodyBorder: false, border: false, autoScroll:true, };
	ontos.DetailsDiagramPanel.superclass.constructor.call(this, cfg);
	
	this.module = cfg.module;
	this.dataStore = null;
	this.contentElement = null;
	this.addEvents({
        "objectSelected" : true
    });
   	
   	this._initialized = false;
	this._invalidated = false;
	
	this.on("activate", function() {
		this._activated = true;
		this.update();
	}, this);
	
	this.on("deactivate", function() {
		this._activated = false;
	}, this);
   	
	this.on('resize', function(){
		if(this.diagramlayout)
			this.diagramlayout.setSize();
	},this);
	
    this.dataStore = new Ext.data.Store({
    	proxy: new Ext.data.HttpProxy({method:"POST", url: "data",timeout: 3000000}),
        // create reader that reads the Topic records
        reader: new Ext.data.JsonReader({
            root: 'ds',
            totalProperty: 'size',
            id: 'id'
        }, [
            {name: 'x', mapping: 'x'}
        ])
    });
	this.dataStore.addListener("load",this.onDataReady,this);
			/*
	if (this.dispatcher) {
	   	this.dispatcher.on("subjectSelected", function(anObject, h) {
	   		var theEntityID = anObject.id; 
			if (this.selectedObject != theEntityID) {
				this.selectedObject = theEntityID;
	    		this._anObject = anObject;
	    		this._invalidated = true;
	    		this.update();
			}
		}, this);
	}
	*/ 
} 

Ext.extend(ontos.DetailsDiagramPanel, ontos.ContentPanel, {
	update : function() {
		this._invalidated = this._invalidated || 
			(this._subject != null && (this.entityid != this._subject.id || this.src != this._subject.src));
	    
		if (this._initialized && this._invalidated && this._activated) {
			this.loadData(this._subject.id,this._subject.label,this._subject.type, this._subject.src);
			this._invalidated = false;
		}
	},
//	onResize : function(adjWidth,adjHeight,rawWidth,rawHeight ){
//		debugger;
//		ontos.widgets.EntityRelations.superclass.onResize(adjWidth, adjHeight,rawWidth,rawHeight);
//	},
    loadData : function(anEntityID,anEntityLabel,anEntityType,src) {
    	this.entityid = anEntityID;
    	this.entityLabel = anEntityLabel;
    	this.entityType = anEntityType;
    	this.src = src;
		this.maskState = true;
		this.updateLoadMask();
    	this.dataStore.removeAll();
    	this.dataStore.load({params:{mode:"json", module: "TryPage", query:"diagram", cache:'ON|OFF', src:this.src, subjid:anEntityID, ontology: ontos.currentOntology, limit:1000}});
    }, 
    renderData : function() {
    	this.createLayout();
    	
		this.buildTimer.stop();
		this.diagramlayout.clear();
    	var theCenterNode = new DataGraphNode();
    	theCenterNode.color = "#FF0000";
    	theCenterNode.label = this.entityLabel;
    	theCenterNode.entityID = this.entityid;
    	theCenterNode.entityType = this.entityType;
		theCenterNode.root = true;
    	this.diagramlayout.dataGraph.addNode(theCenterNode);
    	var theDist = {};
    	var relNodes = {};
    	if (this.dataStore && this.dataStore.getCount()>0){
    		for (var i = 0;i<this.dataStore.getCount();i++){
				var theRecord = this.dataStore.getAt(i).json;
				if (this.entityid==theRecord.entity)
					continue;
    			var theEntityType = theRecord.entityType;
    			var theEntityID = theRecord.entity;
    			var theRelationType = theRecord.relationLabel;
    			/////
    			var theKey = theRelationType+theRecord.entityLabel.toLowerCase();
    			if (theDist[theKey]==null){
    				theDist[theKey] = 1;
    			} 
    			else 
    				continue;

				var theNode = new DataGraphNode();
				var theColor = "#000000";   
		    	theNode.label = theRecord.entityLabel;
		    	theNode.entityType = theEntityType;
		    	theNode.entityID = theEntityID;

				var theRelNode = relNodes[theRelationType];
				if (theRelNode==null){
					theRelNode = new DataGraphNode();
					theRelNode.entityType = "Relation";
					theRelNode.label = theRelationType;
					theRelNode.isRelation = true;
					this.diagramlayout.dataGraph.addNode(theRelNode);					
   					theRelNode.parent = theCenterNode;
   					theCenterNode.edgeCount +=1;
			        relNodes[theRelationType] = theRelNode;
				}
				if (theRelNode.edgeCount > 10){
					continue;
				}
				theNode.parent=theRelNode;
				theRelNode.edgeCount +=1;				
				
		    	this.diagramlayout.dataGraph.addNode(theNode);
    		}
    	}
		this.diagramlayout.setSize();
		this.buildTimer.start();
    },
    initialize : function(){
		this._initialized = true;
		this.update();
		this.module.on("subjectSelected", function(s) {
			this._subject = s;
			this.update();
		}, this);
		this.module.on("onSearch", function(s) {
			this._subject = s;
			this.update();
		}, this);
    },
    createLayout : function(){
    		if (this.diagramlayout) return;
    			// create layout
    			//var cnt = Ext.getCmp('ekbdiagrampanel').getEl().dom;
    			var cnt = Ext.get('ekbdiagrampanel2').dom;
			this.diagramlayout = new SnowflakeLayout(cnt, true );
			var layout = this.diagramlayout;
			this.diagramlayout.view.skewBase=400;
			this.diagramlayout.setSize();
			
			this.diagramlayout.config._default = {
				This:this, 
				model: function( dataNode ) {
					var theSector = dataNode.edgeCount*23+10;
					if (theSector>=360) theSector = 300;
				    return {
				      childRadius: 90, 
				      fanAngle: dataNode.root?360:theSector,
				      rootAngle: 45
				    }
			  	},
				view: function( dataNode, modelNode ) {
					var nodeElement = document.createElement( 'div' );
					if (dataNode.isRelation){
						nodeElement.className = "nodeLink";
						nodeElement.innerHTML = dataNode.label;
						return nodeElement;
					} else {
				    	nodeElement.onclick =  new EventHandler( this.This, this.This.handleMouseClickEvent, dataNode);
						nodeElement.className = "node";
						nodeElement.innerHTML = (dataNode.label.length>10)?dataNode.label.substring(0,10):dataNode.label;

						var theObject = new ontos.widgets.EntityObject(dataNode.entityID,ontos.pandora(dataNode.label),dataNode.entityType, {onlyTooltip:true});
						
						//var theObject = new ontos.widgets.LightEntityObject(dataNode.entityID,ontos.pandora(dataNode.label),dataNode.entityType);
						
						//var theObject = new ontos.widgets.EntityObject(dataNode.entityID,ontos.pandora(dataNode.label),dataNode.entityType);
						//theObject.stats = "";	
						theObject.render(nodeElement);
						//if (theObject.isPerson()){
							
							//Ext.QuickTips.register({entityLabel:dataNode.label,callback:getPhoto,target:nodeElement,text:theObject.getTooltipCode()});
						//} else {
							//Ext.QuickTips.register({target:nodeElement,text:theObject.getTooltipCode()});
						//}
					}
//					Ext.QuickTips.register({target:nodeElement,title:dataNode.entityType.split("#")[1],text:dataNode.label});
					nodeElement.style.color = dataNode.color;

					return nodeElement;
				}
			}
//    		this.layout.forces.spring._default = function( nodeA, nodeB, isParentChild ) {
//				return {	springConstant: 0.2,dampingConstant: 0.2,restLength: 20	};
//			}
//    		this.layout.forces.magnet = function() {
//				return {	magnetConstant: -4000,minimumDistance: 20};
//			}
			this.diagramlayout.viewEdgeBuilder = function( dataNodeSrc, dataNodeDest ) {
				if ( this.svg ) {
					return {	stroke:'#111111',"stroke-width": '2px',"stroke-dasharray": '2,4'};
				} else {
					return {	pixelColor: '#111111',	pixelWidth: '2px',	pixelHeight: '2px',pixels: 15};
				}
			}
			//this.layout.model.ENTROPY_THROTTLE=false;
			var SimpleBuilder = function() {
			  this.started = false;
			  this.update = function() {
			    var d = layout.dequeueNode();
			    if ( !this.started && d ) {
			      this.started=true;
			      while( layout.dequeueNode() ) {};
			    }
			    if ( this.started && !d ) { return false; }
			  }
			};
			this.buildTimer = new Timer(0);
			this.buildTimer.subscribe( new SimpleBuilder );
			this.buildTimer.start();
    },
    handleMouseClickEvent : function(aNode){
    	window.top._dispatcher.fireEvent('objectSelected', {id: aNode.entityID, label: aNode.label, type: aNode.entityType, src: this._subject.src});
		//this.doFireEvent("objectSelected", {entityID:aNode.entityID,entityLabel:aNode.label,entityType:aNode.entityType});
    },
    onDataReady : function(aStore,aRecords,anOptions){
    	this.renderData();
		this.maskState = false;
		this.updateLoadMask();
    }
});