view show.html @ 48:107cf3f3134e draft

implemented inspectAccess popup
author Nobuyasu Oshiro <dimolto@cr.ie.u-ryukyu.ac.jp>
date Sun, 24 Mar 2013 06:05:42 +0900
parents 0f624dc3664d
children 614acb91d753
line wrap: on
line source

#{extends 'main.html' /}
#{set title:messages.get('AAEvidenceSiftingModel.userdesktops.show.title') /}

#{set 'moreStyles'}
        <link rel="stylesheet" href="/aat/public/viewer/css/viewer_form.css">
#{/set}
#{set 'moreScripts'}
	<script type="text/javascript" src="@{'/public/viewer/js/lib/jquery-ui-1.8.23-min.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/lib/jquery.ui.touch-punch.min.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/lib/jquery.contextmenu.r2.packed.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/lib/jsBezier-0.4-min.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jsPlumb-util-1.3.15-RC1.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jsPlumb-dom-adapter-1.3.15-RC1.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jsPlumb-1.3.15-RC1.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jsPlumb-defaults-1.3.15-RC1.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jsPlumb-renderers-svg-1.3.15-RC1.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jsPlumb-renderers-canvas-1.3.15-RC1.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jsPlumb-renderers-vml-1.3.15-RC1.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jquery.jsPlumb-1.3.15-RC1.js'}" charset="${_response_encoding}"></script>
	<script type="text/javascript" src="@{'/public/viewer/js/1.3.15/jquery.jsPlumb-1.3.15-all-min.js'}" charset="${_response_encoding}"></script>
#{/set}

<div id="page">
    <div class="title">
	&{'AAEvidenceSiftingModel.userdesktops.show.title'}&nbsp;[ ${desktop.project.name} ]
    </div>
    <ul >
	<li>&gt; <a href="@{AAEvidenceSiftingModel.Projects.show(desktop.id)}">&{'navigation.back'}</a></li>
    </ul>
	<script type="text/javascript">var _desktopid = ${desktop.id};function desktopid(){return _desktopid;}</script>


<div id="miniDisplay" style='position:fixed; width:250px; height:250px; border:solid 1px; border-radius:5px; opacity:1; z-index:10; visibility:visible;'>
    <div style='position:absolute; left:0; top:0; width:100%; height:100%; background:black; opacity:0.5;'></div>
    <div id="closeMiniDisplay" style='position:absolute; right:5px; top:-3px; z-index:10; color:white;' onclick="$('#miniDisplay').css('visibility','hidden');" onmouseover="$('#closeMiniDisplay').css('color','yellow');" onmouseout="$('#closeMiniDisplay').css('color','white')" >CLOSE</div>
    <div style='position:absolute; width:90%; height:90%;'>
	<div style='position:absolute; left:5%; top:5%; width:100%; height:100%; background:white;'>
	    <div id="miniDisplayTitle" style='position:absolute; left:10px; top:5px; font-size:24px; width:100%; text-align:left;'>
  Evidence Title
	    </div>
	    <div id="miniDisplayBody" style='position:absolute; left:20px; top:40px;'>
		Please click any node.
	    </div>
	</div>
    </div>
</div>

<div class="graphMainCss" style="position:absolute; left:0; bottom:0; width:100%; height:75%;" id='graphMain'>
    <div  style="position:absolute; width:0; height:0;left:0;" id='graphRoot'>
    </div>
</div>

<div id='menuDisplay' class='menuDisplayCss' style='left:0; top:20; z-index:20;'>
    <div id="closeMenuDisplay" style='position:absolute; right:5px; top:-15px; z-index:10; color:white;' onclick="closeSelectMenu();" onmouseover="$('#closeEdgeInfoDisplay').css('color','yellow');" onmouseout="$('#closeMenuDisplay').css('color','white')" >CLOSE</div>  
    <div class='menu' id='stateMenu'>
	<div class='menuTitleCss' id='stateMenuTitle'>StateSelect</div>
	<div class='menuTitleBodyCss' id='stateMenuBody'>
	</div>
    </div>
    <div class='menu' id='traverseMenu' style=''>
	<div class='menuTitleCss' id='traverseMenuTitle'>TraverseSelect</div>
	<div class='menuTitleBodyCss'id='traverseMenuBody'>
	</div>
    </div>
    <div class='menu' id='' style=''>
	<div class='menuTitleCss' onclick="getInspect(CURRENT_DATA.nodeId);" id='accesDocument'>Read Document Now!!</div>
  </div>
</div>

<div class='contextMenu' id='selectMenu'>
    <ul>
	<div class='contextMenuTitle' >State Select</div>
	<div id='stateSlectMenu'>
	    <li id='stateAccept' class='contextMenuContent'>accept</li>
	    <li id='stateReject' class='contextMenuContent'>reject</li>
	    <li id='stateRetract' class='contextMenuContent'>retract</li>
	</div>
	<div class='contextMenuTitle' >Traverse</div>
	<div id='traverseSelectMenu'>
	</div>
	<div class='contextMenuTitle'>Inspect</div>
	<div id='inspectMenu'>
	</div>
    </ul>
</div>

<div id='popupAccessUrl' style='position:fixed; left:0px; top:0px; width:100%; height:100%; z-index:30; display:none'>
  <div style='position:absolute;left:0;top:0;width:100%;height:100%;background:black;opacity:0.5'></div>
  <div style='position:absolute;left:50%;top:50%;'>
      <div style='position:absolute;left:-160px;top:-80px;width:320px;height:120px;background:white'>
	  <form onsubmit="" id='accessForm'>
	      <div style='position:absolute;left:20px;top:15px;font-size:24px;width:280;text-align:center;'>
		  Document Access
	      </div>
	      <span id='accessStop' style='position:absolute;left:100px;top:70px;width:80px;font-size:16px;height:24px;line-height:24px;' class='button' value='back' onclick="$('#popupAccessUrl').css('display','none');">Back</span>  
	      <span id='accessRequest' style='position:absolute;left:220px;top:70px;width:80px;font-size:16px;height:24px;line-height:24px;' class='button' value='access' onclick="">Access</span>
	  </form>
      </div>
  </div>
</div>



<script type="text/javascript">
var CURRENT_DATA = {};

if(!Array.prototype.filter){
    Array.prototype.filter=function(func){
	var arr=[];
	for(var i=0;i<this.length;i++)if(func(this[i]))arr.push(this[i]);
	return arr;
    }
}

var arrowConnector = {
    connector:"StateMachine",
    //    paintStyle:{lineWidth:3,strokeStyle:"#056"},
    paintStyle:{lineWidth:2,strokeStyle:"#aaf"},
    hoverPaintStyle:{strokeStyle:"#dbe300"},
    endpoint:"Blank",
    anchor:"Continuous",
    overlays:[ ["PlainArrow", {location:1, width:20, length:12} ]]
};
var arrowBothConnector = {
    connector:"StateMachine",
    paintStyle:{lineWidth:2,strokeStyle:"#aaf"},
    hoverPaintStyle:{strokeStyle:"#dbe300"},
    endpoint:"Blank",
};
function GraphData() {
    var graphData = {};
    graphData.nodes = {};
    graphData.edges = {};
    return graphData;
}
var DragHandler = {
    _oElem : null,
    _id : null,
    attach : function(oElem) {
	oElem.onmousedown = DragHandler._dragBegin;
	return oElem;
    },
    _dragBegin : function(e) {
	var oElem = DragHandler._oElem = this;
	if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
	if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
	var x = parseInt(oElem.style.left);
	var y = parseInt(oElem.style.top);
	e = e ? e : window.event;
	oElem.mouseX = e.clientX;
	oElem.mouseY = e.clientY;
	document.onmousemove = DragHandler._drag;
 	document.onmouseup = DragHandler._dragEnd;
	return false;
    },
    _drag : function(e) {
	var oElem = DragHandler._oElem;
	var x = parseInt(oElem.style.left);
	var y = parseInt(oElem.style.top);
	e = e ? e : window.event;
	var nextX =  x + (e.clientX - oElem.mouseX);
	var nextY =  y + (e.clientY - oElem.mouseY);
	if (nextX < 0) nextX = 0;
	if (nextY < 0) nextY = 0;
	oElem.style.left = nextX + 'px';
	oElem.style.top = nextY  + 'px';
	oElem.mouseX = e.clientX;
	oElem.mouseY = e.clientY;
	if (oElem.nodeId) {
	    var id = oElem.nodeId;
	    var node = GRAPH_DATA.nodes[id];
	    node.position.x = nextX;
	    node.position.y = nextY;	    
	}
	return false;
     },
    _dragEnd : function() {
	var oElem = DragHandler._oElem;
	document.onmousemove = null;
	document.onmouseup = null;
	DragHandler._oElem = null;
	if (oElem.nodeId) {
	    var x = parseInt(oElem.style.left);
	    var y = parseInt(oElem.style.top);
	    var node = GRAPH_DATA.nodes[oElem.nodeId];
	    if (x < 0) x = 0;
	    if (y < 0) y = 0;
	    node.position.x = x;
	    node.position.y = y;
	    nodePositionPost(node);
	}
    }
};

function writeMiniDisplay(title,str) {
    $('#miniDisplayBody')[0].innerHTML = str;
    if(title) {
	$('#miniDisplayTitle')[0].innerHTML = title;
    }
}

function writeJSONDataToMiniDisplay(jsonObj) {
    var str = "";
    for (var key in jsonObj.property) {
	if (key != 'edgeInfo' ) {
	    str = str + key + ": "+ jsonObj.property[key] + "<br>";
	}
    }
    writeMiniDisplay(jsonObj.property.title, str);
}

function setEdgeInfoClickFunction(nodeId, edgeInfo, edgeInfoDiv) {
    edgeInfoDiv.click(function(){ getEvidence(nodeId, edgeInfo); }); 
    edgeInfoDiv.hover(
	function(){edgeInfoDiv.css("box-shadow","black 0 0 50px");  },
	function(){edgeInfoDiv.css("box-shadow","");}
    );
}

function createEdgeInfoDiv(nodeId, edgeInfo) {
    function createEdgeInfoinnerHTML(_edgeInfo) {
	return _edgeInfo.kind + " : " + _edgeInfo.num + ": " + _edgeInfo.direction;
    }
    var edgeInfoDiv = $('<div class="menuContent"/>')
    edgeInfoDiv[0].innerHTML = createEdgeInfoinnerHTML(edgeInfo);
    setEdgeInfoClickFunction(nodeId, edgeInfo, edgeInfoDiv);
    return edgeInfoDiv;
}

function updateEdgeInfoDisplay() {
    var nodeId = CURRENT_DATA.nodeId;
    var node = GRAPH_DATA.nodes[nodeId];
    showEdgeInfoDisplay(node);
}

function showEdgeInfoDisplay(node) {
    removeTraverseMenuBody();
    var tMenuBody = $('#traverseMenuBody');
    var edgeInfoArray = node.property.edgeInfo;
    for (var i=0; i<edgeInfoArray.length; i++) {
	var edgeInfo = edgeInfoArray[i];
	if (!edgeInfo.view) {
	    edgeInfo.view = createEdgeInfoDiv(node.property.id, edgeInfo);
	} else {
	    setEdgeInfoClickFunction(node.property.id, edgeInfo, edgeInfo.view);
	}
	appendElement(tMenuBody, edgeInfo.view);
    }
    updateMenuDisplayHeight();
    $('#accesDocument').click(function(){  });
}

function calcChildrenHeight(childArray) {
    var height = 0;
    for (var i=0; i<childArray.length; i++) {
	height = height + childArray[i].offsetHeight + BASE_MARGIN;
    }
    return height;
}

function appendElement(menuBodyDiv, menuContentDiv) {
    menuBodyDiv.append(menuContentDiv);
}

function removeTraverseMenuBody() {
    $('#traverseMenuBody').children().remove();    
}

function removeStateMenuBody() {
    $('#stateMenuBody').children().remove();    
}

function showMenuBody(menu) {
    var body = $(menu.children()[1]);
    var childArray = body.children();
    $(childArray).css('visibility','visible');
    var height = calcChildrenHeight(childArray);
    menu.css('height', height+'px');    
}

function showStateMenuBody() {
    showMenuBody($('#stateMenu'));
}

function showTraverseMenuBody(node) {
    $('#traverseMenu').css('visibility','visible');;
    showEdgeInfoDisplay(node);
}

function hiddenMenuBody(menu, height) {
    var body = $(menu.children()[1]);
    var childArray = body.children();
    $(childArray).css('visibility','hidden');
    menu.css('height', height+'px');    
}

function hiddenStateMenuBody() {
    var height = DefaultSelectMenuInfo.stateMenuHeight;
    hiddenMenuBody($('#stateMenu'), height);
}

function hiddenTraverseMenuBody() {
    var menu = $('#traverseMenu');
    menu.css('visibility','hidden');
}

var MENU_BORDER_MARGIN = 2*parseInt($('.menu').css('border-top-width').split('px')[0]);
var DefaultSelectMenuInfo = {
    stateMenuHeight : $('#stateMenu')[0].offsetHeight - MENU_BORDER_MARGIN,
    traverseMenuHeight : $('#traverseMenu')[0].offsetHeight - MENU_BORDER_MARGIN
};

function appendStateSelectDiv(body, div, state) {
	div.click(function(){if (!CURRENT_DATA.nodeId) { alert("please click any node.");return; } stateTraversePost(state);  });
	div.hover(
	    function(){div.css("box-shadow","black 0 0 50px");  },
	    function(){div.css("box-shadow","");}
	);
	appendElement(body, div);
}

function clickStateSelect() {
    var flag = $('#stateMenuBody').css('visibility') == 'visible';
    if (flag) {
	hiddenStateMenuBody();
    } else {
	showStateMenuBody();
    }
}

function createStateSelectMenu() {
    removeStateMenuBody();
    var stateMenu = $('#stateMenu');
    var body = $('#stateMenuBody');
    var title = $('#stateMenuTitle');
    title.click(function(){ clickStateSelect(); updateMenuDisplayHeight(); });
    title.hover(
	function(){ title.css("box-shadow","black 0 0 50px");  },
	function(){ title.css("box-shadow","");}
    );
    for (var state in stateObj) {
	var div = $('<div class="menuContent" >'+state+'</div>');
	appendStateSelectDiv(body, div, stateObj[state]);
    }
}

var MARGIN = parseInt($('.menu').css('margin-top').split('px')[0]);
var BASE_MARGIN = 2*MARGIN + 
    parseInt($('.menuDisplayCss').css('border-top-width').split('px')[0])*2;
function updateMenuDisplayHeight() {
    function calcMenuDisplayHeight(menuD, childArray) {
	var menuArray = $('.menu');
	var height = 0;
	for (var i=0; i<menuArray.length; i++) {
	    height = height + menuArray[i].offsetHeight
	}
	return height;
    }
    function updateMenuTop(childArray) {
	var height = 0;
	for (var i=0; i<childArray.length; i++) {
	    childArray[i].style.top = height + 'px';
	    height = height + childArray[i].offsetHeight + MARGIN;
	}
    }
    var menuD =  $('#menuDisplay');
    var menuArray = $('.menu');
    updateMenuTop(menuArray);
    var height = calcMenuDisplayHeight(menuD, menuArray) + BASE_MARGIN;
    menuD.css('height', height + 'px');
}

function closeSelectMenu() {
    hiddenStateMenuBody(); 
    hiddenTraverseMenuBody(); 
    $('#menuDisplay').css('visibility','hidden'); 
}

function showSelectMenu(node) {
    $('#menuDisplay').css('visibility','visible'); 
    showStateMenuBody();
    showTraverseMenuBody(node);
}
 
function init() {
    jsPlumb.importDefaults({
	Connector : [ "Straight", { curviness:50 } ],
	PaintStyle : { strokeStyle:"gray", lineWidth:2 },
	EndpointStyle : {},
	Anchors: ["BottomCenter","TopCenter"],
    });
    var rootDiv = $('#graphMain');
    var rootLeft = rootDiv.offset().left;
    var rootTop = rootDiv.offset().top;
    $('#miniDisplay').css( {
	left: rootLeft + 'px',
	top: rootTop + 'px'
    });
    var heightStr = $('#miniDisplay').css('height').split('px')[0];
    var height = parseInt(heightStr);
    $('#menuDisplay').css({
	left: rootLeft + 'px',
	top: rootTop + height + 50 +'px'
    });
    createStateSelectMenu();
//    hiddenStateMenuBody();
    updateMenuDisplayHeight();
}

function showMiniDisplay(node) {
    CURRENT_DATA.nodeId = node.property.id;
    $("#miniDisplay").css("visibility", "visible");
    writeJSONDataToMiniDisplay(node);
}

var nodeNum = 0;
var OFFSET = 300;
var miniD = $('#miniDisplay')[0].style;
var offsetLeft = parseInt(miniD.width.split('px')[0]);
var offsetTop = parseInt(miniD.height.split('px')[0]);
function calcNewNodePosition() {
    var position = {};
    position = {x: offsetLeft+OFFSET, y: nodeNum*OFFSET + offsetTop / 3};
    nodeNum++;
    return position;
}

function showEdgesAndNodes(graphData,jsonData,kind) {
    var nodes = graphData.nodes;
    var jsonNodes = jsonData.nodes;
    for (var i=0; i<jsonNodes.length; i++) {
	var id = jsonNodes[i].id;
	updateNode(nodes[id]);
    }
    var edges = graphData.edges;
    var jsonEdges = jsonData.edges;
    for (var i=0; i<jsonEdges.length; i++) {
	var edge = edges[jsonEdges[i].id];
	edge.property.kind = kind;
	showEdge(graphData, edge);
    }
    showAllEdge(graphData);
}

function inspectAction(url) {
    $('#accessRequest').click(function(){
	console.log('accesRequest');
	window.open(url, 'accessUrl', "width=600,height=500,resizable=yes,scrollbars=yes");
	$('#popupAccessUrl').css('display','none');
	return false;
    });
    $('#popupAccessUrl').css('display','block');
}

function getInspect(id) {
    $.ajax({
	url:"/aat/aaevidencesiftingmodel.userdesktops/inspect?id="+id,
	success:function(o) { inspectAction(o); },
	type:"GET", cache:true,
	error:function(o) { console.log("getEvidence error : ", o); }
    });
}

function getEvidence(nodeId, edgeInfo) {
    $.ajax({
	url:"/aat/aaevidencesiftingmodel.userdesktops/get?desktopid="+desktopid() +"&id="+nodeId+"&edgeinfoid="+edgeInfo.id,
	success:function(o) { if(!o){return;} parseJSONGraphData(GRAPH_DATA, o); recursiveCalcPosition(GRAPH_DATA, GRAPH_DATA.nodes[nodeId]);  showEdgesAndNodes(GRAPH_DATA, o, edgeInfo.kind);},
	type:"GET", cache:true,
	error:function(o) { console.log("getEvidence error : ", o); }
    });
}

function postToServer(parameter) {
    $.ajax({
	url:"/aat/aaevidencesiftingmodel.userdesktops/update?desktopid="+desktopid()+"&"+parameter,
	success:function(o) {},
	type:"POST", cache:true,
	error:function(o) { console.log("post error : ", o); }
    });
}

var stateObj = {
    accept:"Accepted",
    reject:"Rejected",
    retract:"Retract"
};

function stateTraversePost(state) {
    var id = CURRENT_DATA.nodeId;
    var node = GRAPH_DATA.nodes[id];
    node.property.state = state;
    postToServer("id="+id+"&state="+state);
    showMiniDisplay(node);
    updateNodeElement(node);
}

function nodePositionPost(node) {
    postToServer("id="+node.property.id+"&coordX="+node.position.x+"&coordY="+node.position.y);
}

function createNodeDiv(node) {
    node.view = $("<span class='graphNode'/>");
    if(!node.position) {
	node.position = calcNewNodePosition();
    }
    var div = $("<div class='graphNodeContent' />")[0];
    div.id = node.property.id;
    div.innerHTML = node.property.title;
    node.view[0].appendChild(div);
    return node;
}

var StateColor = {
    Accepted:"#48f",
    Rejected:"#a66",
    Retracted:"#fff"
};

var borderStyle = {
//  kind : 'style',
    Document:'solid',
    Context:'dashed'
};

function createContextMenuObj(node) {
    function _updateInfo(node, state) {
	postToServer("id="+node.property.id+"&state="+state);
	node.property.state = state;
	updateNodeElement(node);
    }
    var bindObj = {
	bindings: {
	    'stateAccept': function(f) {
		_updateInfo(node,"Accepted");
	    },
	    'stateReject': function(f) {
		_updateInfo(node,"Rejected");
	    },
	    'stateRetract': function(f) {
		_updateInfo(node,"Retracted");
	    }
	}
    };
    return bindObj;
}

function returnTraverseMenuFunction(id, edgeInfo) {
    return function(f){ getEvidence(id, edgeInfo);   };
}

var TRAVERSE_LI_ID_NAME = "traverseList";
function createTraverseMenuAndObj(id, edgeInfoArray) {
    var menu = $('#traverseSelectMenu');
    menu.children().remove();
    var bindObj = {};
    bindObj.bindings = {};
    for (var i=0; i<edgeInfoArray.length; i++) {
	var edgeInfo = edgeInfoArray[i];
	var str = edgeInfo.kind +" : " + edgeInfo.num + " : " + edgeInfo.direction;
	var idName = TRAVERSE_LI_ID_NAME + i;
	var divStr = "<li id='"+idName+"' class='contextMenuContent'>"+str+"</li>";
	var div = $(divStr);
	appendElement(menu, div);
	bindObj.bindings[idName] = returnTraverseMenuFunction(id, edgeInfo);
    }
    return bindObj;
}

function returnInspectMenuFunction(id) {
    return function(f) { getInspect(id); };
}

var INSPECT_LI_ID_NAME = 'inspectId'
function createInspectMenuAndObj(node) {
    var bindObj = {};
    bindObj.bindings = {};
    if (node.property.kind != 'Document') return bindObj;
    var menu = $('#inspectMenu');
    menu.children().remove();
    var idName = INSPECT_LI_ID_NAME;
    var str = "access";
    var divStr = "<li id='"+idName+"' class='contextMenuContent'>"+str+"</li>";
    var div = $(divStr);
    appendElement(menu,div);
    bindObj.bindings[idName] = returnInspectMenuFunction(node.property.id);
    return bindObj;
}

function plusBindingsObject(obj1, obj2) {
    var newObj = {};
    newObj.bindings = {};
    var o1 = obj1.bindings;
    var o2 = obj2.bindings;
    if (!o1) return o2;
    if (!o2) return o1;
    for (var key in o1 ) {
	newObj.bindings[key] = o1[key];
    }
    for (var key in o2 ) {
	newObj.bindings[key] = o2[key]
    }
    return newObj;
}

function setInitContextMenu(node,elem) {
    var bindObj = createContextMenuObj(node);
    var tObj = createTraverseMenuAndObj(node.property.id, node.property.edgeInfo);
    var inspectObj = createInspectMenuAndObj(node);
    var o = plusBindingsObject(bindObj, tObj);
    var newObj = plusBindingsObject(o, inspectObj);
    elem.bindObj = newObj;
    elem.menuHTML = $('#selectMenu').clone()[0].innerHTML;
}

function updateContextMenu(elem) {
    removeContextMenu();
    if (!elem.bindObj) return;
    var menu = $('#selectMenu');
    menu[0].innerHTML = elem.menuHTML;
    elem.contextMenu('selectMenu', elem.bindObj);
}

function removeContextMenu() {
    $('#stateSelectMenu').children().remove();
    $('#traverseSelectMenu').children().remove();
}

function updateNodeElement(node) {
    var created = false;
    if(!node.view) {
	/* Make graphNode Element in node.view */
	createNodeDiv(node);
	created = true;
    }
    var div = node.view;
    setInitContextMenu(node,div);
    div.hover(  
	function(){ CURRENT_DATA.nodeId = node.property.id; div.css("box-shadow","white 0 0 50px");  updateContextMenu(div); },
	function(){div.css("box-shadow","");}
    );
    node.view[0].nodeId = node.property.id;
    div.click(function(){ showMiniDisplay(node); showSelectMenu(node);  });
    DragHandler.attach($(node.view)[0]);
    div.css('border-style',borderStyle[node.property.kind]);
    div.css("background", StateColor[node.property.state]||"white");
    /* graphNode border color setting */
//    var kindBorder = {agreeed:"#66a", rejected:"#a66", retracted:#6a6 };
//    div.css("border-color", kindBorder[node.property.state] ||"#58f");
    div.css("border-color","#444");
    div.css({
	left: node.position.x + 'px',
	top: node.position.y + 'px'
    }); 
    var contentDiv = $(div[0].firstChild);
    contentDiv.css("background", StateColor[node.property.state]||"white");
    return created;    
}


function updateNode(node) {
    if(updateNodeElement(node)) {
	var fc = $('#graphRoot')[0].firstChild;
	if(fc) {
	    $('#graphRoot')[0].insertBefore(node.view[0], fc);
	} else {
	    $('#graphRoot').append(node.view);
	}
    }
    nodePositionPost(node);
}

function parseJSONGraphData(memory ,jsonObj) {
    var nodes = jsonObj.nodes;
    for (var i=0; i<nodes.length; i++) {
	var node = nodes[i];
	if (memory.nodes[node.id]) continue;
	memory.nodes[node.id] = {};
	memory.nodes[node.id].in = [];
	memory.nodes[node.id].out = [];
	memory.nodes[node.id].both = [];
	memory.nodes[node.id].property = node;
	if (node.coordX) {
	    memory.nodes[node.id].position = {};
	    memory.nodes[node.id].position.x = node.coordX;
	    memory.nodes[node.id].position.y = node.coordY;
	}
    }
    if (!jsonObj.edges) return memory; 
    var edges = jsonObj.edges;
    for (var i=0; i<edges.length; i++) {
	var edge = edges[i];
	var edgeId = edge.id;
	if (memory.edges[edgeId]) continue;
	memory.edges[edgeId] = {};
	memory.edges[edgeId].property = edge;
	memory.edges[edgeId].visible = false;
	memory.nodes[edge.from].out.push(edgeId);
	memory.nodes[edge.to].in.push(edgeId);
    }
    return memory;
}

function showEdge(graphData, edge) {
    function connectEdge(fromNode, toNode, kind) {
	var c;
	c = jsPlumb.connect({source:fromNode.view[0], target:toNode.view[0]}, arrowConnector);
	//	jsPlumb.select({source:fromNode.view[0]}).removeAllOverlays();
	c.setLabel({label:"<span style='color:#129; font-size:1.5em;'>"+kind+"</span>",cssStyle:""});
	return c;
    }
    if (edge.visible) return;
    var fromNode = graphData.nodes[edge.property.from];
    var toNode = graphData.nodes[edge.property.to];
    if (!fromNode.view && !toNode.view) return;
    var kind = edge.property.kind;
    connectEdge(fromNode, toNode, kind);
    edge.visible = true;
}

function createNodeFromEdge(graphData, edge, baseNode) {
    if(edge.visible) return;
    var fromNode = graphData.nodes[edge.property.from];
    if (!fromNode.view) {
	updateNode(fromNode);
    }
    var toNode = graphData.nodes[edge.property.to];
    if (!toNode.view) {
	updateNode(toNode);
    }
    showEdge(graphData, edge);
}

function getRelationEdgeIds(node) {
    var edgeIds = [];
    for (var i=0; i<node.in.length; i++) edgeIds.push(node.in[i]);
    for (var i=0; i<node.out.length; i++) edgeIds.push(node.out[i]);
    for (var i=0; i<node.both.length; i++) edgeIds.push(node.both[i]);
    return edgeIds;
}

function getRelationNodeIds(graphData, node) {
    var nodes = graphData.nodes;
    var edges = graphData.edges;
    var nodeIds = [];
    for (var i=0; i<node.in.length; i++) {
	var edgeId = node.in[i];
	nodeIds.push(edges[edgeId].property.from);
    }
    for (var i=0; i<node.out.length; i++) {
	var edgeId = node.out[i];
	nodeIds.push(edges[edgeId].property.to);
    }
    for (var i=0; i<node.both.length; i++) {
	var edgeId = node.both[i];
	var fromId = edges[edgeId].property.from;
	var toId = edges[edgeId].property.to;
	if (fromId == node.property.id) {
	    nodeIds.push(toId);
	} else {
	    nodeIds.push(fromId);
	}
    }
    return nodeIds;
}

/*
 * This function output all NODE that are related [node]
 */
function updateRelationNodes(graphData, node) {
    var id = node.property.id;
    var edges = graphData.edges;
    var edgeIds = getRelationEdgeIds(node);
    for (var i=0; i<edgeIds.length; i++ ) {
	createNodeFromEdge(graphData, edges[edgeIds[i]]);
    }
    jsPlumb.removeAllEndpoints();
    jsPlumb.draggable($('.graphNode'));
}

var BASE_THETA = -30;
var BASE_ANGLE = 180;
var BASE_DISTANCE = 180;
function calcChildNodePosition(parent, num) {
    var pX = parent.position.x;
    var pY = parent.position.y;
    var deg = BASE_ANGLE - num * BASE_THETA;
    var theta = deg * (Math.PI / 180);
    var cX = pX - (BASE_DISTANCE * Math.cos(theta));
    var cY = pY - (BASE_DISTANCE * Math.sin(theta));
    return {x:cX, y:cY};
}

function showAllEdge(graphData) {
    jsPlumb.removeAllEndpoints();
    var edges = graphData.edges;
    for (var id in edges) {
	showEdge(graphData, edges[id]);
    }
    jsPlumb.draggable($('.graphNode'));
}

function recursiveCalcPosition(graphData, parentNode) {
    if (!parentNode.position) updateNode(parentNode);
    childNodeIds = getRelationNodeIds(graphData, parentNode);
    /* calcration of childNode position */
    var numCalcChild = 0;
    var childArray = {};
    for (var i=0; i<childNodeIds.length; i++) { 
	var id = childNodeIds[i];
	var childNode = graphData.nodes[id];
	if (childNode.position) {
	    numCalcChild++;
	}
    }
    for (var i=0; i<childNodeIds.length; i++) {
	var id = childNodeIds[i];
	var childNode = graphData.nodes[id];
	childArray[id] = childNode;
	if (!childNode.position) {
	    childNode.position = calcChildNodePosition(parentNode, numCalcChild);
	    numCalcChild++;
	    nodePositionPost(childNode);
	}
    }
    /* calcration of grandchildNode position  */
    for (var id in childArray) {
	var childNode = childArray[id];
	var grandChildIds = getRelationNodeIds(graphData, childNode);
	for (var i=0; i<grandChildIds.length; i++) {
	    var gId = grandChildIds[i];
	    var grandChild = graphData.nodes[gId];
	    if (!grandChild.position) {
 		recursiveCalcPosition(graphData, childNode);
	    }
	}
    }
}

var GRAPH_DATA = new GraphData();
function startUserDesktopUI() {
    function showFirstEvidenceList(graphData) {
	var nodes = graphData.nodes;
	for (var id in nodes) {
	    updateNode(nodes[id]);
	}
    }
    var gData = GRAPH_DATA;
    showFirstEvidenceList(gData);
    showAllEdge(gData);
}

function start() {
    function _start() {
	startUserDesktopUI();
    }
    init();
    $.ajax({
	url:"/aat/aaevidencesiftingmodel.userdesktops/get?desktopid="+desktopid(),
	success:function(o) {	parseJSONGraphData(GRAPH_DATA, o); _start(); },
	type:"GET", cache:false,
	error:function(o) { console.log("first get error : ",o); }
    });
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
	window.onload = func;
    } else {
	window.onload = function() {
	    if (oldonload) {
		oldonload();
	    }
	    func();
	}
    }
}

addLoadEvent(function() {
    beginScript();
});

function beginScript() {
    DragHandler.attach($('#miniDisplay')[0]);
    DragHandler.attach($('#menuDisplay')[0]);
    start();
}

</script>