diff --git a/js/apps/system/_admin/aardvark/APP/GruntFile.js b/js/apps/system/_admin/aardvark/APP/GruntFile.js
index 30d093be75..bd16ca6432 100644
--- a/js/apps/system/_admin/aardvark/APP/GruntFile.js
+++ b/js/apps/system/_admin/aardvark/APP/GruntFile.js
@@ -66,7 +66,7 @@
"frontend/js/lib/sigma.plugins.lasso.js",
"frontend/js/lib/sigma.layout.noverlap.js",
"frontend/js/lib/sigma.layout.fruchtermanReingold.js",
- "frontend/js/lib/sigma.exporters.svg.js",
+ "frontend/js/lib/sigma.exporters.image.js",
"frontend/js/lib/sigma.canvas.edges.labels.curve.js",
"frontend/js/lib/sigma.canvas.edges.labels.curvedArrow.js",
"frontend/js/lib/sigma.canvas.edges.labels.def.js",
diff --git a/js/apps/system/_admin/aardvark/APP/frontend/build/app.min.js b/js/apps/system/_admin/aardvark/APP/frontend/build/app.min.js
index d94d07f217..e506de4ebd 100644
--- a/js/apps/system/_admin/aardvark/APP/frontend/build/app.min.js
+++ b/js/apps/system/_admin/aardvark/APP/frontend/build/app.min.js
@@ -1,14 +1,15 @@
function AbstractAdapter(a,b,c,d,e){"use strict";if(void 0===a)throw"The nodes have to be given.";if(void 0===b)throw"The edges have to be given.";if(void 0===c)throw"An inheriting class has to be given.";if(void 0===d)throw"A reference to the graph viewer has to be given.";e=e||{};var f,g,h,i,j,k=this,l=!1,m={},n={},o={},p={},q=0,r={},s={},t=function(a){void 0!==a.prioList&&g.changePrioList(a.prioList||[])},u=function(a){m.range=a/2,m.start=a/4,m.getStart=function(){return this.start+Math.random()*this.range}},v=function(a){n.range=a/2,n.start=a/4,n.getStart=function(){return this.start+Math.random()*this.range}},w=function(b){var c=p[b]||b,d=$.grep(a,function(a){return a._id===c});if(0===d.length)return!1;if(1===d.length)return d[0];throw"Too many nodes with the same ID, should never happen"},x=function(a){var c=$.grep(b,function(b){return b._id===a});if(0===c.length)return!1;if(1===c.length)return c[0];throw"Too many edges with the same ID, should never happen"},y=function(b,c,d){var e={_data:b,_id:b._id},f=w(e._id);return f?f:(e.x=c||m.getStart(),e.y=d||n.getStart(),e.weight=1,a.push(e),e._outboundCounter=0,e._inboundCounter=0,e)},z=function(a){var b=y(a);return b.x=2*m.start,b.y=2*n.start,b.fixed=!0,b},A=function(){a.length=0,b.length=0,p={},o={},d.cleanUp()},B=function(a){var c,d,e,f=!0,g={_data:a,_id:a._id},i=x(g._id);if(i)return i;if(c=w(a._from),d=w(a._to),!c)throw"Unable to insert Edge, source node not existing "+a._from;if(!d)throw"Unable to insert Edge, target node not existing "+a._to;return g.source=c,g.source._isCommunity?(e=o[g.source._id],g.source=e.getNode(a._from),g.source._outboundCounter++,e.insertOutboundEdge(g),f=!1):c._outboundCounter++,g.target=d,g.target._isCommunity?(e=o[g.target._id],g.target=e.getNode(a._to),g.target._inboundCounter++,e.insertInboundEdge(g),f=!1):d._inboundCounter++,b.push(g),f&&h.call("insertEdge",c._id,d._id),g},C=function(b){var c;for(c=0;c0){var c,d=[];for(c=0;cf&&(c?c.collapse():K(b))},M=function(c){var d=c.getDissolveInfo(),e=d.nodes,g=d.edges.both,i=d.edges.inbound,j=d.edges.outbound;C(c),fi){var b=g.bucketNodes(_.values(a),i);_.each(b,function(a){if(a.nodes.length>1){var b=_.map(a.nodes,function(a){return a._id});I(b,a.reason)}})}},P=function(a,b){f=a,L(),void 0!==b&&b()},Q=function(a){i=a},R=function(a,b){a._expanded=!1;var c=b.removeOutboundEdgesFromNode(a);_.each(c,function(a){j(a),E(a,!0)})},S=function(a){a._expanded=!1,p[a._id]&&o[p[a._id]].collapseNode(a);var b=H(a),c=[];_.each(b,function(b){0===q?(r=b,s=a,c.push(b)):void 0!==a&&(a._id===r.target._id?b.target._id===s._id&&c.push(r):c.push(b),r=b,s=a),q++}),_.each(c,j),q=0},T=function(a){var b=a.getDissolveInfo();C(a),_.each(b.nodes,function(a){delete p[a._id]}),_.each(b.edges.outbound,function(a){j(a),E(a,!0)}),delete o[a._id]},U=function(a,b){a._isCommunity?k.expandCommunity(a,b):(a._expanded=!0,c.loadNode(a._id,b))},V=function(a,b){a._expanded?S(a):U(a,b)};j=function(a){var b,c=a.target;return c._isCommunity?(b=a._target,c.removeInboundEdge(a),b._inboundCounter--,0===b._inboundCounter&&(R(b,c),c.removeNode(b),delete p[b._id]),void(0===c._inboundCounter&&T(c))):(c._inboundCounter--,void(0===c._inboundCounter&&(S(c),C(c))))},i=Number.POSITIVE_INFINITY,g=e.prioList?new NodeReducer(e.prioList):new NodeReducer,h=new WebWorkerWrapper(ModularityJoiner,J),m.getStart=function(){return 0},n.getStart=function(){return 0},this.cleanUp=A,this.setWidth=u,this.setHeight=v,this.insertNode=y,this.insertInitialNode=z,this.insertEdge=B,this.removeNode=C,this.removeEdge=E,this.removeEdgesForNode=F,this.expandCommunity=N,this.setNodeLimit=P,this.setChildLimit=Q,this.checkSizeOfInserted=O,this.checkNodeLimit=L,this.explore=V,this.changeTo=t,this.getPrioList=g.getPrioList,this.dissolveCommunity=M}function ArangoAdapter(a,b,c,d){"use strict";if(void 0===a)throw"The nodes have to be given.";if(void 0===b)throw"The edges have to be given.";if(void 0===c)throw"A reference to the graph viewer has to be given.";if(void 0===d)throw"A configuration with node- and edgeCollection has to be given.";if(void 0===d.graph){if(void 0===d.nodeCollection)throw"The nodeCollection or a graphname has to be given.";if(void 0===d.edgeCollection)throw"The edgeCollection or a graphname has to be given."}var e,f,g,h,i,j=this,k={},l={},m={},n=function(a){h=a},o=function(a){f=a,l.node=l.base+"document?collection="+f},p=function(a){g=a,l.edge=l.base+"edge?collection="+g},q=function(a){$.ajax({cache:!1,type:"GET",async:!1,url:l.graph+"/"+a,contentType:"application/json",success:function(a){o(a.graph.vertices),p(a.graph.edges)}})},r=function(a){console.log(a.baseUrl);var b=a.baseUrl||"";void 0!==a.width&&e.setWidth(a.width),void 0!==a.height&&e.setHeight(a.height),i=void 0!==a.undirected&&a.undirected===!0?"any":"outbound",l.base=b+"_api/",l.cursor=l.base+"cursor",l.graph=l.base+"graph",l.collection=l.base+"collection/",l.document=l.base+"document/",l.any=l.base+"simple/any",a.graph?(q(a.graph),n(a.graph)):(o(a.nodeCollection),p(a.edgeCollection),n(void 0))},s=function(a,b,c){a!==m.getAllGraphs&&(a!==m.connectedEdges&&(b["@nodes"]=f,a!==m.childrenCentrality&&(b.dir=i)),b["@edges"]=g);var d={query:a,bindVars:b};$.ajax({type:"POST",url:l.cursor,data:JSON.stringify(d),contentType:"application/json",dataType:"json",processData:!1,success:function(a){c(a.result)},error:function(a){try{throw console.log(a.statusText),"["+a.errorNum+"] "+a.errorMessage}catch(b){throw"Undefined ERROR"}}})},t=function(a,b){var c=[],d=0,e=function(d){c.push(d.document||{}),c.length===a&&b(c)};for(d=0;a>d;d++)$.ajax({cache:!1,type:"PUT",url:l.any,data:JSON.stringify({collection:f}),contentType:"application/json",success:e})},u=function(b,c){if(0===b.length)return void(c&&c({errorCode:404}));b=b[0];var d={},f=e.insertNode(b[0].vertex),g=a.length;_.each(b,function(b){var c=e.insertNode(b.vertex),f=b.path;g=2&&$.ajax({cache:!1,type:"GET",url:l.collection,contentType:"application/json",dataType:"json",processData:!1,success:function(b){var c=b.collections,d=[],e=[];_.each(c,function(a){a.name.match(/^_/)||(3===a.type?e.push(a.name):2===a.type&&d.push(a.name))}),a(d,e)},error:function(a){throw a.statusText}})},j.getGraphs=function(a){a&&a.length>=1&&s(m.getAllGraphs,{},a)},j.getAttributeExamples=function(a){a&&a.length>=1&&t(10,function(b){var c=_.sortBy(_.uniq(_.flatten(_.map(b,function(a){return _.keys(a)}))),function(a){return a.toLowerCase()});a(c)})},j.getNodeCollection=function(){return f},j.getEdgeCollection=function(){return g},j.getDirection=function(){return i},j.getGraphName=function(){return h},j.setWidth=e.setWidth,j.changeTo=e.changeTo,j.getPrioList=e.getPrioList}function ColourMapper(){"use strict";var a,b={},c={},d=[],e=this,f=0;d.push({back:"#C8E6C9",front:"black"}),d.push({back:"#8aa249",front:"white"}),d.push({back:"#8BC34A",front:"black"}),d.push({back:"#388E3C",front:"white"}),d.push({back:"#4CAF50",front:"white"}),d.push({back:"#212121",front:"white"}),d.push({back:"#727272",front:"white"}),d.push({back:"#B6B6B6",front:"black"}),d.push({back:"#e5f0a3",front:"black"}),d.push({back:"#6c4313",front:"white"}),d.push({back:"#9d8564",front:"white"}),this.getColour=function(g){return void 0===b[g]&&(b[g]=d[f],void 0===c[d[f].back]&&(c[d[f].back]={front:d[f].front,list:[]}),c[d[f].back].list.push(g),f++,f===d.length&&(f=0)),void 0!==a&&a(e.getList()),b[g].back},this.getCommunityColour=function(){return"#333333"},this.getForegroundColour=function(g){return void 0===b[g]&&(b[g]=d[f],void 0===c[d[f].back]&&(c[d[f].back]={front:d[f].front,list:[]}),c[d[f].back].list.push(g),f++,f===d.length&&(f=0)),void 0!==a&&a(e.getList()),b[g].front},this.getForegroundCommunityColour=function(){return"white"},this.reset=function(){b={},c={},f=0,void 0!==a&&a(e.getList())},this.getList=function(){return c},this.setChangeListener=function(b){a=b},this.reset()}function CommunityNode(a,b){"use strict";if(_.isUndefined(a)||!_.isFunction(a.dissolveCommunity)||!_.isFunction(a.checkNodeLimit))throw"A parent element has to be given.";b=b||[];var c,d,e,f,g,h=this,i={},j=[],k=[],l={},m={},n={},o={},p=function(a){return h._expanded?2*a*Math.sqrt(j.length):a},q=function(a){return h._expanded?4*a*Math.sqrt(j.length):a},r=function(a){var b=h.position,c=a.x*b.z+b.x,d=a.y*b.z+b.y,e=a.z*b.z;return{x:c,y:d,z:e}},s=function(a){return h._expanded?r(a._source.position):h.position},t=function(a){return h._expanded?r(a._target.position):h.position},u=function(){var a=document.getElementById(h._id).getBBox();c.attr("transform","translate("+(a.x-5)+","+(a.y-25)+")"),d.attr("width",a.width+10).attr("height",a.height+30),e.attr("width",a.width+10)},v=function(){if(!f){var a=new DomObserverFactory;f=a.createObserver(function(a){_.any(a,function(a){return"transform"===a.attributeName})&&(u(),f.disconnect())})}return f},w=function(){g.stop(),j.length=0,_.each(i,function(a){j.push(a)}),g.start()},x=function(){g.stop(),k.length=0,_.each(l,function(a){k.push(a)}),g.start()},y=function(a){var b=[];return _.each(a,function(a){b.push(a)}),b},z=function(a){return!!i[a]},A=function(){return j},B=function(a){return i[a]},C=function(a){i[a._id]=a,w(),h._size++},D=function(a){_.each(a,function(a){i[a._id]=a,h._size++}),w()},E=function(a){var b=a._id||a;delete i[b],w(),h._size--},F=function(a){var b;return _.has(a,"_id")?b=a._id:(b=a,a=l[b]||m[b]),a.target=a._target,delete a._target,l[b]?(delete l[b],h._outboundCounter++,n[b]=a,void x()):(delete m[b],void h._inboundCounter--)},G=function(a){var b;return _.has(a,"_id")?b=a._id:(b=a,a=l[b]||n[b]),a.source=a._source,delete a._source,delete o[a.source._id][b],l[b]?(delete l[b],h._inboundCounter++,m[b]=a,void x()):(delete n[b],void h._outboundCounter--)},H=function(a){var b=a._id||a,c=[];return _.each(o[b],function(a){G(a),c.push(a)}),delete o[b],c},I=function(a){return a._target=a.target,a.target=h,n[a._id]?(delete n[a._id],h._outboundCounter--,l[a._id]=a,x(),!0):(m[a._id]=a,h._inboundCounter++,!1)},J=function(a){var b=a.source._id;return a._source=a.source,a.source=h,o[b]=o[b]||{},o[b][a._id]=a,m[a._id]?(delete m[a._id],h._inboundCounter--,l[a._id]=a,x(),!0):(h._outboundCounter++,n[a._id]=a,!1)},K=function(){return{nodes:j,edges:{both:k,inbound:y(m),outbound:y(n)}}},L=function(){this._expanded=!0},M=function(){a.dissolveCommunity(h)},N=function(){this._expanded=!1},O=function(a,b){var c=a.select("rect").attr("width"),d=a.append("text").attr("text-anchor","middle").attr("fill",b.getForegroundCommunityColour()).attr("stroke","none");c*=2,c/=3,h._reason&&h._reason.key&&(d.append("tspan").attr("x","0").attr("dy","-4").text(h._reason.key+":"),d.append("tspan").attr("x","0").attr("dy","16").text(h._reason.value)),d.append("tspan").attr("x",c).attr("y","0").attr("fill",b.getCommunityColour()).text(h._size)},P=function(b,c,d,e){var f=b.append("g").attr("stroke",e.getForegroundCommunityColour()).attr("fill",e.getCommunityColour());c(f,9),c(f,6),c(f,3),c(f),f.on("click",function(){h.expand(),a.checkNodeLimit(h),d()}),O(f,e)},Q=function(a,b){var c=a.selectAll(".node").data(j,function(a){return a._id});c.enter().append("g").attr("class","node").attr("id",function(a){return a._id}),c.exit().remove(),c.selectAll("* > *").remove(),b(c)},R=function(a,b){c=a.append("g"),d=c.append("rect").attr("rx","8").attr("ry","8").attr("fill","none").attr("stroke","black"),e=c.append("rect").attr("rx","8").attr("ry","8").attr("height","20").attr("fill","#686766").attr("stroke","none"),c.append("image").attr("id",h._id+"_dissolve").attr("xlink:href","img/icon_delete.png").attr("width","16").attr("height","16").attr("x","5").attr("y","2").attr("style","cursor:pointer").on("click",function(){h.dissolve(),b()}),c.append("image").attr("id",h._id+"_collapse").attr("xlink:href","img/gv_collapse.png").attr("width","16").attr("height","16").attr("x","25").attr("y","2").attr("style","cursor:pointer").on("click",function(){h.collapse(),b()});var f=c.append("text").attr("x","45").attr("y","15").attr("fill","white").attr("stroke","none").attr("text-anchor","left");h._reason&&f.text(h._reason.text),v().observe(document.getElementById(h._id),{subtree:!0,attributes:!0})},S=function(a){if(h._expanded){var b=a.focus(),c=[b[0]-h.position.x,b[1]-h.position.y];a.focus(c),_.each(j,function(b){b.position=a(b),b.position.x/=h.position.z,b.position.y/=h.position.z,b.position.z/=h.position.z}),a.focus(b)}},T=function(a,b,c,d,e){return a.on("click",null),h._expanded?(R(a,d),void Q(a,c,d,e)):void P(a,b,d,e)},U=function(a,b,c){if(h._expanded){var d=a.selectAll(".link"),e=d.select("line");b(e,d),c(d)}},V=function(a,b){var c,d,e=function(a){return a._id};h._expanded&&(d=a.selectAll(".link").data(k,e),d.enter().append("g").attr("class","link").attr("id",e),d.exit().remove(),d.selectAll("* > *").remove(),c=d.append("line"),b(c,d))},W=function(a){H(a)};g=new ForceLayouter({distance:100,gravity:.1,charge:-500,width:1,height:1,nodes:j,links:k}),this._id="*community_"+Math.floor(1e6*Math.random()),b.length>0?(this.x=b[0].x,this.y=b[0].y):(this.x=0,this.y=0),this._size=0,this._inboundCounter=0,this._outboundCounter=0,this._expanded=!1,this._isCommunity=!0,D(b),this.hasNode=z,this.getNodes=A,this.getNode=B,this.getDistance=p,this.getCharge=q,this.insertNode=C,this.insertInboundEdge=I,this.insertOutboundEdge=J,this.removeNode=E,this.removeInboundEdge=F,this.removeOutboundEdge=G,this.removeOutboundEdgesFromNode=H,this.collapseNode=W,this.dissolve=M,this.getDissolveInfo=K,this.collapse=N,this.expand=L,this.shapeNodes=T,this.shapeInnerEdges=V,this.updateInnerEdges=U,this.addDistortion=S,this.getSourcePosition=s,this.getTargetPosition=t}function DomObserverFactory(){"use strict";var a=window.WebKitMutationObserver||window.MutationObserver;this.createObserver=function(b){if(!a)throw"Observer not supported";return new a(b)}}function EdgeShaper(a,b,c){"use strict";var d,e,f,g=this,h=[],i={},j=new ContextMenu("gv_edge_cm"),k=function(a,b){return _.isArray(a)?b[_.find(a,function(a){return b[a]})]:b[a]},l=function(a){if(void 0===a)return[""];"string"!=typeof a&&(a=String(a));var b=a.match(/[\w\W]{1,10}(\s|$)|\S+?(\s|$)/g);return b[0]=$.trim(b[0]),b[1]=$.trim(b[1]),b[0].length>12&&(b[0]=$.trim(a.substring(0,10))+"-",b[1]=$.trim(a.substring(10)),b[1].length>12&&(b[1]=b[1].split(/\W/)[0],b[1].length>12&&(b[1]=b[1].substring(0,10)+"...")),b.length=2),b.length>2&&(b.length=2,b[1]+="..."),b},m=!0,n={},o=function(a){return a._id},p=function(a,b){},q=new ColourMapper,r=function(){q.reset()},s=p,t=p,u=p,v=p,w=function(){f={click:p,dblclick:p,mousedown:p,mouseup:p,mousemove:p,mouseout:p,mouseover:p}},x=function(a,b){return 180*Math.atan2(b.y-a.y,b.x-a.x)/Math.PI},y=function(a,b){var c,d=Math.sqrt((b.y-a.y)*(b.y-a.y)+(b.x-a.x)*(b.x-a.x));return a.x===b.x?d-=18*b.z:(c=Math.abs((b.y-a.y)/(b.x-a.x)),d-=.4>c?Math.abs(d*b.z*45/(b.x-a.x)):Math.abs(d*b.z*18/(b.y-a.y))),d},z=function(a,b){_.each(f,function(a,c){b.on(c,a)})},A=function(a,b){if("update"===a)s=b;else{if(void 0===f[a])throw"Sorry Unknown Event "+a+" cannot be bound.";f[a]=b}},B=function(a){var b,c,d,e;return d=a.source,e=a.target,d._isCommunity?(i[d._id]=d,b=d.getSourcePosition(a)):b=d.position,e._isCommunity?(i[e._id]=e,c=e.getTargetPosition(a)):c=e.position,{s:b,t:c}},C=function(a,b){i={},b.attr("transform",function(a){var b=B(a);return"translate("+b.s.x+", "+b.s.y+")rotate("+x(b.s,b.t)+")"}),a.attr("x2",function(a){var b=B(a);return y(b.s,b.t)})},D=function(a,b){t(a,b),m&&u(a,b),v(a,b),z(a,b),C(a,b)},E=function(a){void 0!==a&&(h=a);var b,c=g.parent.selectAll(".link").data(h,o);c.enter().append("g").attr("class","link").attr("id",o),c.exit().remove(),c.selectAll("* > *").remove(),b=c.append("line"),D(b,c),_.each(i,function(a){a.shapeInnerEdges(d3.select(this),D)}),j.bindMenu($(".link"))},F=function(){var a=g.parent.selectAll(".link"),b=a.select("line");C(b,a),s(a),_.each(i,function(a){a.updateInnerEdges(d3.select(this),C,s)})},G=function(a){switch($("svg defs marker#arrow").remove(),a.type){case EdgeShaper.shapes.NONE:t=p;break;case EdgeShaper.shapes.ARROW:t=function(a,b){a.attr("marker-end","url(#arrow)")},0===d.selectAll("defs")[0].length&&d.append("defs"),d.select("defs").append("marker").attr("id","arrow").attr("refX","10").attr("refY","5").attr("markerUnits","strokeWidth").attr("markerHeight","10").attr("markerWidth","10").attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z");break;default:throw"Sorry given Shape not known!"}},H=function(a){u=_.isFunction(a)?function(b,c){c.append("text").attr("text-anchor","middle").text(a)}:function(b,c){c.append("text").attr("text-anchor","middle").text(function(b){var c=l(k(a,b._data));return c[0]||""})},s=function(a){a.select("text").attr("transform",function(a){var b=B(a);return"translate("+y(b.s,b.t)/2+", -3)"})}},I=function(a){void 0!==a.reset&&a.reset&&w(),_.each(a,function(a,b){"reset"!==b&&A(b,a)})},J=function(a){switch($("svg defs #gradientEdgeColor").remove(),r(),a.type){case"single":v=function(b,c){b.attr("stroke",a.stroke)};break;case"gradient":0===d.selectAll("defs")[0].length&&d.append("defs");var b=d.select("defs").append("linearGradient").attr("id","gradientEdgeColor");b.append("stop").attr("offset","0").attr("stop-color",a.source),b.append("stop").attr("offset","0.4").attr("stop-color",a.source),b.append("stop").attr("offset","0.6").attr("stop-color",a.target),b.append("stop").attr("offset","1").attr("stop-color",a.target),v=function(a,b){a.attr("stroke","url(#gradientEdgeColor)"),a.attr("y2","0.0000000000000001")};break;case"attribute":v=function(b,c){c.attr("stroke",function(b){return q.getColour(b._data[a.key])})};break;default:throw"Sorry given colour-scheme not known"}},K=function(a){void 0!==a.shape&&G(a.shape),void 0!==a.label&&(H(a.label),g.label=a.label),void 0!==a.actions&&I(a.actions),void 0!==a.color&&J(a.color)};for(g.parent=a,w(),d=a;d[0][0]&&d[0][0].ownerSVGElement;)d=d3.select(d[0][0].ownerSVGElement);void 0===b&&(b={color:{type:"single",stroke:"#686766"}}),void 0===b.color&&(b.color={type:"single",stroke:"#686766"}),K(b),_.isFunction(c)&&(o=c),e=d.append("g"),g.changeTo=function(a){K(a),E(),F()},g.drawEdges=function(a){E(a),F()},g.updateEdges=function(){F()},g.reshapeEdges=function(){E()},g.activateLabel=function(a){m=!!a,E()},g.addAnEdgeFollowingTheCursor=function(a,b){return n=e.append("line"),n.attr("stroke","black").attr("id","connectionLine").attr("x1",a).attr("y1",b).attr("x2",a).attr("y2",b),function(a,b){n.attr("x2",a).attr("y2",b)}},g.removeCursorFollowingEdge=function(){n.remove&&(n.remove(),n={})},g.addMenuEntry=function(a,b){j.addEntry(a,b)},g.getLabel=function(){return g.label||""},g.resetColourMap=r}function EventDispatcher(a,b,c){"use strict";var d,e,f,g,h=this,i=function(b){if(void 0===b.shaper&&(b.shaper=a),d.checkNodeEditorConfig(b)){var c=new d.InsertNode(b),e=new d.PatchNode(b),f=new d.DeleteNode(b);h.events.CREATENODE=function(a,b,d,e){var f;return f=_.isFunction(a)?a():a,function(){c(f,b,d,e)}},h.events.PATCHNODE=function(a,b,c){if(!_.isFunction(b))throw"Please give a function to extract the new node data";return function(){e(a,b(),c)}},h.events.DELETENODE=function(a){return function(b){f(b,a)}}}},j=function(a){if(void 0===a.shaper&&(a.shaper=b),d.checkEdgeEditorConfig(a)){var c=new d.InsertEdge(a),e=new d.PatchEdge(a),f=new d.DeleteEdge(a),g=null,i=!1;h.events.STARTCREATEEDGE=function(a){return function(b){var c=d3.event||window.event;g=b,i=!1,void 0!==a&&a(b,c),c.stopPropagation()}},h.events.CANCELCREATEEDGE=function(a){return function(){g=null,void 0===a||i||a()}},h.events.FINISHCREATEEDGE=function(a){return function(b){null!==g&&b!==g&&(c(g,b,a),i=!0)}},h.events.PATCHEDGE=function(a,b,c){if(!_.isFunction(b))throw"Please give a function to extract the new node data";return function(){e(a,b(),c)}},h.events.DELETEEDGE=function(a){return function(b){f(b,a)}}}},k=function(){g=g||$("svg"),g.unbind(),_.each(e,function(a,b){g.bind(b,function(c){_.each(a,function(a){a(c)}),f[b]&&f[b](c)})})};if(void 0===a)throw"NodeShaper has to be given.";if(void 0===b)throw"EdgeShaper has to be given.";d=new EventLibrary,e={click:[],dblclick:[],mousedown:[],mouseup:[],mousemove:[],mouseout:[],mouseover:[]},f={},h.events={},void 0!==c&&(void 0!==c.expand&&d.checkExpandConfig(c.expand)&&(h.events.EXPAND=new d.Expand(c.expand),a.setGVStartFunction(function(){c.expand.reshapeNodes(),c.expand.startCallback()})),void 0!==c.drag&&d.checkDragConfig(c.drag)&&(h.events.DRAG=d.Drag(c.drag)),void 0!==c.nodeEditor&&i(c.nodeEditor),void 0!==c.edgeEditor&&j(c.edgeEditor)),Object.freeze(h.events),h.bind=function(c,d,e){if(void 0===e||!_.isFunction(e))throw"You have to give a function that should be bound as a third argument";var g={};switch(c){case"nodes":g[d]=e,a.changeTo({actions:g});break;case"edges":g[d]=e,b.changeTo({actions:g});break;case"svg":f[d]=e,k();break;default:if(void 0===c.bind)throw'Sorry cannot bind to object. Please give either "nodes", "edges" or a jQuery-selected DOM-Element';c.unbind(d),c.bind(d,e)}},h.rebind=function(c,d){switch(d=d||{},d.reset=!0,c){case"nodes":a.changeTo({actions:d});break;case"edges":b.changeTo({actions:d});break;case"svg":f={},_.each(d,function(a,b){"reset"!==b&&(f[b]=a)}),k();break;default:throw'Sorry cannot rebind to object. Please give either "nodes", "edges" or "svg"'}},h.fixSVG=function(a,b){if(void 0===e[a])throw"Sorry unkown event";e[a].push(b),k()},Object.freeze(h.events)}function EventLibrary(){"use strict";var a=this;this.checkExpandConfig=function(a){if(void 0===a.startCallback)throw"A callback to the Start-method has to be defined";if(void 0===a.adapter||void 0===a.adapter.explore)throw"An adapter to load data has to be defined";if(void 0===a.reshapeNodes)throw"A callback to reshape nodes has to be defined";return!0},this.Expand=function(b){a.checkExpandConfig(b);var c=b.startCallback,d=b.adapter.explore,e=b.reshapeNodes;return function(a){d(a,c),e(),c()}},this.checkDragConfig=function(a){if(void 0===a.layouter)throw"A layouter has to be defined";if(void 0===a.layouter.drag||!_.isFunction(a.layouter.drag))throw"The layouter has to offer a drag function";return!0},this.Drag=function(b){return a.checkDragConfig(b),b.layouter.drag},this.checkNodeEditorConfig=function(a){if(void 0===a.adapter)throw"An adapter has to be defined";if(void 0===a.shaper)throw"A node shaper has to be defined";return!0},this.checkEdgeEditorConfig=function(a){if(void 0===a.adapter)throw"An adapter has to be defined";if(void 0===a.shaper)throw"An edge Shaper has to be defined";return!0},this.InsertNode=function(b){a.checkNodeEditorConfig(b);var c=b.adapter,d=b.shaper;return function(a,b,e,f){var g,h;_.isFunction(a)&&!b?(g=a,h={}):(g=b,h=a),c.createNode(h,function(a){d.reshapeNodes(),g(a)},e,f)}},this.PatchNode=function(b){a.checkNodeEditorConfig(b);var c=b.adapter,d=b.shaper;return function(a,b,e){c.patchNode(a,b,function(a){d.reshapeNodes(),e(a)})}},this.DeleteNode=function(b){a.checkNodeEditorConfig(b);var c=b.adapter,d=b.shaper;return function(a,b){c.deleteNode(a,function(){d.reshapeNodes(),b()})}},this.SelectNodeCollection=function(b){a.checkNodeEditorConfig(b);var c=b.adapter;if(!_.isFunction(c.useNodeCollection))throw"The adapter has to support collection changes";return function(a,b){c.useNodeCollection(a),b()}},this.InsertEdge=function(b){a.checkEdgeEditorConfig(b);var c=b.adapter,d=b.shaper;return function(a,b,e){c.createEdge({source:a,target:b},function(a){d.reshapeEdges(),e(a)})}},this.PatchEdge=function(b){a.checkEdgeEditorConfig(b);var c=b.adapter,d=b.shaper;return function(a,b,e){c.patchEdge(a,b,function(a){d.reshapeEdges(),e(a)})}},this.DeleteEdge=function(b){a.checkEdgeEditorConfig(b);var c=b.adapter,d=b.shaper;return function(a,b){c.deleteEdge(a,function(){d.reshapeEdges(),b()})}}}function ForceLayouter(a){"use strict";var b=this,c=d3.layout.force(),d=a.charge||-600,e=a.distance||80,f=a.gravity||.01,g=function(a){var b=0;return b+=a.source._isCommunity?a.source.getDistance(e):e,b+=a.target._isCommunity?a.target.getDistance(e):e},h=function(a){return a._isCommunity?a.getCharge(d):d},i=a.onUpdate||function(){},j=a.width||880,k=a.height||680,l=function(a){a.distance&&(e=a.distance),a.gravity&&c.gravity(a.gravity),a.charge&&(d=a.charge)};if(void 0===a.nodes)throw"No nodes defined";if(void 0===a.links)throw"No links defined";c.nodes(a.nodes),c.links(a.links),c.size([j,k]),c.linkDistance(g),c.gravity(f),c.charge(h),c.on("tick",function(){}),b.start=function(){c.start()},b.stop=function(){c.stop()},b.drag=c.drag,b.setCombinedUpdateFunction=function(a,d,e){void 0!==e?(i=function(){c.alpha()<.1&&(a.updateNodes(),d.updateEdges(),e(),c.alpha()<.05&&b.stop())},c.on("tick",i)):(i=function(){c.alpha()<.1&&(a.updateNodes(),d.updateEdges(),c.alpha()<.05&&b.stop())},c.on("tick",i))},b.changeTo=function(a){l(a)},b.changeWidth=function(a){j=a,c.size([j,k])}}function FoxxAdapter(a,b,c,d,e){"use strict";if(void 0===a)throw"The nodes have to be given.";if(void 0===b)throw"The edges have to be given.";if(void 0===c)throw"The route has to be given.";if(void 0===d)throw"A reference to the graph viewer has to be given.";e=e||{};var f,g=this,h={},i={},j=c,k={cache:!1,contentType:"application/json",dataType:"json",processData:!1,error:function(a){try{throw console.log(a.statusText),"["+a.errorNum+"] "+a.errorMessage}catch(b){throw console.log(b),"Undefined ERROR"}}},l=function(){i.query={get:function(a,b){var c=$.extend(k,{type:"GET",url:j+"/query/"+a,success:b});$.ajax(c)}},i.nodes={post:function(a,b){var c=$.extend(k,{type:"POST",url:j+"/nodes",data:JSON.stringify(a),success:b});$.ajax(c)},put:function(a,b,c){var d=$.extend(k,{type:"PUT",url:j+"/nodes/"+a,data:JSON.stringify(b),success:c});$.ajax(d)},del:function(a,b){var c=$.extend(k,{type:"DELETE",url:j+"/nodes/"+a,success:b});$.ajax(c)}},i.edges={post:function(a,b){var c=$.extend(k,{type:"POST",url:j+"/edges",data:JSON.stringify(a),success:b});$.ajax(c)},put:function(a,b,c){var d=$.extend(k,{type:"PUT",
url:j+"/edges/"+a,data:JSON.stringify(b),success:c});$.ajax(d)},del:function(a,b){var c=$.extend(k,{type:"DELETE",url:j+"/edges/"+a,success:b});$.ajax(c)}},i.forNode={del:function(a,b){var c=$.extend(k,{type:"DELETE",url:j+"/edges/forNode/"+a,success:b});$.ajax(c)}}},m=function(a,b,c){i[a].get(b,c)},n=function(a,b,c){i[a].post(b,c)},o=function(a,b,c){i[a].del(b,c)},p=function(a,b,c,d){i[a].put(b,c,d)},q=function(a){void 0!==a.width&&f.setWidth(a.width),void 0!==a.height&&f.setHeight(a.height)},r=function(b,c){var d={},e=b.first,g=a.length;e=f.insertNode(e),_.each(b.nodes,function(b){b=f.insertNode(b),g=l.TOTAL_NODES?$(".infoField").hide():$(".infoField").show());var e=t(l.NODES_TO_DISPLAY,d[c]);if(e.length>0)return _.each(e,function(a){l.randomNodes.push(a)}),void l.loadInitialNode(e[0]._id,a)}a({errorCode:404})},l.loadInitialNode=function(a,b){e.cleanUp(),l.loadNode(a,v(b))},l.getRandomNodes=function(){var a=[],b=[];l.definedNodes.length>0&&_.each(l.definedNodes,function(a){b.push(a)}),l.randomNodes.length>0&&_.each(l.randomNodes,function(a){b.push(a)});var c=0;return _.each(b,function(b){c0?_.each(d,function(a){s(o.traversal(k),{example:a.vertex._id},function(a){_.each(a,function(a){c.push(a)}),u(c,b)})}):s(o.traversal(k),{example:a},function(a){u(a,b)})})},l.loadNodeFromTreeByAttributeValue=function(a,b,c){var d={},e=o.traversalAttributeValue(k,d,f,a,b);s(e,d,function(a){u(a,c)})},l.getNodeExampleFromTreeByAttributeValue=function(a,b,c){var d,g=o.travesalAttributeValue(k,d,f,a,b);s(g,d,function(d){if(0===d.length)throw arangoHelper.arangoError("Graph error","no nodes found"),"No suitable nodes have been found.";_.each(d,function(d){if(d.vertex[a]===b){var f={};f._key=d.vertex._key,f._id=d.vertex._id,f._rev=d.vertex._rev,e.insertNode(f),c(f)}})})},l.loadAdditionalNodeByAttributeValue=function(a,b,c){l.getNodeExampleFromTreeByAttributeValue(a,b,c)},l.loadInitialNodeByAttributeValue=function(a,b,c){e.cleanUp(),l.loadNodeFromTreeByAttributeValue(a,b,v(c))},l.requestCentralityChildren=function(a,b){s(o.childrenCentrality,{id:a},function(a){b(a[0])})},l.createEdge=function(a,b){var c={};c._from=a.source._id,c._to=a.target._id,$.ajax({cache:!1,type:"POST",url:n.edges+i,data:JSON.stringify(c),dataType:"json",contentType:"application/json",processData:!1,success:function(a){if(a.error===!1){var d,f=a.edge;f._from=c._from,f._to=c._to,d=e.insertEdge(f),b(d)}},error:function(a){var b="";try{b=JSON.parse(a.responseText).errorMessage+" ("+JSON.parse(a.responseText).errorNum+")",arangoHelper.arangoError(a.statusText,b)}catch(c){throw a.statusText}}})},l.deleteEdge=function(a,b){$.ajax({cache:!1,type:"DELETE",url:n.edges+a._id,contentType:"application/json",dataType:"json",processData:!1,success:function(){e.removeEdge(a),void 0!==b&&_.isFunction(b)&&b()},error:function(a){var b="";try{b=JSON.parse(a.responseText).errorMessage+" ("+JSON.parse(a.responseText).errorNum+")",arangoHelper.arangoError(a.statusText,b)}catch(c){throw a.statusText}}})},l.patchEdge=function(a,b,c){$.ajax({cache:!1,type:"PUT",url:n.edges+a._id,data:JSON.stringify(b),dataType:"json",contentType:"application/json",processData:!1,success:function(){a._data=$.extend(a._data,b),c()},error:function(a){var b="";try{b=JSON.parse(a.responseText).errorMessage+" ("+JSON.parse(a.responseText).errorNum+")",arangoHelper.arangoError(a.statusText,b)}catch(c){throw a.statusText}}})},l.createNode=function(a,b){$.ajax({cache:!1,type:"POST",url:n.vertices+g,data:JSON.stringify(a),dataType:"json",contentType:"application/json",processData:!1,success:function(c){c.error===!1&&(a._key=c.vertex._key,a._id=c.vertex._id,a._rev=c.vertex._rev,e.insertNode(a),b(a))},error:function(a){var b="";try{b=JSON.parse(a.responseText).errorMessage+" ("+JSON.parse(a.responseText).errorNum+")",arangoHelper.arangoError(a.statusText,b)}catch(c){throw a.statusText}}})},l.deleteNode=function(a,b){$.ajax({cache:!1,type:"DELETE",url:n.vertices+a._id,dataType:"json",contentType:"application/json",processData:!1,success:function(){e.removeEdgesForNode(a),e.removeNode(a),void 0!==b&&_.isFunction(b)&&b()},error:function(a){var b="";try{b=JSON.parse(a.responseText).errorMessage+" ("+JSON.parse(a.responseText).errorNum+")",arangoHelper.arangoError(a.statusText,b)}catch(c){throw a.statusText}}})},l.patchNode=function(a,b,c){$.ajax({cache:!1,type:"PUT",url:n.vertices+a._id,data:JSON.stringify(b),dataType:"json",contentType:"application/json",processData:!1,success:function(){a._data=$.extend(a._data,b),c(a)},error:function(a){throw a.statusText}})},l.changeToGraph=function(a,b){e.cleanUp(),q(a),void 0!==b&&(k=b===!0?"any":"outbound")},l.setNodeLimit=function(a,b){e.setNodeLimit(a,b)},l.setChildLimit=function(a){e.setChildLimit(a)},l.expandCommunity=function(a,b){e.expandCommunity(a),void 0!==b&&b()},l.getGraphs=function(a){a&&a.length>=1&&s(o.getAllGraphs,{},a)},l.getAttributeExamples=function(a){if(a&&a.length>=1){var b,c=[],d=_.shuffle(l.getNodeCollections());for(b=0;b0&&(c=c.concat(_.flatten(_.map(e,function(a){return _.keys(a)}))))}c=_.sortBy(_.uniq(c),function(a){return a.toLowerCase()}),a(c)}},l.getEdgeCollections=function(){return h},l.getSelectedEdgeCollection=function(){return i},l.useEdgeCollection=function(a){if(!_.contains(h,a))throw"Collection "+a+" is not available in the graph.";i=a},l.getNodeCollections=function(){return f},l.getSelectedNodeCollection=function(){return g},l.useNodeCollection=function(a){if(!_.contains(f,a))throw"Collection "+a+" is not available in the graph.";g=a},l.getDirection=function(){return k},l.getGraphName=function(){return j},l.setWidth=e.setWidth,l.changeTo=e.changeTo,l.getPrioList=e.getPrioList}function JSONAdapter(a,b,c,d,e,f){"use strict";var g=this,h={},i={},j=new AbstractAdapter(b,c,this,d);h.range=e/2,h.start=e/4,h.getStart=function(){return this.start+Math.random()*this.range},i.range=f/2,i.start=f/4,i.getStart=function(){return this.start+Math.random()*this.range},g.loadNode=function(a,b){g.loadNodeFromTreeById(a,b)},g.loadInitialNode=function(b,c){var d=a+b+".json";j.cleanUp(),d3.json(d,function(a,d){void 0!==a&&null!==a&&console.log(a);var e=j.insertInitialNode(d);g.requestCentralityChildren(b,function(a){e._centrality=a}),_.each(d.children,function(a){var b=j.insertNode(a),c={_from:e._id,_to:b._id,_id:e._id+"-"+b._id};j.insertEdge(c),g.requestCentralityChildren(b._id,function(a){b._centrality=a}),delete b._data.children}),delete e._data.children,c&&c(e)})},g.loadNodeFromTreeById=function(b,c){var d=a+b+".json";d3.json(d,function(a,d){void 0!==a&&null!==a&&console.log(a);var e=j.insertNode(d);g.requestCentralityChildren(b,function(a){e._centrality=a}),_.each(d.children,function(a){var b=j.insertNode(a),c={_from:e._id,_to:b._id,_id:e._id+"-"+b._id};j.insertEdge(c),g.requestCentralityChildren(b._id,function(a){e._centrality=a}),delete b._data.children}),delete e._data.children,c&&c(e)})},g.requestCentralityChildren=function(b,c){var d=a+b+".json";d3.json(d,function(a,b){void 0!==a&&null!==a&&console.log(a),void 0!==c&&c(void 0!==b.children?b.children.length:0)})},g.loadNodeFromTreeByAttributeValue=function(a,b,c){throw"Sorry this adapter is read-only"},g.loadInitialNodeByAttributeValue=function(a,b,c){throw"Sorry this adapter is read-only"},g.createEdge=function(a,b){throw"Sorry this adapter is read-only"},g.deleteEdge=function(a,b){throw"Sorry this adapter is read-only"},g.patchEdge=function(a,b,c){throw"Sorry this adapter is read-only"},g.createNode=function(a,b){throw"Sorry this adapter is read-only"},g.deleteNode=function(a,b){throw"Sorry this adapter is read-only"},g.patchNode=function(a,b,c){throw"Sorry this adapter is read-only"},g.setNodeLimit=function(a,b){},g.setChildLimit=function(a){},g.expandCommunity=function(a,b){},g.setWidth=function(){},g.explore=j.explore}function ModularityJoiner(){"use strict";var a={},b=Array.prototype.forEach,c=Object.keys,d=Array.isArray,e=Object.prototype.toString,f=Array.prototype.indexOf,g=Array.prototype.map,h=Array.prototype.some,i={isArray:d||function(a){return"[object Array]"===e.call(a)},isFunction:function(a){return"function"==typeof a},isString:function(a){return"[object String]"===e.call(a)},each:function(c,d,e){if(null!==c&&void 0!==c){var f,g,h;if(b&&c.forEach===b)c.forEach(d,e);else if(c.length===+c.length){for(f=0,g=c.length;g>f;f++)if(d.call(e,c[f],f,c)===a)return}else for(h in c)if(c.hasOwnProperty(h)&&d.call(e,c[h],h,c)===a)return}},keys:c||function(a){if("object"!=typeof a||Array.isArray(a))throw new TypeError("Invalid object");var b,c=[];for(b in a)a.hasOwnProperty(b)&&(c[c.length]=b);return c},min:function(a,b,c){if(!b&&i.isArray(a)&&a[0]===+a[0]&&a.length<65535)return Math.min.apply(Math,a);if(!b&&i.isEmpty(a))return 1/0;var d={computed:1/0,value:1/0};return i.each(a,function(a,e,f){var g=b?b.call(c,a,e,f):a;gc&&(c=a,b=d)}),0>c?void delete q[a]:void(q[a]=b)},t=function(a,b){s(b)},u=function(a,b){return b>a?p[a]&&p[a][b]:p[b]&&p[b][a]},v=function(a,b){return b>a?p[a][b]:p[b][a]},w=function(a,b,c){return b>a?(p[a]=p[a]||{},void(p[a][b]=c)):(p[b]=p[b]||{},void(p[b][a]=c))},x=function(a,b){if(b>a){if(!p[a])return;return delete p[a][b],void(i.isEmpty(p[a])&&delete p[a])}a!==b&&x(b,a)},y=function(a,b){var c,d;return b>a?u(a,b)?(d=v(a,b),q[a]===b?void s(a):u(a,q[a])?(c=v(a,q[a]),void(d>c&&(q[a]=b))):void s(a)):void s(a):void(a!==b&&y(b,a))},z=function(a,b){o[a]._in+=o[b]._in,o[a]._out+=o[b]._out,delete o[b]},A=function(a,b){j[a]=j[a]||{},j[a][b]=(j[a][b]||0)+1,k[b]=k[b]||{},k[b][a]=(k[b][a]||0)+1,l[a]=l[a]||{_in:0,_out:0},l[b]=l[b]||{_in:0,_out:0},l[a]._out++,l[b]._in++,m++,n=Math.pow(m,-1)},B=function(a,b){j[a]&&(j[a][b]--,0===j[a][b]&&delete j[a][b],k[b][a]--,0===k[b][a]&&delete k[b][a],l[a]._out--,l[b]._in--,m--,n=m>0?Math.pow(m,-1):0,i.isEmpty(j[a])&&delete j[a],i.isEmpty(k[b])&&delete k[b],0===l[a]._in&&0===l[a]._out&&delete l[a],0===l[b]._in&&0===l[b]._out&&delete l[b])},C=function(){return o={},i.each(l,function(a,b){o[b]={_in:a._in/m,_out:a._out/m}}),o},D=function(a,b){return o[a]._out*o[b]._in+o[a]._in*o[b]._out},E=function(a){var b=i.keys(j[a]||{}),c=i.keys(k[a]||{});return i.union(b,c)},F=function(){p={},i.each(j,function(a,b){var c=k[b]||{},d=E(b);i.each(d,function(d){var e,f=a[d]||0;f+=c[d]||0,e=f*n-D(b,d),e>0&&w(b,d,e)})})},G=function(){return q={},i.each(p,t),q},H=function(a,b,c){var d;return u(c,a)?(d=v(c,a),u(c,b)?(d+=v(c,b),w(c,a,d),x(c,b),y(c,a),void y(c,b)):(d-=D(c,b),0>d&&x(c,a),void y(c,a))):void(u(c,b)&&(d=v(c,b),d-=D(c,a),d>0&&w(c,a,d),y(c,a),x(c,b),y(c,b)))},I=function(a,b){i.each(p,function(c,d){return d===a||d===b?void i.each(c,function(c,d){return d===b?(x(a,b),void y(a,b)):void H(a,b,d)}):void H(a,b,d)})},J=function(){return j},K=function(){return q},L=function(){return p},M=function(){return o},N=function(){return r},O=function(){var a,b,c=Number.NEGATIVE_INFINITY;return i.each(q,function(d,e){c
=c?null:{sID:b,lID:a,val:c}},P=function(a){var b,c=Number.NEGATIVE_INFINITY;return i.each(a,function(a){a.q>c&&(c=a.q,b=a.nodes)}),b},Q=function(){C(),F(),G(),r={}},R=function(a){var b=a.sID,c=a.lID,d=a.val;r[b]=r[b]||{nodes:[b],q:0},r[c]?(r[b].nodes=r[b].nodes.concat(r[c].nodes),r[b].q+=r[c].q,delete r[c]):r[b].nodes.push(c),r[b].q+=d,I(b,c),z(b,c)},S=function(a,b,c){if(0===c.length)return!0;var d=[];return i.each(c,function(c){a[c]===Number.POSITIVE_INFINITY&&(a[c]=b,d=d.concat(E(c)))}),S(a,b+1,d)},T=function(a){var b={};if(i.each(j,function(a,c){b[c]=Number.POSITIVE_INFINITY}),b[a]=0,S(b,1,E(a)))return b;throw"FAIL!"},U=function(a){return function(b){return a[b]}},V=function(a,b){var c,d={},e=[],f={},g=function(a,b){var c=f[i.min(a,U(f))],e=f[i.min(b,U(f))],g=e-c;return 0===g&&(g=d[b[b.length-1]].q-d[a[a.length-1]].q),g};for(Q(),c=O();null!==c;)R(c),c=O();return d=N(),void 0!==b?(i.each(d,function(a,c){i.contains(a.nodes,b)&&delete d[c]}),e=i.pluck(i.values(d),"nodes"),f=T(b),e.sort(g),e[0]):P(d)};this.insertEdge=A,this.deleteEdge=B,this.getAdjacencyMatrix=J,this.getHeap=K,this.getDQ=L,this.getDegrees=M,this.getCommunities=N,this.getBest=O,this.setup=Q,this.joinCommunity=R,this.getCommunity=V}function NodeReducer(a){"use strict";a=a||[];var b=function(a,b){a.push(b)},c=function(a,b){if(!a.reason.example)return a.reason.example=b,1;var c=b._data||{},d=a.reason.example._data||{},e=_.union(_.keys(d),_.keys(c)),f=0,g=0;return _.each(e,function(a){void 0!==d[a]&&void 0!==c[a]&&(f++,d[a]===c[a]&&(f+=4))}),g=5*e.length,g++,f++,f/g},d=function(){return a},e=function(b){a=b},f=function(b,c){var d={},e=[];return _.each(b,function(b){var c,e,f=b._data,g=0;for(g=0;gd;d++){if(g[d]=g[d]||{reason:{type:"similar",text:"Similar Nodes"},nodes:[]},c(g[d],a)>h)return void b(g[d].nodes,a);i>g[d].nodes.length&&(f=d,i=g[d].nodes.length)}b(g[f].nodes,a)}),g):f(d,e)};this.bucketNodes=g,this.changePrioList=e,this.getPrioList=d}function NodeShaper(a,b,c){"use strict";var d,e,f=this,g=[],h=!0,i=new ContextMenu("gv_node_cm"),j=function(a,b){return _.isArray(a)?b[_.find(a,function(a){return b[a]})]:b[a]},k=function(a){if(void 0===a)return[""];"string"!=typeof a&&(a=String(a));var b=a.match(/[\w\W]{1,10}(\s|$)|\S+?(\s|$)/g);return b[0]=$.trim(b[0]),b[1]=$.trim(b[1]),b[0].length>12&&(b[0]=$.trim(a.substring(0,10)),b[1]=$.trim(a.substring(10)),b[1].length>12&&(b[1]=b[1].split(/\W/)[0],b[1].length>2&&(b[1]=b[1].substring(0,5)+"...")),b.length=2),b.length>2&&(b.length=2,b[1]+="..."),b},l=function(a){},m=l,n=function(a){return{x:a.x,y:a.y,z:1}},o=n,p=function(){_.each(g,function(a){a.position=o(a),a._isCommunity&&a.addDistortion(o)})},q=new ColourMapper,r=function(){q.reset()},s=function(a){return a._id},t=l,u=l,v=l,w=function(){return"black"},x=function(){f.parent.selectAll(".node").on("mousedown.drag",null),d={click:l,dblclick:l,drag:l,mousedown:l,mouseup:l,mousemove:l,mouseout:l,mouseover:l},e=l},y=function(a){_.each(d,function(b,c){"drag"===c?a.call(b):a.on(c,b)})},z=function(a){var b=a.filter(function(a){return a._isCommunity}),c=a.filter(function(a){return!a._isCommunity});u(c),b.each(function(a){a.shapeNodes(d3.select(this),u,z,m,q)}),h&&v(c),t(c),y(c),p()},A=function(a,b){if("update"===a)e=b;else{if(void 0===d[a])throw"Sorry Unknown Event "+a+" cannot be bound.";d[a]=b}},B=function(){var a=f.parent.selectAll(".node");p(),a.attr("transform",function(a){return"translate("+a.position.x+","+a.position.y+")scale("+a.position.z+")"}),e(a)},C=function(a){void 0!==a&&(g=a);var b=f.parent.selectAll(".node").data(g,s);b.enter().append("g").attr("class",function(a){return a._isCommunity?"node communitynode":"node"}).attr("id",s),b.exit().remove(),b.selectAll("* > *").remove(),z(b),B(),i.bindMenu($(".node"))},D=function(a){var b,c,d,e,f,g,h;switch(a.type){case NodeShaper.shapes.NONE:u=l;break;case NodeShaper.shapes.CIRCLE:b=a.radius||25,u=function(a,c){a.append("circle").attr("r",b),c&&a.attr("cx",-c).attr("cy",-c)};break;case NodeShaper.shapes.RECT:c=a.width||90,d=a.height||36,e=_.isFunction(c)?function(a){return-(c(a)/2)}:function(a){return-(c/2)},f=_.isFunction(d)?function(a){return-(d(a)/2)}:function(){return-(d/2)},u=function(a,b){b=b||0,a.append("rect").attr("width",c).attr("height",d).attr("x",function(a){return e(a)-b}).attr("y",function(a){return f(a)-b}).attr("rx","8").attr("ry","8")};break;case NodeShaper.shapes.IMAGE:c=a.width||32,d=a.height||32,g=a.fallback||"",h=a.source||g,e=_.isFunction(c)?function(a){return-(c(a)/2)}:-(c/2),f=_.isFunction(d)?function(a){return-(d(a)/2)}:-(d/2),u=function(a){var b=a.append("image").attr("width",c).attr("height",d).attr("x",e).attr("y",f);_.isFunction(h)?b.attr("xlink:href",h):b.attr("xlink:href",function(a){return a._data[h]?a._data[h]:g})};break;case void 0:break;default:throw"Sorry given Shape not known!"}},E=function(a){var b=[];_.each(a,function(a){b=$(a).find("text"),$(a).css("width","90px"),$(a).css("height","36px"),$(a).textfill({innerTag:"text",maxFontPixels:16,minFontPixels:10,explicitWidth:90,explicitHeight:36})})},F=function(a){v=_.isFunction(a)?function(b){var c=b.append("text").attr("text-anchor","middle").attr("fill",w).attr("stroke","none");c.each(function(b){var c=k(a(b)),d=c[0];2===c.length&&(d+=c[1]),d.length>15&&(d=d.substring(0,13)+"..."),void 0!==d&&""!==d||(d="ATTR NOT SET"),d3.select(this).append("tspan").attr("x","0").attr("dy","5").text(d)}),E(b)}:function(b){var c=b.append("text").attr("text-anchor","middle").attr("fill",w).attr("stroke","none");c.each(function(b){var c=k(j(a,b._data)),d=c[0];2===c.length&&(d+=c[1]),d.length>15&&(d=d.substring(0,13)+"..."),void 0!==d&&""!==d||(d="ATTR NOT SET"),d3.select(this).append("tspan").attr("x","0").attr("dy","5").text(d)}),E(b)}},G=function(a){void 0!==a.reset&&a.reset&&x(),_.each(a,function(a,b){"reset"!==b&&A(b,a)})},H=function(a){switch(r(),a.type){case"single":t=function(b){b.attr("fill",a.fill)},w=function(b){return a.stroke};break;case"expand":t=function(b){b.attr("fill",function(b){return b._expanded?a.expanded:a.collapsed})},w=function(a){return"white"};break;case"attribute":t=function(b){b.attr("fill",function(b){return void 0===b._data?q.getCommunityColour():q.getColour(j(a.key,b._data))}).attr("stroke",function(a){return a._expanded?"#fff":"transparent"}).attr("fill-opacity",function(a){return a._expanded?"1":"0.3"})},w=function(b){return void 0===b._data?q.getForegroundCommunityColour():q.getForegroundColour(j(a.key,b._data))};break;default:throw"Sorry given colour-scheme not known"}},I=function(a){if("reset"===a)o=n;else{if(!_.isFunction(a))throw"Sorry distortion cannot be parsed.";o=a}},J=function(a){void 0!==a.shape&&D(a.shape),void 0!==a.label&&(F(a.label),f.label=a.label),void 0!==a.actions&&G(a.actions),void 0!==a.color&&(H(a.color),f.color=a.color),void 0!==a.distortion&&I(a.distortion)};f.parent=a,x(),void 0===b&&(b={}),void 0===b.shape&&(b.shape={type:NodeShaper.shapes.RECT}),void 0===b.color&&(b.color={type:"single",fill:"#333333",stroke:"white"}),void 0===b.distortion&&(b.distortion="reset"),J(b),_.isFunction(c)&&(s=c),f.changeTo=function(a){J(a),C()},f.drawNodes=function(a){C(a)},f.updateNodes=function(){B()},f.reshapeNodes=function(){C()},f.activateLabel=function(a){h=!!a,C()},f.getColourMapping=function(){return q.getList()},f.setColourMappingListener=function(a){q.setChangeListener(a)},f.setGVStartFunction=function(a){m=a},f.getLabel=function(){return f.label||""},f.getColor=function(){return f.color.key||""},f.addMenuEntry=function(a,b){i.addEntry(a,b)},f.resetColourMap=r}function PreviewAdapter(a,b,c,d){"use strict";if(void 0===a)throw"The nodes have to be given.";if(void 0===b)throw"The edges have to be given.";if(void 0===c)throw"A reference to the graph viewer has to be given.";var e=this,f=new AbstractAdapter(a,b,this,c),g=function(a){void 0!==a.width&&f.setWidth(a.width),void 0!==a.height&&f.setHeight(a.height)},h=function(a,b){var c={},d=a.first;d=f.insertNode(d),_.each(a.nodes,function(a){a=f.insertNode(a),c[a._id]=a}),_.each(a.edges,function(a){f.insertEdge(a)}),delete c[d._id],void 0!==b&&_.isFunction(b)&&b(d)};d=d||{},g(d),e.loadInitialNode=function(a,b){f.cleanUp();var c=function(a){b(f.insertInitialNode(a))};e.loadNode(a,c)},e.loadNode=function(a,b){var c=[],d=[],e={},f={_id:1,label:"Node 1",image:"img/stored.png"},g={_id:2,label:"Node 2"},i={_id:3,label:"Node 3"},j={_id:4,label:"Node 4"},k={_id:5,label:"Node 5"},l={_id:"1-2",_from:1,_to:2,label:"Edge 1"},m={_id:"1-3",_from:1,_to:3,label:"Edge 2"},n={_id:"1-4",_from:1,_to:4,label:"Edge 3"},o={_id:"1-5",_from:1,_to:5,label:"Edge 4"},p={_id:"2-3",_from:2,_to:3,label:"Edge 5"};c.push(f),c.push(g),c.push(i),c.push(j),c.push(k),d.push(l),d.push(m),d.push(n),d.push(o),d.push(p),e.first=f,e.nodes=c,e.edges=d,h(e,b)},e.explore=f.explore,e.requestCentralityChildren=function(a,b){},e.createEdge=function(a,b){arangoHelper.arangoError("Server-side","createEdge was triggered.")},e.deleteEdge=function(a,b){arangoHelper.arangoError("Server-side","deleteEdge was triggered.")},e.patchEdge=function(a,b,c){arangoHelper.arangoError("Server-side","patchEdge was triggered.")},e.createNode=function(a,b){arangoHelper.arangoError("Server-side","createNode was triggered.")},e.deleteNode=function(a,b){arangoHelper.arangoError("Server-side","deleteNode was triggered."),arangoHelper.arangoError("Server-side","onNodeDelete was triggered.")},e.patchNode=function(a,b,c){arangoHelper.arangoError("Server-side","patchNode was triggered.")},e.setNodeLimit=function(a,b){f.setNodeLimit(a,b)},e.setChildLimit=function(a){f.setChildLimit(a)},e.setWidth=f.setWidth,e.expandCommunity=function(a,b){f.expandCommunity(a),void 0!==b&&b()}}function WebWorkerWrapper(a,b){"use strict";if(void 0===a)throw"A class has to be given.";if(void 0===b)throw"A callback has to be given.";var c,d=Array.prototype.slice.call(arguments),e={},f=function(){var c,d=function(a){switch(a.data.cmd){case"construct":try{w=new(Function.prototype.bind.apply(Construct,[null].concat(a.data.args))),w?self.postMessage({cmd:"construct",result:!0}):self.postMessage({cmd:"construct",result:!1})}catch(b){self.postMessage({cmd:"construct",result:!1,error:b.message||b})}break;default:var c,d={cmd:a.data.cmd};if(w&&"function"==typeof w[a.data.cmd])try{c=w[a.data.cmd].apply(w,a.data.args),c&&(d.result=c),self.postMessage(d)}catch(e){d.error=e.message||e,self.postMessage(d)}else d.error="Method not known",self.postMessage(d)}},e=function(a){var b="var w, Construct = "+a.toString()+";self.onmessage = "+d.toString();return new window.Blob(b.split())},f=window.URL,g=new e(a);return c=new window.Worker(f.createObjectURL(g)),c.onmessage=b,c},g=function(){return a.apply(this,d)};try{return c=f(),e.call=function(a){var b=Array.prototype.slice.call(arguments);b.shift(),c.postMessage({cmd:a,args:b})},d.shift(),d.shift(),d.unshift("construct"),e.call.apply(this,d),e}catch(h){d.shift(),d.shift(),g.prototype=a.prototype;try{c=new g}catch(i){return void b({data:{cmd:"construct",error:i}})}return e.call=function(a){var d=Array.prototype.slice.call(arguments),e={data:{cmd:a}};if(!_.isFunction(c[a]))return e.data.error="Method not known",void b(e);d.shift();try{e.data.result=c[a].apply(c,d),b(e)}catch(f){e.data.error=f,b(e)}},b({data:{cmd:"construct",result:!0}}),e}}function ZoomManager(a,b,c,d,e,f,g,h){"use strict";if(void 0===a||0>a)throw"A width has to be given.";if(void 0===b||0>b)throw"A height has to be given.";if(void 0===c||void 0===c.node||"svg"!==c.node().tagName.toLowerCase())throw"A svg has to be given.";if(void 0===d||void 0===d.node||"g"!==d.node().tagName.toLowerCase())throw"A group has to be given.";if(void 0===e||void 0===e.activateLabel||void 0===e.changeTo||void 0===e.updateNodes)throw"The Node shaper has to be given.";if(void 0===f||void 0===f.activateLabel||void 0===f.updateEdges)throw"The Edge shaper has to be given.";var i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=a*b,z=h||function(){},A=function(){var a,b;return l>=k?(b=i*l,b*=b,a=60*b):(b=j*l,b*=b,a=4*Math.PI*b),Math.floor(y/a)},B=function(){q=s/l-.99999999,r=t/l,p.distortion(q),p.radius(r)},C=function(a,b,c,g){g?null!==a&&(l=a):l=a,null!==b&&(m[0]+=b),null!==c&&(m[1]+=c),o=A(),z(o),e.activateLabel(l>=k),f.activateLabel(l>=k),B();var h="translate("+m+")",i=" scale("+l+")";d._isCommunity?d.attr("transform",h):d.attr("transform",h+i),v&&v.slider("option","value",l)},D=function(a){var b=[];return b[0]=a[0]-n[0],b[1]=a[1]-n[1],n[0]=a[0],n[1]=a[1],b},E=function(a){void 0===a&&(a={});var b=a.maxFont||16,c=a.minFont||6,d=a.maxRadius||25,e=a.minRadius||4;s=a.focusZoom||1,t=a.focusRadius||100,w=e/d,i=b,j=d,k=c/b,l=1,m=[0,0],n=[0,0],B(),o=A(),u=d3.behavior.zoom().scaleExtent([w,1]).on("zoom",function(){var a,b=d3.event.sourceEvent,c=l;"mousewheel"===b.type||"DOMMouseScroll"===b.type?(b.wheelDelta?b.wheelDelta>0?(c+=.01,c>1&&(c=1)):(c-=.01,w>c&&(c=w)):b.detail>0?(c+=.01,c>1&&(c=1)):(c-=.01,w>c&&(c=w)),a=[0,0]):a=D(d3.event.translate),C(c,a[0],a[1])})},F=function(){};p=d3.fisheye.circular(),E(g),c.call(u),e.changeTo({distortion:p}),c.on("mousemove",F),x.translation=function(){return null},x.scaleFactor=function(){return l},x.scaledMouse=function(){return null},x.getDistortion=function(){return q},x.getDistortionRadius=function(){return r},x.getNodeLimit=function(){return o},x.getMinimalZoomFactor=function(){return w},x.registerSlider=function(a){v=a},x.triggerScale=function(a){C(a,null,null,!0)},x.triggerTranslation=function(a,b){C(null,a,b,!0)},x.changeWidth=function(c){y=a*b}}function ArangoAdapterControls(a,b){"use strict";if(void 0===a)throw"A list element has to be given.";if(void 0===b)throw"The ArangoAdapter has to be given.";this.addControlChangeCollections=function(c){var d="control_adapter_collections",e=d+"_";b.getCollections(function(f,g){b.getGraphs(function(h){uiComponentsHelper.createButton(a,"Collections",d,function(){modalDialogHelper.createModalDialog("Switch Collections",e,[{
type:"decission",id:"collections",group:"loadtype",text:"Select existing collections",isDefault:void 0===b.getGraphName(),interior:[{type:"list",id:"node_collection",text:"Vertex collection",objects:f,selected:b.getNodeCollection()},{type:"list",id:"edge_collection",text:"Edge collection",objects:g,selected:b.getEdgeCollection()}]},{type:"decission",id:"graphs",group:"loadtype",text:"Select existing graph",isDefault:void 0!==b.getGraphName(),interior:[{type:"list",id:"graph",objects:h,selected:b.getGraphName()}]},{type:"checkbox",text:"Start with random vertex",id:"random",selected:!0},{type:"checkbox",id:"undirected",selected:"any"===b.getDirection()}],function(){var a=$("#"+e+"node_collection").children("option").filter(":selected").text(),d=$("#"+e+"edge_collection").children("option").filter(":selected").text(),f=$("#"+e+"graph").children("option").filter(":selected").text(),g=!!$("#"+e+"undirected").prop("checked"),h=!!$("#"+e+"random").prop("checked"),i=$("input[type='radio'][name='loadtype']:checked").prop("id");return i===e+"collections"?b.changeToCollections(a,d,g):b.changeToGraph(f,g),h?void b.loadRandomNode(c):void(_.isFunction(c)&&c())})})})})},this.addControlChangePriority=function(){var c="control_adapter_priority",d=c+"_",e=(b.getPrioList(),"Group vertices");uiComponentsHelper.createButton(a,e,c,function(){modalDialogHelper.createModalChangeDialog(e,d,[{type:"extendable",id:"attribute",objects:b.getPrioList()}],function(){var a=$("input[id^="+d+"attribute_]"),c=[];a.each(function(a,b){var d=$(b).val();""!==d&&c.push(d)}),b.changeTo({prioList:c})})})},this.addAll=function(){this.addControlChangeCollections(),this.addControlChangePriority()}}function ContextMenu(a){"use strict";if(void 0===a)throw"An id has to be given.";var b,c,d="#"+a,e=function(a,d){var e,f;e=document.createElement("div"),e.className="context-menu-item",f=document.createElement("div"),f.className="context-menu-item-inner",f.appendChild(document.createTextNode(a)),f.onclick=function(){d(d3.select(c.target).data()[0])},e.appendChild(f),b.appendChild(e)},f=function(a){c=$.contextMenu.create(d,{shadow:!1}),a.each(function(){$(this).bind("contextmenu",function(a){return c.show(this,a),!1})})},g=function(){return b=document.getElementById(a),b&&b.parentElement.removeChild(b),b=document.createElement("div"),b.className="context-menu context-menu-theme-osx",b.id=a,document.body.appendChild(b),b};g(),this.addEntry=e,this.bindMenu=f}function EdgeShaperControls(a,b){"use strict";if(void 0===a)throw"A list element has to be given.";if(void 0===b)throw"The EdgeShaper has to be given.";var c=this;this.addControlOpticShapeNone=function(){var c="control_edge_none";uiComponentsHelper.createButton(a,"None",c,function(){b.changeTo({shape:{type:EdgeShaper.shapes.NONE}})})},this.addControlOpticShapeArrow=function(){var c="control_edge_arrow";uiComponentsHelper.createButton(a,"Arrow",c,function(){b.changeTo({shape:{type:EdgeShaper.shapes.ARROW}})})},this.addControlOpticLabel=function(){var c="control_edge_label",d=c+"_";uiComponentsHelper.createButton(a,"Configure Label",c,function(){modalDialogHelper.createModalDialog("Switch Label Attribute",d,[{type:"text",id:"key",text:"Edge label attribute",value:b.getLabel()}],function(){var a=$("#"+d+"key").attr("value");b.changeTo({label:a})})})},this.addControlOpticLabelList=function(){var d="control_edge_label",e=d+"_";uiComponentsHelper.createButton(a,"Configure Label",d,function(){modalDialogHelper.createModalDialog("Change Label Attribute",e,[{type:"extendable",id:"label",text:"Edge label attribute",objects:b.getLabel()}],function(){var a=$("input[id^="+e+"label_]"),d=[];a.each(function(a,b){var c=$(b).val();""!==c&&d.push(c)});var f={label:d};c.applyLocalStorage(f),b.changeTo(f)})})},this.applyLocalStorage=function(a){if("undefined"!==Storage)try{var b=JSON.parse(localStorage.getItem("graphSettings")),c=window.location.hash.split("/")[1],d=window.location.pathname.split("/")[2],e=c+d;_.each(a,function(a,c){void 0!==c&&(b[e].viewer.hasOwnProperty("edgeShaper")||(b[e].viewer.edgeShaper={}),b[e].viewer.edgeShaper[c]=a)}),localStorage.setItem("graphSettings",JSON.stringify(b))}catch(f){console.log(f)}},this.addControlOpticSingleColour=function(){var c="control_edge_singlecolour",d=c+"_";uiComponentsHelper.createButton(a,"Single Colour",c,function(){modalDialogHelper.createModalDialog("Switch to Colour",d,[{type:"text",id:"stroke"}],function(){var a=$("#"+d+"stroke").attr("value");b.changeTo({color:{type:"single",stroke:a}})})})},this.addControlOpticAttributeColour=function(){var c="control_edge_attributecolour",d=c+"_";uiComponentsHelper.createButton(a,"Colour by Attribute",c,function(){modalDialogHelper.createModalDialog("Display colour by attribute",d,[{type:"text",id:"key"}],function(){var a=$("#"+d+"key").attr("value");b.changeTo({color:{type:"attribute",key:a}})})})},this.addControlOpticGradientColour=function(){var c="control_edge_gradientcolour",d=c+"_";uiComponentsHelper.createButton(a,"Gradient Colour",c,function(){modalDialogHelper.createModalDialog("Change colours for gradient",d,[{type:"text",id:"source"},{type:"text",id:"target"}],function(){var a=$("#"+d+"source").attr("value"),c=$("#"+d+"target").attr("value");b.changeTo({color:{type:"gradient",source:a,target:c}})})})},this.addAllOptics=function(){c.addControlOpticShapeNone(),c.addControlOpticShapeArrow(),c.addControlOpticLabel(),c.addControlOpticSingleColour(),c.addControlOpticAttributeColour(),c.addControlOpticGradientColour()},this.addAllActions=function(){},this.addAll=function(){c.addAllOptics(),c.addAllActions()}}function EventDispatcherControls(a,b,c,d,e){"use strict";if(void 0===a)throw"A list element has to be given.";if(void 0===b)throw"The NodeShaper has to be given.";if(void 0===c)throw"The EdgeShaper has to be given.";if(void 0===d)throw"The Start callback has to be given.";var f=this,g={expand:{icon:"hand-pointer-o",title:"Expand a node."},add:{icon:"plus-square",title:"Add a node."},trash:{icon:"minus-square",title:"Remove a node/edge."},drag:{icon:"hand-rock-o",title:"Drag a node."},edge:{icon:"external-link-square",title:"Create an edge between two nodes."},edit:{icon:"pencil-square",title:"Edit attributes of a node."},view:{icon:"search",title:"View attributes of a node."}},h=new EventDispatcher(b,c,e),i=e.edgeEditor.adapter,j=!!i&&_.isFunction(i.useNodeCollection)&&_.isFunction(i.useEdgeCollection),k=function(b){a.appendChild(b)},l=function(a,b,c){var d=uiComponentsHelper.createIconButton(a,"control_event_"+b,c);k(d)},m=function(a){h.rebind("nodes",a)},n=function(a){h.rebind("edges",a)},o=function(a){h.rebind("svg",a)},p=function(a){var b=a||window.event,c={};return c.x=b.clientX,c.y=b.clientY,c.x+=document.body.scrollLeft,c.y+=document.body.scrollTop,c},q=function(a){var b,c,d,e=p(a),f=$("svg#graphViewerSVG").offset();return b=d3.select("svg#graphViewerSVG").node(),d=b.getBoundingClientRect(),$("svg#graphViewerSVG").height()<=d.height?{x:e.x-f.left,y:e.y-f.top}:(c=b.getBBox(),{x:e.x-(d.left-c.x),y:e.y-(d.top-c.y)})},r={nodes:{},edges:{},svg:{}},s=function(){var a="control_event_new_node",c=a+"_",e=function(a){var e=q(a);modalDialogHelper.createModalCreateDialog("Create New Node",c,{},function(a){h.events.CREATENODE(a,function(a){$("#"+c+"modal").modal("hide"),b.reshapeNodes(),d()},e.x,e.y)()})};r.nodes.newNode=e},t=function(){var a=function(a){modalDialogHelper.createModalViewDialog("View Node "+a._id,"control_event_node_view_",a._data,function(){modalDialogHelper.createModalEditDialog("Edit Node "+a._id,"control_event_node_edit_",a._data,function(b){h.events.PATCHNODE(a,b,function(){$("#control_event_node_edit_modal").modal("hide")})()})})},b=function(a){modalDialogHelper.createModalViewDialog("View Edge "+a._id,"control_event_edge_view_",a._data,function(){modalDialogHelper.createModalEditDialog("Edit Edge "+a._id,"control_event_edge_edit_",a._data,function(b){h.events.PATCHEDGE(a,b,function(){$("#control_event_edge_edit_modal").modal("hide")})()})})};r.nodes.view=a,r.edges.view=b},u=function(){var a=h.events.STARTCREATEEDGE(function(a,b){var d=q(b),e=c.addAnEdgeFollowingTheCursor(d.x,d.y);h.bind("svg","mousemove",function(a){var b=q(a);e(b.x,b.y)})}),b=h.events.FINISHCREATEEDGE(function(a){c.removeCursorFollowingEdge(),h.bind("svg","mousemove",function(){}),d()}),e=function(){h.events.CANCELCREATEEDGE(),c.removeCursorFollowingEdge(),h.bind("svg","mousemove",function(){})};r.nodes.startEdge=a,r.nodes.endEdge=b,r.svg.cancelEdge=e},v=function(){var a=function(a){arangoHelper.openDocEditor(a._id,"document")},b=function(a){arangoHelper.openDocEditor(a._id,"edge")};r.nodes.edit=a,r.edges.edit=b},w=function(){var a=function(a){modalDialogHelper.createModalDeleteDialog("Delete Node "+a._id,"control_event_node_delete_",a,function(a){h.events.DELETENODE(function(){$("#control_event_node_delete_modal").modal("hide"),b.reshapeNodes(),c.reshapeEdges(),d()})(a)})},e=function(a){modalDialogHelper.createModalDeleteDialog("Delete Edge "+a._id,"control_event_edge_delete_",a,function(a){h.events.DELETEEDGE(function(){$("#control_event_edge_delete_modal").modal("hide"),b.reshapeNodes(),c.reshapeEdges(),d()})(a)})};r.nodes.del=a,r.edges.del=e},x=function(){r.nodes.spot=h.events.EXPAND};s(),t(),u(),v(),w(),x(),this.dragRebinds=function(){return{nodes:{drag:h.events.DRAG}}},this.newNodeRebinds=function(){return{svg:{click:r.nodes.newNode}}},this.viewRebinds=function(){return{nodes:{click:r.nodes.view},edges:{click:r.edges.view}}},this.connectNodesRebinds=function(){return{nodes:{mousedown:r.nodes.startEdge,mouseup:r.nodes.endEdge},svg:{mouseup:r.svg.cancelEdge}}},this.editRebinds=function(){return{nodes:{click:r.nodes.edit},edges:{click:r.edges.edit}}},this.expandRebinds=function(){return{nodes:{click:r.nodes.spot}}},this.deleteRebinds=function(){return{nodes:{click:r.nodes.del},edges:{click:r.edges.del}}},this.rebindAll=function(a){m(a.nodes),n(a.edges),o(a.svg)},b.addMenuEntry("Edit",r.nodes.edit),b.addMenuEntry("Spot",r.nodes.spot),b.addMenuEntry("Trash",r.nodes.del),c.addMenuEntry("Edit",r.edges.edit),c.addMenuEntry("Trash",r.edges.del),this.addControlNewNode=function(){var a=g.add,b="select_node_collection",c=function(){j&&i.getNodeCollections().length>1&&modalDialogHelper.createModalDialog("Select Vertex Collection",b,[{type:"list",id:"vertex",objects:i.getNodeCollections(),text:"Select collection",selected:i.getSelectedNodeCollection()}],function(){var a=$("#"+b+"vertex").children("option").filter(":selected").text();i.useNodeCollection(a)},"Select"),f.rebindAll(f.newNodeRebinds())};l(a,"new_node",c)},this.addControlView=function(){var a=g.view,b=function(){f.rebindAll(f.viewRebinds())};l(a,"view",b)},this.addControlDrag=function(){var a=g.drag,b=function(){f.rebindAll(f.dragRebinds())};l(a,"drag",b)},this.addControlEdit=function(){var a=g.edit,b=function(){f.rebindAll(f.editRebinds())};l(a,"edit",b)},this.addControlExpand=function(){var a=g.expand,b=function(){f.rebindAll(f.expandRebinds())};l(a,"expand",b)},this.addControlDelete=function(){var a=g.trash,b=function(){f.rebindAll(f.deleteRebinds())};l(a,"delete",b)},this.addControlConnect=function(){var a=g.edge,b="select_edge_collection",c=function(){j&&i.getEdgeCollections().length>1&&modalDialogHelper.createModalDialog("Select Edge Collection",b,[{type:"list",id:"edge",objects:i.getEdgeCollections(),text:"Select collection",selected:i.getSelectedEdgeCollection()}],function(){var a=$("#"+b+"edge").children("option").filter(":selected").text();i.useEdgeCollection(a)},"Select"),f.rebindAll(f.connectNodesRebinds())};l(a,"connect",c)},this.addAll=function(){f.addControlExpand(),f.addControlDrag(),f.addControlEdit(),f.addControlConnect(),f.addControlNewNode(),f.addControlDelete()}}function GharialAdapterControls(a,b){"use strict";if(void 0===a)throw"A list element has to be given.";if(void 0===b)throw"The GharialAdapter has to be given.";this.addControlChangeGraph=function(c){var d="control_adapter_graph",e=d+"_";b.getGraphs(function(f){uiComponentsHelper.createButton(a,"Switch Graph",d,function(){modalDialogHelper.createModalDialog("Switch Graph",e,[{type:"list",id:"graph",objects:f,text:"Select graph",selected:b.getGraphName()},{type:"checkbox",text:"Start with random vertex",id:"random",selected:!0}],function(){var a=$("#"+e+"graph").children("option").filter(":selected").text(),d=!!$("#"+e+"undirected").prop("checked"),f=!!$("#"+e+"random").prop("checked");return b.changeToGraph(a,d),f?void b.loadRandomNode(c):void(_.isFunction(c)&&c())})})})},this.addControlChangePriority=function(){var c="control_adapter_priority",d=c+"_",e="Group vertices";uiComponentsHelper.createButton(a,e,c,function(){modalDialogHelper.createModalChangeDialog(e+" by attribute",d,[{type:"extendable",id:"attribute",objects:b.getPrioList()}],function(){var a=$("input[id^="+d+"attribute_]"),c=[];_.each(a,function(a){var b=$(a).val();""!==b&&c.push(b)}),b.changeTo({prioList:c})})})},this.addAll=function(){this.addControlChangeGraph(),this.addControlChangePriority()}}function GraphViewerPreview(a,b){"use strict";var c,d,e,f,g,h,i,j=function(){return d3.select(a).append("svg").attr("id","graphViewerSVG").attr("width",d).attr("height",e).attr("class","graph-viewer").attr("style","width:"+d+"px;height:"+e+";")},k=function(a){var b=0;return _.each(a,function(c,d){c===!1?delete a[d]:b++}),b>0},l=function(a,b){_.each(b,function(b,c){a[c]=a[c]||{},_.each(b,function(b,d){a[c][d]=b})})},m=function(a){if(a){var b={};a.drag&&l(b,i.dragRebinds()),a.create&&(l(b,i.newNodeRebinds()),l(b,i.connectNodesRebinds())),a.remove&&l(b,i.deleteRebinds()),a.expand&&l(b,i.expandRebinds()),a.edit&&l(b,i.editRebinds()),i.rebindAll(b)}},n=function(b){var c=document.createElement("div");i=new EventDispatcherControls(c,f.nodeShaper,f.edgeShaper,f.start,f.dispatcherConfig),c.id="toolbox",c.className="btn-group btn-group-vertical pull-left toolbox",a.appendChild(c),_.each(b,function(a,b){switch(b){case"expand":i.addControlExpand();break;case"create":i.addControlNewNode(),i.addControlConnect();break;case"drag":i.addControlDrag();break;case"edit":i.addControlEdit();break;case"remove":i.addControlDelete()}})},o=function(a){var b=document.createElement("div");i=new EventDispatcherControls(b,f.nodeShaper,f.edgeShaper,f.start,f.dispatcherConfig)},p=function(){b&&(b.nodeShaper&&(b.nodeShaper.label&&(b.nodeShaper.label="label"),b.nodeShaper.shape&&b.nodeShaper.shape.type===NodeShaper.shapes.IMAGE&&b.nodeShaper.shape.source&&(b.nodeShaper.shape.source="image")),b.edgeShaper&&b.edgeShaper.label&&(b.edgeShaper.label="label"))},q=function(){return p(),new GraphViewer(c,d,e,h,b)};d=a.getBoundingClientRect().width,e=a.getBoundingClientRect().height,h={type:"preview"},b=b||{},g=k(b.toolbox),g&&(d-=43),c=j(),f=q(),g?n(b.toolbox):o(),f.loadGraph("1"),m(b.actions)}function GraphViewerUI(a,b,c,d,e,f){"use strict";if(void 0===a)throw"A parent element has to be given.";if(!a.id)throw"The parent element needs an unique id.";if(void 0===b)throw"An adapter configuration has to be given";var g,h,i,j,k,l,m,n,o,p=c+20||a.getBoundingClientRect().width-81+20,q=d||a.getBoundingClientRect().height,r=document.createElement("ul"),s=document.createElement("div"),t=function(){g.adapter.NODES_TO_DISPLAYGraph too big. A random section is rendered.'),$(".infoField .fa-info-circle").attr("title","You can display additional/other vertices by using the toolbar buttons.").tooltip())},u=function(){var a,b=document.createElement("div"),c=document.createElement("div"),d=document.createElement("div"),e=document.createElement("div"),f=document.createElement("button"),h=document.createElement("span"),i=document.createElement("input"),j=document.createElement("i"),k=document.createElement("span"),l=function(){$(s).css("cursor","progress")},n=function(){$(s).css("cursor","")},o=function(a){return n(),a&&a.errorCode&&404===a.errorCode?void arangoHelper.arangoError("Graph error","could not find a matching node."):void 0},p=function(){l(),""===a.value||void 0===a.value?g.loadGraph(i.value,o):g.loadGraphWithAttributeValue(a.value,i.value,o)};b.id="filterDropdown",b.className="headerDropdown smallDropdown",c.className="dropdownInner",d.className="queryline",a=document.createElement("input"),m=document.createElement("ul"),e.className="pull-left input-append searchByAttribute",a.id="attribute",a.type="text",a.placeholder="Attribute name",f.id="attribute_example_toggle",f.className="button-neutral gv_example_toggle",h.className="caret gv_caret",m.className="gv-dropdown-menu",i.id="value",i.className="searchInput gv_searchInput",i.type="text",i.placeholder="Attribute value",j.id="loadnode",j.className="fa fa-search",k.className="searchEqualsLabel",k.appendChild(document.createTextNode("==")),c.appendChild(d),d.appendChild(e),e.appendChild(a),e.appendChild(f),e.appendChild(m),f.appendChild(h),d.appendChild(k),d.appendChild(i),d.appendChild(j),j.onclick=p,$(i).keypress(function(a){return 13===a.keyCode||13===a.which?(p(),!1):void 0}),f.onclick=function(){$(m).slideToggle(200)};var q=document.createElement("p");return q.className="dropdown-title",q.innerHTML="Filter graph by attribute:",b.appendChild(q),b.appendChild(c),b},v=function(){var a,b=document.createElement("div"),c=document.createElement("div"),d=document.createElement("div"),e=document.createElement("div"),f=document.createElement("button"),h=document.createElement("span"),i=document.createElement("input"),j=document.createElement("i"),k=document.createElement("span"),l=function(){$(s).css("cursor","progress")},m=function(){$(s).css("cursor","")},o=function(a){return m(),a&&a.errorCode&&404===a.errorCode?void arangoHelper.arangoError("Graph error","could not find a matching node."):void 0},p=function(){l(),""!==a.value&&g.loadGraphWithAdditionalNode(a.value,i.value,o)};b.id="nodeDropdown",b.className="headerDropdown smallDropdown",c.className="dropdownInner",d.className="queryline",a=document.createElement("input"),n=document.createElement("ul"),e.className="pull-left input-append searchByAttribute",a.id="attribute",a.type="text",a.placeholder="Attribute name",f.id="attribute_example_toggle2",f.className="button-neutral gv_example_toggle",h.className="caret gv_caret",n.className="gv-dropdown-menu",i.id="value",i.className="searchInput gv_searchInput",i.type="text",i.placeholder="Attribute value",j.id="loadnode",j.className="fa fa-search",k.className="searchEqualsLabel",k.appendChild(document.createTextNode("==")),c.appendChild(d),d.appendChild(e),e.appendChild(a),e.appendChild(f),e.appendChild(n),f.appendChild(h),d.appendChild(k),d.appendChild(i),d.appendChild(j),C(n),j.onclick=p,$(i).keypress(function(a){return 13===a.keyCode||13===a.which?(p(),!1):void 0}),f.onclick=function(){$(n).slideToggle(200)};var q=document.createElement("p");return q.className="dropdown-title",q.innerHTML="Add specific node by attribute:",b.appendChild(q),b.appendChild(c),b},w=function(){var a,b,c,d,e,f,g,h;return a=document.createElement("div"),a.id="configureDropdown",a.className="headerDropdown",b=document.createElement("div"),b.className="dropdownInner",c=document.createElement("ul"),d=document.createElement("li"),d.className="nav-header",d.appendChild(document.createTextNode("Vertices")),g=document.createElement("ul"),h=document.createElement("li"),h.className="nav-header",h.appendChild(document.createTextNode("Edges")),e=document.createElement("ul"),f=document.createElement("li"),f.className="nav-header",f.appendChild(document.createTextNode("Connection")),c.appendChild(d),g.appendChild(h),e.appendChild(f),b.appendChild(c),b.appendChild(g),b.appendChild(e),a.appendChild(b),{configure:a,nodes:c,edges:g,col:e}},x=function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o;return a.className="headerButtonBar",e=document.createElement("ul"),e.className="headerButtonList",a.appendChild(e),g=document.createElement("li"),g.className="enabled",h=document.createElement("a"),h.id=b,h.className="headerButton",i=document.createElement("span"),i.className="icon_arangodb_settings2",$(i).attr("title","Configure"),e.appendChild(g),g.appendChild(h),h.appendChild(i),j=document.createElement("li"),j.className="enabled",k=document.createElement("a"),k.id=d,k.className="headerButton",l=document.createElement("span"),l.className="fa fa-search-plus",$(l).attr("title","Show additional vertices"),e.appendChild(j),j.appendChild(k),k.appendChild(l),m=document.createElement("li"),m.className="enabled",n=document.createElement("a"),n.id=c,n.className="headerButton",o=document.createElement("span"),o.className="icon_arangodb_filter",$(o).attr("title","Filter"),e.appendChild(m),m.appendChild(n),n.appendChild(o),f=w(),f.filter=u(),f.node=v(),h.onclick=function(){$("#filterdropdown").removeClass("activated"),$("#nodedropdown").removeClass("activated"),$("#configuredropdown").toggleClass("activated"),$(f.configure).slideToggle(200),$(f.filter).hide(),$(f.node).hide()},k.onclick=function(){$("#filterdropdown").removeClass("activated"),$("#configuredropdown").removeClass("activated"),$("#nodedropdown").toggleClass("activated"),$(f.node).slideToggle(200),$(f.filter).hide(),$(f.configure).hide()},n.onclick=function(){$("#configuredropdown").removeClass("activated"),$("#nodedropdown").removeClass("activated"),$("#filterdropdown").toggleClass("activated"),$(f.filter).slideToggle(200),$(f.node).hide(),$(f.configure).hide()},f},y=function(){return d3.select("#"+a.id+" #background").append("svg").attr("id","graphViewerSVG").attr("width",p).attr("height",q).attr("class","graph-viewer").style("width",p+"px").style("height",q+"px")},z=function(){var a=document.createElement("div"),b=document.createElement("div"),c=document.createElement("button"),d=document.createElement("button"),e=document.createElement("button"),f=document.createElement("button");a.className="gv_zoom_widget",b.className="gv_zoom_buttons_bg",c.className="btn btn-icon btn-zoom btn-zoom-top gv-zoom-btn pan-top",d.className="btn btn-icon btn-zoom btn-zoom-left gv-zoom-btn pan-left",e.className="btn btn-icon btn-zoom btn-zoom-right gv-zoom-btn pan-right",f.className="btn btn-icon btn-zoom btn-zoom-bottom gv-zoom-btn pan-bottom",c.onclick=function(){g.zoomManager.triggerTranslation(0,-10)},d.onclick=function(){g.zoomManager.triggerTranslation(-10,0)},e.onclick=function(){g.zoomManager.triggerTranslation(10,0)},f.onclick=function(){g.zoomManager.triggerTranslation(0,10)},b.appendChild(c),b.appendChild(d),b.appendChild(e),b.appendChild(f),l=document.createElement("div"),l.id="gv_zoom_slider",l.className="gv_zoom_slider",s.appendChild(a),s.insertBefore(a,o[0][0]),a.appendChild(b),a.appendChild(l),$("#gv_zoom_slider").slider({orientation:"vertical",min:g.zoomManager.getMinimalZoomFactor(),max:1,value:1,step:.01,slide:function(a,b){g.zoomManager.triggerScale(b.value)}}),g.zoomManager.registerSlider($("#gv_zoom_slider"))},A=function(){var a=document.createElement("div"),b=new EventDispatcherControls(a,g.nodeShaper,g.edgeShaper,g.start,g.dispatcherConfig);a.id="toolbox",a.className="btn-group btn-group-vertical toolbox",s.insertBefore(a,o[0][0]),b.addAll(),$("#control_event_expand").click()},B=function(){var a='';$(".headerBar .headerButtonList").prepend(a)},C=function(a){var b;b=a?$(a):$(m),b.innerHTML="";var c=document.createElement("li"),d=document.createElement("img");$(c).append(d),d.className="gv-throbber",b.append(c),g.adapter.getAttributeExamples(function(a){$(b).html(""),_.each(a,function(a){var c=document.createElement("li"),d=document.createElement("a"),e=document.createElement("label");$(c).append(d),$(d).append(e),$(e).append(document.createTextNode(a)),e.className="gv_dropdown_label",b.append(c),c.onclick=function(){b.value=a,$(b).parent().find("input").val(a),$(b).slideToggle(200)}})})},D=function(){var a=document.createElement("div"),b=document.createElement("div"),c=(document.createElement("a"),x(b,"configuredropdown","filterdropdown","nodedropdown"));i=new NodeShaperControls(c.nodes,g.nodeShaper),j=new EdgeShaperControls(c.edges,g.edgeShaper),k=new GharialAdapterControls(c.col,g.adapter),r.id="menubar",a.className="headerBar",b.id="modifiers",r.appendChild(a),r.appendChild(c.configure),r.appendChild(c.filter),r.appendChild(c.node),a.appendChild(b),k.addControlChangeGraph(function(){C(),g.start(!0)}),k.addControlChangePriority(),i.addControlOpticLabelAndColourList(g.adapter),j.addControlOpticLabelList(),C()},E=function(){h=i.createColourMappingList(),h.className="gv-colour-list",s.insertBefore(h,o[0][0])};a.appendChild(r),a.appendChild(s),s.className="contentDiv gv-background ",s.id="background",e=e||{},e.zoom=!0,$("#subNavigationBar .breadcrumb").html("Graph: "+b.graphName),o=y(),"undefined"!==Storage&&(this.graphSettings={},this.loadLocalStorage=function(){var a=b.baseUrl.split("/")[2],c=b.graphName+a;if(null===localStorage.getItem("graphSettings")||"null"===localStorage.getItem("graphSettings")){var d={};d[c]={viewer:e,adapter:b},localStorage.setItem("graphSettings",JSON.stringify(d))}else try{var f=JSON.parse(localStorage.getItem("graphSettings"));this.graphSettings=f,void 0!==f[c].viewer&&(e=f[c].viewer),void 0!==f[c].adapter&&(b=f[c].adapter)}catch(g){console.log("Could not load graph settings, resetting graph settings."),this.graphSettings[c]={viewer:e,adapter:b},localStorage.setItem("graphSettings",JSON.stringify(this.graphSettings))}},this.loadLocalStorage(),this.writeLocalStorage=function(){}),g=new GraphViewer(o,p,q,b,e),A(),z(),D(),E(),t(),B(),$("#graphSize").on("change",function(){var a=$("#graphSize").find(":selected").val();g.loadGraphWithRandomStart(function(a){a&&a.errorCode&&arangoHelper.arangoError("Graph","Sorry your graph seems to be empty")},a)}),f&&("string"==typeof f?g.loadGraph(f):g.loadGraphWithRandomStart(function(a){a&&a.errorCode&&arangoHelper.arangoError("Graph","Sorry your graph seems to be empty")})),this.changeWidth=function(a){g.changeWidth(a);var b=a-55;o.attr("width",b).style("width",b+"px")}}function GraphViewerWidget(a,b){"use strict";var c,d,e,f,g,h,i,j,k=function(){return d3.select(d).append("svg").attr("id","graphViewerSVG").attr("width",e).attr("height",f).attr("class","graph-viewer").attr("style","width:"+e+"px;height:"+f+"px;")},l=function(a){var b=0;return _.each(a,function(c,d){c===!1?delete a[d]:b++}),b>0},m=function(a,b){_.each(b,function(b,c){a[c]=a[c]||{},_.each(b,function(b,d){a[c][d]=b})})},n=function(a){if(a){var b={};a.drag&&m(b,j.dragRebinds()),a.create&&(m(b,j.newNodeRebinds()),m(b,j.connectNodesRebinds())),a.remove&&m(b,j.deleteRebinds()),a.expand&&m(b,j.expandRebinds()),a.edit&&m(b,j.editRebinds()),j.rebindAll(b)}},o=function(a){var b=document.createElement("div");j=new EventDispatcherControls(b,g.nodeShaper,g.edgeShaper,g.start,g.dispatcherConfig),b.id="toolbox",b.className="btn-group btn-group-vertical pull-left toolbox",d.appendChild(b),_.each(a,function(a,b){switch(b){case"expand":j.addControlExpand();break;case"create":j.addControlNewNode(),j.addControlConnect();break;case"drag":j.addControlDrag();break;case"edit":j.addControlEdit();break;case"remove":j.addControlDelete()}})},p=function(a){var b=document.createElement("div");j=new EventDispatcherControls(b,g.nodeShaper,g.edgeShaper,g.start,g.dispatcherConfig)},q=function(){return new GraphViewer(c,e,f,i,a)};d=document.body,e=d.getBoundingClientRect().width,f=d.getBoundingClientRect().height,i={type:"foxx",route:"."},a=a||{},h=l(a.toolbox),h&&(e-=43),c=k(),g=q(),h?o(a.toolbox):p(),b&&g.loadGraph(b),n(a.actions)}function LayouterControls(a,b){"use strict";if(void 0===a)throw"A list element has to be given.";if(void 0===b)throw"The Layouter has to be given.";var c=this;this.addControlGravity=function(){var c="control_layout_gravity",d=c+"_";uiComponentsHelper.createButton(a,"Gravity",c,function(){modalDialogHelper.createModalDialog("Switch Gravity Strength",d,[{type:"text",id:"value"}],function(){var a=$("#"+d+"value").attr("value");b.changeTo({gravity:a})})})},this.addControlCharge=function(){var c="control_layout_charge",d=c+"_";uiComponentsHelper.createButton(a,"Charge",c,function(){modalDialogHelper.createModalDialog("Switch Charge Strength",d,[{type:"text",id:"value"}],function(){var a=$("#"+d+"value").attr("value");b.changeTo({charge:a})})})},this.addControlDistance=function(){var c="control_layout_distance",d=c+"_";uiComponentsHelper.createButton(a,"Distance",c,function(){modalDialogHelper.createModalDialog("Switch Distance Strength",d,[{type:"text",id:"value"}],function(){var a=$("#"+d+"value").attr("value");b.changeTo({distance:a})})})},this.addAll=function(){c.addControlDistance(),c.addControlGravity(),c.addControlCharge()}}function NodeShaperControls(a,b){"use strict";if(void 0===a)throw"A list element has to be given.";if(void 0===b)throw"The NodeShaper has to be given.";var c,d=this,e=function(a){for(;c.hasChildNodes();)c.removeChild(c.lastChild);var b=document.createElement("ul");c.appendChild(b),_.each(a,function(a,c){var d=document.createElement("ul"),e=a.list,f=a.front;d.style.backgroundColor=c,d.style.color=f,_.each(e,function(a){var b=document.createElement("li");b.appendChild(document.createTextNode(a)),d.appendChild(b)}),b.appendChild(d)})};this.addControlOpticShapeNone=function(){uiComponentsHelper.createButton(a,"None","control_node_none",function(){b.changeTo({shape:{type:NodeShaper.shapes.NONE}})})},this.applyLocalStorage=function(a){if("undefined"!==Storage)try{var b=JSON.parse(localStorage.getItem("graphSettings")),c=window.location.hash.split("/")[1],d=window.location.pathname.split("/")[2],e=c+d;_.each(a,function(a,c){void 0!==c&&(b[e].viewer.nodeShaper[c]=a)}),localStorage.setItem("graphSettings",JSON.stringify(b))}catch(f){console.log(f)}},this.addControlOpticShapeCircle=function(){var c="control_node_circle",d=c+"_";uiComponentsHelper.createButton(a,"Circle",c,function(){modalDialogHelper.createModalDialog("Switch to Circle",d,[{type:"text",id:"radius"}],function(){var a=$("#"+d+"radius").attr("value");b.changeTo({shape:{type:NodeShaper.shapes.CIRCLE,radius:a}})})})},this.addControlOpticShapeRect=function(){var c="control_node_rect",d=c+"_";uiComponentsHelper.createButton(a,"Rectangle",c,function(){modalDialogHelper.createModalDialog("Switch to Rectangle","control_node_rect_",[{type:"text",id:"width"},{type:"text",id:"height"}],function(){var a=$("#"+d+"width").attr("value"),c=$("#"+d+"height").attr("value");b.changeTo({shape:{type:NodeShaper.shapes.RECT,width:a,height:c}})})})},this.addControlOpticLabel=function(){var c="control_node_label",e=c+"_";uiComponentsHelper.createButton(a,"Configure Label",c,function(){modalDialogHelper.createModalChangeDialog("Change label attribute",e,[{type:"text",id:"key"}],function(){var a=$("#"+e+"key").attr("value"),c={label:a};d.applyLocalStorage(c),b.changeTo(c)})})},this.addControlOpticSingleColour=function(){var c="control_node_singlecolour",d=c+"_";uiComponentsHelper.createButton(a,"Single Colour",c,function(){modalDialogHelper.createModalDialog("Switch to Colour",d,[{type:"text",id:"fill"},{type:"text",id:"stroke"}],function(){var a=$("#"+d+"fill").attr("value"),c=$("#"+d+"stroke").attr("value");b.changeTo({color:{type:"single",fill:a,stroke:c}})})})},this.addControlOpticAttributeColour=function(){var c="control_node_attributecolour",d=c+"_";uiComponentsHelper.createButton(a,"Colour by Attribute",c,function(){modalDialogHelper.createModalDialog("Display colour by attribute",d,[{
-type:"text",id:"key"}],function(){var a=$("#"+d+"key").attr("value");b.changeTo({color:{type:"attribute",key:a}})})})},this.addControlOpticExpandColour=function(){var c="control_node_expandcolour",d=c+"_";uiComponentsHelper.createButton(a,"Expansion Colour",c,function(){modalDialogHelper.createModalDialog("Display colours for expansion",d,[{type:"text",id:"expanded"},{type:"text",id:"collapsed"}],function(){var a=$("#"+d+"expanded").attr("value"),c=$("#"+d+"collapsed").attr("value");b.changeTo({color:{type:"expand",expanded:a,collapsed:c}})})})},this.addControlOpticLabelAndColour=function(e){var f="control_node_labelandcolour",g=f+"_";uiComponentsHelper.createButton(a,"Configure Label",f,function(){modalDialogHelper.createModalChangeDialog("Change label attribute",g,[{type:"text",id:"label-attribute",text:"Vertex label attribute",value:b.getLabel()||""},{type:"decission",id:"samecolour",group:"colour",text:"Use this attribute for coloring, too",isDefault:b.getLabel()===b.getColor()},{type:"decission",id:"othercolour",group:"colour",text:"Use different attribute for coloring",isDefault:b.getLabel()!==b.getColor(),interior:[{type:"text",id:"colour-attribute",text:"Color attribute",value:b.getColor()||""}]}],function(){var a=$("#"+g+"label-attribute").attr("value"),e=$("#"+g+"colour-attribute").attr("value"),f=$("input[type='radio'][name='colour']:checked").attr("id");f===g+"samecolour"&&(e=a);var h={label:a,color:{type:"attribute",key:e}};d.applyLocalStorage(h),b.changeTo(h),void 0===c&&(c=d.createColourMappingList())})})},this.addControlOpticLabelAndColourList=function(e){var f="control_node_labelandcolourlist",g=f+"_";uiComponentsHelper.createButton(a,"Configure Label",f,function(){modalDialogHelper.createModalChangeDialog("Change label attribute",g,[{type:"extendable",id:"label",text:"Vertex label attribute",objects:b.getLabel()},{type:"decission",id:"samecolour",group:"colour",text:"Use this attribute for coloring, too",isDefault:b.getLabel()===b.getColor()},{type:"decission",id:"othercolour",group:"colour",text:"Use different attribute for coloring",isDefault:b.getLabel()!==b.getColor(),interior:[{type:"extendable",id:"colour",text:"Color attribute",objects:b.getColor()||""}]}],function(){var a=$("input[id^="+g+"label_]"),e=$("input[id^="+g+"colour_]"),f=$("input[type='radio'][name='colour']:checked").attr("id"),h=[],i=[];a.each(function(a,b){var c=$(b).val();""!==c&&h.push(c)}),e.each(function(a,b){var c=$(b).val();""!==c&&i.push(c)}),f===g+"samecolour"&&(i=h);var j={label:h,color:{type:"attribute",key:i}};d.applyLocalStorage(j),b.changeTo(j),void 0===c&&(c=d.createColourMappingList())})})},this.addAllOptics=function(){d.addControlOpticShapeNone(),d.addControlOpticShapeCircle(),d.addControlOpticShapeRect(),d.addControlOpticLabel(),d.addControlOpticSingleColour(),d.addControlOpticAttributeColour(),d.addControlOpticExpandColour()},this.addAllActions=function(){},this.addAll=function(){d.addAllOptics(),d.addAllActions()},this.createColourMappingList=function(){return void 0!==c?c:(c=document.createElement("div"),c.id="node_colour_list",e(b.getColourMapping()),b.setColourMappingListener(e),c)}}function GraphViewer(a,b,c,d,e){"use strict";if($("html").attr("xmlns:xlink","http://www.w3.org/1999/xlink"),void 0===a||void 0===a.append)throw"SVG has to be given and has to be selected using d3.select";if(void 0===b||0>=b)throw"A width greater 0 has to be given";if(void 0===c||0>=c)throw"A height greater 0 has to be given";if(void 0===d||void 0===d.type)throw"An adapter configuration has to be given";var f,g,h,i,j,k,l,m,n=this,o=[],p=[],q=function(a){if(!a)return a={},a.nodes=p,a.links=o,a.width=b,a.height=c,void(i=new ForceLayouter(a));switch(a.type.toLowerCase()){case"force":a.nodes=p,a.links=o,a.width=b,a.height=c,i=new ForceLayouter(a);break;default:throw"Sorry unknown layout type."}},r=function(a){f.setNodeLimit(a,n.start)},s=function(d){d&&(j=new ZoomManager(b,c,a,k,g,h,{},r))},t=function(a){var b=a.edgeShaper||{},c=a.nodeShaper||{},d=c.idfunc||void 0,e=a.zoom||!1;b.shape=b.shape||{type:EdgeShaper.shapes.ARROW},q(a.layouter),m=k.append("g"),h=new EdgeShaper(m,b),l=k.append("g"),g=new NodeShaper(l,c,d),i.setCombinedUpdateFunction(g,h),s(e)};switch(d.type.toLowerCase()){case"arango":d.width=b,d.height=c,f=new ArangoAdapter(p,o,this,d),f.setChildLimit(10);break;case"gharial":d.width=b,d.height=c,f=new GharialAdapter(p,o,this,d),f.setChildLimit(10);break;case"foxx":d.width=b,d.height=c,f=new FoxxAdapter(p,o,d.route,this,d);break;case"json":f=new JSONAdapter(d.path,p,o,this,b,c);break;case"preview":d.width=b,d.height=c,f=new PreviewAdapter(p,o,this,d);break;default:throw"Sorry unknown adapter type."}k=a.append("g"),t(e||{}),this.start=function(a){i.stop(),a&&(""!==$(".infoField").text()?_.each(p,function(a){_.each(f.randomNodes,function(b){a._id===b._id&&(a._expanded=!0)})}):_.each(p,function(a){a._expanded=!0})),g.drawNodes(p),h.drawEdges(o),i.start()},this.loadGraph=function(a,b){f.loadInitialNode(a,function(a){return a.errorCode?void b(a):(a._expanded=!0,n.start(),void(_.isFunction(b)&&b()))})},this.loadGraphWithRandomStart=function(a,b){f.loadRandomNode(function(b){return b.errorCode&&404===b.errorCode?void a(b):(b._expanded=!0,n.start(!0),void(_.isFunction(a)&&a()))},b)},this.loadGraphWithAdditionalNode=function(a,b,c){f.loadAdditionalNodeByAttributeValue(a,b,function(a){return a.errorCode?void c(a):(a._expanded=!0,n.start(),void(_.isFunction(c)&&c()))})},this.loadGraphWithAttributeValue=function(a,b,c){f.randomNodes=[],f.definedNodes=[],f.loadInitialNodeByAttributeValue(a,b,function(a){return a.errorCode?void c(a):(a._expanded=!0,n.start(),void(_.isFunction(c)&&c()))})},this.cleanUp=function(){g.resetColourMap(),h.resetColourMap()},this.changeWidth=function(a){i.changeWidth(a),j.changeWidth(a),f.setWidth(a)},this.dispatcherConfig={expand:{edges:o,nodes:p,startCallback:n.start,adapter:f,reshapeNodes:g.reshapeNodes},drag:{layouter:i},nodeEditor:{nodes:p,adapter:f},edgeEditor:{edges:o,adapter:f}},this.adapter=f,this.nodeShaper=g,this.edgeShaper=h,this.layouter=i,this.zoomManager=j}EdgeShaper.shapes=Object.freeze({NONE:0,ARROW:1}),NodeShaper.shapes=Object.freeze({NONE:0,CIRCLE:1,RECT:2,IMAGE:3});var modalDialogHelper=modalDialogHelper||{};!function(){"use strict";var a,b=function(a){$(document).bind("keypress.key13",function(b){b.which&&13===b.which&&$(a).click()})},c=function(){$(document).unbind("keypress.key13")},d=function(a,b,c,d,e){var f,g,h=function(){e(f)},i=modalDialogHelper.modalDivTemplate(a,b,c,h),j=document.createElement("tr"),k=document.createElement("th"),l=document.createElement("th"),m=document.createElement("th"),n=document.createElement("button"),o=1;f=function(){var a={};return _.each($("#"+c+"table tr:not(#first_row)"),function(b){var c=$(".keyCell input",b).val(),d=$(".valueCell input",b).val();a[c]=d}),a},i.appendChild(j),j.id="first_row",j.appendChild(k),k.className="keyCell",j.appendChild(l),l.className="valueCell",j.appendChild(m),m.className="actionCell",m.appendChild(n),n.id=c+"new",n.className="graphViewer-icon-button gv-icon-small add",g=function(a,b){var d,e,f,g=/^_(id|rev|key|from|to)/,h=document.createElement("tr"),j=document.createElement("th"),k=document.createElement("th"),l=document.createElement("th");g.test(b)||(i.appendChild(h),h.appendChild(k),k.className="keyCell",e=document.createElement("input"),e.type="text",e.id=c+b+"_key",e.value=b,k.appendChild(e),h.appendChild(l),l.className="valueCell",f=document.createElement("input"),f.type="text",f.id=c+b+"_value","object"==typeof a?f.value=JSON.stringify(a):f.value=a,l.appendChild(f),h.appendChild(j),j.className="actionCell",d=document.createElement("button"),d.id=c+b+"_delete",d.className="graphViewer-icon-button gv-icon-small delete",j.appendChild(d),d.onclick=function(){i.removeChild(h)})},n.onclick=function(){g("","new_"+o),o++},_.each(d,g),$("#"+c+"modal").modal("show")},e=function(a,b,c,d,e){var f=modalDialogHelper.modalDivTemplate(a,b,c,e),g=document.createElement("tr"),h=document.createElement("th"),i=document.createElement("pre");f.appendChild(g),g.appendChild(h),h.appendChild(i),i.className="gv-object-view",i.innerHTML=JSON.stringify(d,null,2),$("#"+c+"modal").modal("show")},f=function(a,b){var c=document.createElement("input");return c.type="text",c.id=a,c.value=b,c},g=function(a,b){var c=document.createElement("input");return c.type="checkbox",c.id=a,c.checked=b,c},h=function(a,b,c){var d=document.createElement("select");return d.id=a,_.each(_.sortBy(b,function(a){return a.toLowerCase()}),function(a){var b=document.createElement("option");b.value=a,b.selected=a===c,b.appendChild(document.createTextNode(a)),d.appendChild(b)}),d},i=function(a){var b=$(".decission_"+a),c=$("input[type='radio'][name='"+a+"']:checked").attr("id");b.each(function(){$(this).attr("decider")===c?$(this).css("display",""):$(this).css("display","none")})},j=function(b,c,d,e,f,g,h,j){var k=document.createElement("input"),l=b+c,m=document.createElement("label"),n=document.createElement("tbody");k.id=l,k.type="radio",k.name=d,k.className="gv-radio-button",m.className="radio",h.appendChild(m),m.appendChild(k),m.appendChild(document.createTextNode(e)),j.appendChild(n),$(n).toggleClass("decission_"+d,!0),$(n).attr("decider",l),_.each(g,function(c){a(n,b,c)}),f?k.checked=!0:k.checked=!1,m.onclick=function(a){i(d),a.stopPropagation()},i(d)},k=function(a,b,c,d,e,f){var g,h=[],i=a+b,j=1,k=document.createElement("th"),l=document.createElement("button"),m=document.createElement("input"),n=function(a){j++;var c,d=document.createElement("tr"),g=document.createElement("th"),k=document.createElement("th"),l=document.createElement("th"),m=document.createElement("input"),n=document.createElement("button");m.type="text",m.id=i+"_"+j,m.value=a||"",c=0===h.length?$(f):$(h[h.length-1]),c.after(d),d.appendChild(g),g.className="collectionTh capitalize",g.appendChild(document.createTextNode(b+" "+j+":")),d.appendChild(k),k.className="collectionTh",k.appendChild(m),n.id=i+"_"+j+"_remove",n.className="graphViewer-icon-button gv-icon-small delete",n.onclick=function(){e.removeChild(d),h.splice(h.indexOf(d),1)},l.appendChild(n),d.appendChild(l),h.push(d)};for(m.type="text",m.id=i+"_1",d.appendChild(m),k.appendChild(l),f.appendChild(k),l.onclick=function(){n()},l.id=i+"_addLine",l.className="graphViewer-icon-button gv-icon-small add","string"==typeof c&&c.length>0&&(c=[c]),c.length>0&&(m.value=c[0]),g=1;g'+c+""),a.disabled||$("#subNavigationBar .bottom").children().last().bind("click",function(){window.App.navigate(a.route,{trigger:!0})})})},buildUserSubNav:function(a,b){var c={General:{route:"#user/"+encodeURIComponent(a)},Permissions:{route:"#user/"+encodeURIComponent(a)+"/permission"}};c[b].active=!0,this.buildSubNavBar(c)},buildGraphSubNav:function(a,b){var c={Content:{route:"#graph2/"+encodeURIComponent(a)},Settings:{route:"#graph2/"+encodeURIComponent(a)+"/settings"}};c[b].active=!0,this.buildSubNavBar(c)},buildNodeSubNav:function(a,b,c){var d={Dashboard:{route:"#node/"+encodeURIComponent(a)}};d[b].active=!0,d[c].disabled=!0,this.buildSubNavBar(d)},buildNodesSubNav:function(a,b){var c={Overview:{route:"#nodes"},Shards:{route:"#shards"}};c[a].active=!0,b&&(c[b].disabled=!0),this.buildSubNavBar(c)},scaleability:void 0,buildCollectionSubNav:function(a,b){var c="#collection/"+encodeURIComponent(a),d={Content:{route:c+"/documents/1"},Indices:{route:"#cIndices/"+encodeURIComponent(a)},Info:{route:"#cInfo/"+encodeURIComponent(a)},Settings:{route:"#cSettings/"+encodeURIComponent(a)}};d[b].active=!0,this.buildSubNavBar(d)},enableKeyboardHotkeys:function(a){var b=window.arangoHelper.hotkeysFunctions;a===!0&&($(document).on("keydown",null,"j",b.scrollDown),$(document).on("keydown",null,"k",b.scrollUp))},databaseAllowed:function(a){var b=function(b,c){b?arangoHelper.arangoError("",""):$.ajax({type:"GET",cache:!1,url:this.databaseUrl("/_api/database/",c),contentType:"application/json",processData:!1,success:function(){a(!1,!0)},error:function(){a(!0,!1)}})}.bind(this);this.currentDatabase(b)},arangoNotification:function(a,b,c){window.App.notificationList.add({title:a,content:b,info:c,type:"success"})},arangoError:function(a,b,c){window.App.notificationList.add({title:a,content:b,info:c,type:"error"})},arangoWarning:function(a,b,c){window.App.notificationList.add({title:a,content:b,info:c,type:"warning"})},arangoMessage:function(a,b,c){window.App.notificationList.add({title:a,content:b,info:c,type:"message"})},hideArangoNotifications:function(){$.noty.clearQueue(),$.noty.closeAll()},openDocEditor:function(a,b,c){var d=a.split("/"),e=this,f=new window.DocumentView({collection:window.App.arangoDocumentStore});f.breadcrumb=function(){},f.colid=d[0],f.docid=d[1],f.el=".arangoFrame .innerDiv",f.render(),f.setType(b),$(".arangoFrame .headerBar").remove(),$(".arangoFrame .outerDiv").prepend(''),$(".arangoFrame .outerDiv").click(function(){e.closeDocEditor()}),$(".arangoFrame .innerDiv").click(function(a){a.stopPropagation()}),$(".fa-times").click(function(){e.closeDocEditor()}),$(".arangoFrame").show(),f.customView=!0,f.customDeleteFunction=function(){window.modalView.hide(),$(".arangoFrame").hide()},$(".arangoFrame #deleteDocumentButton").click(function(){f.deleteDocumentModal()}),$(".arangoFrame #saveDocumentButton").click(function(){f.saveDocument()}),$(".arangoFrame #deleteDocumentButton").css("display","none")},closeDocEditor:function(){$(".arangoFrame .outerDiv .fa-times").remove(),$(".arangoFrame").hide()},addAardvarkJob:function(a,b){$.ajax({cache:!1,type:"POST",url:this.databaseUrl("/_admin/aardvark/job"),data:JSON.stringify(a),contentType:"application/json",processData:!1,success:function(a){b&&b(!1,a)},error:function(a){b&&b(!0,a)}})},deleteAardvarkJob:function(a,b){$.ajax({cache:!1,type:"DELETE",url:this.databaseUrl("/_admin/aardvark/job/"+encodeURIComponent(a)),contentType:"application/json",processData:!1,success:function(a){b&&b(!1,a)},error:function(a){b&&b(!0,a)}})},deleteAllAardvarkJobs:function(a){$.ajax({cache:!1,type:"DELETE",url:this.databaseUrl("/_admin/aardvark/job"),contentType:"application/json",processData:!1,success:function(b){a&&a(!1,b)},error:function(b){a&&a(!0,b)}})},getAardvarkJobs:function(a){$.ajax({cache:!1,type:"GET",url:this.databaseUrl("/_admin/aardvark/job"),contentType:"application/json",processData:!1,success:function(b){a&&a(!1,b)},error:function(b){a&&a(!0,b)}})},getPendingJobs:function(a){$.ajax({cache:!1,type:"GET",url:this.databaseUrl("/_api/job/pending"),contentType:"application/json",processData:!1,success:function(b){a(!1,b)},error:function(b){a(!0,b)}})},syncAndReturnUninishedAardvarkJobs:function(a,b){var c=function(c,d){if(c)b(!0);else{var e=function(c,e){if(c)arangoHelper.arangoError("","");else{var f=[];e.length>0?_.each(d,function(b){if(b.type===a||void 0===b.type){var c=!1;_.each(e,function(a){b.id===a&&(c=!0)}),c?f.push({collection:b.collection,id:b.id,type:b.type,desc:b.desc}):window.arangoHelper.deleteAardvarkJob(b.id)}}):d.length>0&&this.deleteAllAardvarkJobs(),b(!1,f)}}.bind(this);this.getPendingJobs(e)}}.bind(this);this.getAardvarkJobs(c)},getRandomToken:function(){return Math.round((new Date).getTime())},isSystemAttribute:function(a){var b=this.systemAttributes();return b[a]},isSystemCollection:function(a){return"_"===a.name.substr(0,1)},setDocumentStore:function(a){this.arangoDocumentStore=a},collectionApiType:function(a,b,c){if(b||void 0===this.CollectionTypes[a]){var d=function(b,c,d){b?arangoHelper.arangoError("Error","Could not detect collection type"):(this.CollectionTypes[a]=c.type,3===this.CollectionTypes[a]?d(!1,"edge"):d(!1,"document"))}.bind(this);this.arangoDocumentStore.getCollectionInfo(a,d,c)}else c(!1,this.CollectionTypes[a])},collectionType:function(a){if(!a||""===a.name)return"-";var b;return b=2===a.type?"document":3===a.type?"edge":"unknown",this.isSystemCollection(a)&&(b+=" (system)"),b},formatDT:function(a){var b=function(a){return 10>a?"0"+a:a};return a.getUTCFullYear()+"-"+b(a.getUTCMonth()+1)+"-"+b(a.getUTCDate())+" "+b(a.getUTCHours())+":"+b(a.getUTCMinutes())+":"+b(a.getUTCSeconds())},escapeHtml:function(a){return String(a).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")},backendUrl:function(a){return frontendConfig.basePath+a},databaseUrl:function(a,b){if("/_db/"===a.substr(0,5))throw new Error("Calling databaseUrl with a databased url ("+a+") doesn't make any sense");return b||(b="_system",frontendConfig.db&&(b=frontendConfig.db)),this.backendUrl("/_db/"+encodeURIComponent(b)+a)},showAuthDialog:function(){var a=!0,b=localStorage.getItem("authenticationNotification");return"false"===b&&(a=!1),a},doNotShowAgain:function(){localStorage.setItem("authenticationNotification",!1)},renderEmpty:function(a){$("#content").html('
'+a+"
")},download:function(a,b){$.ajax(a).success(function(a,c,d){if(b)return void b(a);var e=new Blob([JSON.stringify(a)],{type:d.getResponseHeader("Content-Type")||"application/octet-stream"}),f=window.URL.createObjectURL(e),g=document.createElement("a");document.body.appendChild(g),g.style="display: none",g.href=f,g.download=d.getResponseHeader("Content-Disposition").replace(/.* filename="([^")]*)"/,"$1"),g.click(),window.URL.revokeObjectURL(f),document.body.removeChild(g)})}}}(),function(){"use strict";if(!window.hasOwnProperty("TEST_BUILD")){var a=function(){var a={};return a.createTemplate=function(a){var b=$("#"+a.replace(".","\\.")).html();return{render:function(a){var c=_.template(b);return c=c(a)}}},a};window.templateEngine=new a}}(),function(){"use strict";window.dygraphConfig={defaultFrame:12e5,zeropad:function(a){return 10>a?"0"+a:a},xAxisFormat:function(a){if(-1===a)return"";var b=new Date(a);return this.zeropad(b.getHours())+":"+this.zeropad(b.getMinutes())+":"+this.zeropad(b.getSeconds())},mergeObjects:function(a,b,c){c||(c=[]);var d,e={};return c.forEach(function(c){var d=a[c],f=b[c];void 0===d&&(d={}),void 0===f&&(f={}),e[c]=_.extend(d,f)}),d=_.extend(a,b),Object.keys(e).forEach(function(a){d[a]=e[a]}),d},mapStatToFigure:{pageFaults:["times","majorPageFaultsPerSecond","minorPageFaultsPerSecond"],systemUserTime:["times","systemTimePerSecond","userTimePerSecond"],totalTime:["times","avgQueueTime","avgRequestTime","avgIoTime"],dataTransfer:["times","bytesSentPerSecond","bytesReceivedPerSecond"],requests:["times","getsPerSecond","putsPerSecond","postsPerSecond","deletesPerSecond","patchesPerSecond","headsPerSecond","optionsPerSecond","othersPerSecond"]},colors:["rgb(95, 194, 135)","rgb(238, 190, 77)","#81ccd8","#7ca530","#3c3c3c","#aa90bd","#e1811d","#c7d4b2","#d0b2d4"],figureDependedOptions:{clusterRequestsPerSecond:{showLabelsOnHighlight:!0,title:"",header:"Cluster Requests per Second",stackedGraph:!0,div:"lineGraphLegend",labelsKMG2:!1,axes:{y:{valueFormatter:function(a){return parseFloat(a.toPrecision(3))},axisLabelFormatter:function(a){return 0===a?0:parseFloat(a.toPrecision(3))}}}},pageFaults:{header:"Page Faults",visibility:[!0,!1],labels:["datetime","Major Page","Minor Page"],div:"pageFaultsChart",labelsKMG2:!1,axes:{y:{valueFormatter:function(a){return parseFloat(a.toPrecision(3))},axisLabelFormatter:function(a){return 0===a?0:parseFloat(a.toPrecision(3))}}}},systemUserTime:{div:"systemUserTimeChart",header:"System and User Time",labels:["datetime","System Time","User Time"],stackedGraph:!0,labelsKMG2:!1,axes:{y:{valueFormatter:function(a){return parseFloat(a.toPrecision(3))},axisLabelFormatter:function(a){return 0===a?0:parseFloat(a.toPrecision(3))}}}},totalTime:{div:"totalTimeChart",header:"Total Time",labels:["datetime","Queue","Computation","I/O"],labelsKMG2:!1,axes:{y:{valueFormatter:function(a){return parseFloat(a.toPrecision(3))},axisLabelFormatter:function(a){return 0===a?0:parseFloat(a.toPrecision(3))}}},stackedGraph:!0},dataTransfer:{header:"Data Transfer",labels:["datetime","Bytes sent","Bytes received"],stackedGraph:!0,div:"dataTransferChart"},requests:{header:"Requests",labels:["datetime","Reads","Writes"],stackedGraph:!0,div:"requestsChart",axes:{y:{valueFormatter:function(a){return parseFloat(a.toPrecision(3))},axisLabelFormatter:function(a){return 0===a?0:parseFloat(a.toPrecision(3))}}}}},getDashBoardFigures:function(a){var b=[],c=this;return Object.keys(this.figureDependedOptions).forEach(function(d){"clusterRequestsPerSecond"!==d&&(c.figureDependedOptions[d].div||a)&&b.push(d)}),b},getDefaultConfig:function(a){var b=this,c={digitsAfterDecimal:1,drawGapPoints:!0,fillGraph:!0,fillAlpha:.85,showLabelsOnHighlight:!1,strokeWidth:0,lineWidth:0,strokeBorderWidth:0,includeZero:!0,highlightCircleSize:2.5,labelsSeparateLines:!0,strokeBorderColor:"rgba(0,0,0,0)",interactionModel:{},maxNumberWidth:10,colors:[this.colors[0]],xAxisLabelWidth:"50",rightGap:15,showRangeSelector:!1,rangeSelectorHeight:50,rangeSelectorPlotStrokeColor:"#365300",rangeSelectorPlotFillColor:"",pixelsPerLabel:50,labelsKMG2:!0,dateWindow:[(new Date).getTime()-this.defaultFrame,(new Date).getTime()],axes:{x:{valueFormatter:function(a){return b.xAxisFormat(a)}},y:{ticker:Dygraph.numericLinearTicks}}};return this.figureDependedOptions[a]&&(c=this.mergeObjects(c,this.figureDependedOptions[a],["axes"]),c.div&&c.labels&&(c.colors=this.getColors(c.labels),c.labelsDiv=document.getElementById(c.div+"Legend"),c.legend="always",c.showLabelsOnHighlight=!0)),c},getDetailChartConfig:function(a){var b=_.extend(this.getDefaultConfig(a),{showRangeSelector:!0,interactionModel:null,showLabelsOnHighlight:!0,highlightCircleSize:2.5,legend:"always",labelsDiv:"div#detailLegend.dashboard-legend-inner"});return"pageFaults"===a&&(b.visibility=[!0,!0]),b.labels||(b.labels=["datetime",b.header],b.colors=this.getColors(b.labels)),b},getColors:function(a){var b;return b=this.colors.concat([]),b.slice(0,a.length-1)}}}(),function(){"use strict";window.arangoCollectionModel=Backbone.Model.extend({idAttribute:"name",urlRoot:arangoHelper.databaseUrl("/_api/collection"),defaults:{id:"",name:"",status:"",type:"",isSystem:!1,picture:"",locked:!1,desc:void 0},getProperties:function(a){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/collection/"+encodeURIComponent(this.get("id"))+"/properties"),contentType:"application/json",processData:!1,success:function(b){a(!1,b)},error:function(b){a(!0,b)}})},getFigures:function(a){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/figures"),contentType:"application/json",processData:!1,success:function(b){a(!1,b)},error:function(){a(!0)}})},getRevision:function(a,b){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/revision"),contentType:"application/json",processData:!1,success:function(c){a(!1,c,b)},error:function(){a(!0)}})},getIndex:function(a){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/index/?collection="+this.get("id")),contentType:"application/json",processData:!1,success:function(b){a(!1,b)},error:function(b){a(!0,b)}})},createIndex:function(a,b){var c=this;$.ajax({cache:!1,type:"POST",url:arangoHelper.databaseUrl("/_api/index?collection="+c.get("id")),headers:{"x-arango-async":"store"},data:JSON.stringify(a),contentType:"application/json",processData:!1,success:function(a,d,e){e.getResponseHeader("x-arango-async-id")?(window.arangoHelper.addAardvarkJob({id:e.getResponseHeader("x-arango-async-id"),type:"index",desc:"Creating Index",collection:c.get("id")}),b(!1,a)):b(!0,a)},error:function(a){b(!0,a)}})},deleteIndex:function(a,b){
-var c=this;$.ajax({cache:!1,type:"DELETE",url:arangoHelper.databaseUrl("/_api/index/"+this.get("name")+"/"+encodeURIComponent(a)),headers:{"x-arango-async":"store"},success:function(a,d,e){e.getResponseHeader("x-arango-async-id")?(window.arangoHelper.addAardvarkJob({id:e.getResponseHeader("x-arango-async-id"),type:"index",desc:"Removing Index",collection:c.get("id")}),b(!1,a)):b(!0,a)},error:function(a){b(!0,a)}}),b()},truncateCollection:function(){$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/truncate"),success:function(){arangoHelper.arangoNotification("Collection truncated.")},error:function(){arangoHelper.arangoError("Collection error.")}})},loadCollection:function(a){$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/load"),success:function(){a(!1)},error:function(){a(!0)}}),a()},unloadCollection:function(a){$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/unload?flush=true"),success:function(){a(!1)},error:function(){a(!0)}}),a()},renameCollection:function(a,b){var c=this;$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/rename"),data:JSON.stringify({name:a}),contentType:"application/json",processData:!1,success:function(){c.set("name",a),b(!1)},error:function(a){b(!0,a)}})},changeCollection:function(a,b,c,d){var e=!1;"true"===a?a=!0:"false"===a&&(a=!1);var f={waitForSync:a,journalSize:parseInt(b,10),indexBuckets:parseInt(c,10)};return $.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/collection/"+this.get("id")+"/properties"),data:JSON.stringify(f),contentType:"application/json",processData:!1,success:function(){d(!1)},error:function(a){d(!1,a)}}),e}})}(),window.DatabaseModel=Backbone.Model.extend({idAttribute:"name",initialize:function(){"use strict"},isNew:function(){"use strict";return!1},sync:function(a,b,c){"use strict";return"update"===a&&(a="create"),Backbone.sync(a,b,c)},url:arangoHelper.databaseUrl("/_api/database"),defaults:{}}),window.arangoDocumentModel=Backbone.Model.extend({initialize:function(){"use strict"},urlRoot:arangoHelper.databaseUrl("/_api/document"),defaults:{_id:"",_rev:"",_key:""},getSorted:function(){"use strict";var a=this,b=Object.keys(a.attributes).sort(function(a,b){var c=arangoHelper.isSystemAttribute(a),d=arangoHelper.isSystemAttribute(b);return c!==d?c?-1:1:b>a?-1:1}),c={};return _.each(b,function(b){c[b]=a.attributes[b]}),c}}),function(){"use strict";window.ArangoQuery=Backbone.Model.extend({urlRoot:arangoHelper.databaseUrl("/_api/user"),defaults:{name:"",type:"custom",value:""}})}(),window.Replication=Backbone.Model.extend({defaults:{state:{},server:{}},initialize:function(){}}),window.Statistics=Backbone.Model.extend({defaults:{},url:function(){"use strict";return"/_admin/statistics"}}),window.StatisticsDescription=Backbone.Model.extend({defaults:{figures:"",groups:""},url:function(){"use strict";return"/_admin/statistics-description"}}),window.Users=Backbone.Model.extend({defaults:{user:"",active:!1,extra:{}},idAttribute:"user",parse:function(a){return this.isNotNew=!0,a},isNew:function(){return!this.isNotNew},url:function(){return this.isNew()?arangoHelper.databaseUrl("/_api/user"):""!==this.get("user")?arangoHelper.databaseUrl("/_api/user/"+this.get("user")):arangoHelper.databaseUrl("/_api/user")},checkPassword:function(a,b){$.ajax({cache:!1,type:"POST",url:arangoHelper.databaseUrl("/_api/user/"+this.get("user")),data:JSON.stringify({passwd:a}),contentType:"application/json",processData:!1,success:function(a){b(!1,a)},error:function(a){b(!0,a)}})},setPassword:function(a){$.ajax({cache:!1,type:"PATCH",url:arangoHelper.databaseUrl("/_api/user/"+this.get("user")),data:JSON.stringify({passwd:a}),contentType:"application/json",processData:!1})},setExtras:function(a,b,c){$.ajax({cache:!1,type:"PATCH",url:arangoHelper.databaseUrl("/_api/user/"+this.get("user")),data:JSON.stringify({extra:{name:a,img:b}}),contentType:"application/json",processData:!1,success:function(){c(!1)},error:function(){c(!0)}})}}),function(){"use strict";window.ClusterCoordinator=Backbone.Model.extend({defaults:{name:"",status:"ok",address:"",protocol:""},idAttribute:"name",forList:function(){return{name:this.get("name"),status:this.get("status"),url:this.get("url")}}})}(),function(){"use strict";window.ClusterServer=Backbone.Model.extend({defaults:{name:"",address:"",role:"",status:"ok"},idAttribute:"name",forList:function(){return{name:this.get("name"),address:this.get("address"),status:this.get("status")}}})}(),function(){"use strict";window.Coordinator=Backbone.Model.extend({defaults:{address:"",protocol:"",name:"",status:""}})}(),function(){"use strict";window.CurrentDatabase=Backbone.Model.extend({url:arangoHelper.databaseUrl("/_api/database/current",frontendConfig.db),parse:function(a){return a.result}})}(),function(){"use strict";var a=function(a,b,c,d,e,f){var g={contentType:"application/json",processData:!1,type:c};b=b||function(){},f=_.extend({mount:a.encodedMount()},f);var h=_.reduce(f,function(a,b,c){return a+encodeURIComponent(c)+"="+encodeURIComponent(b)+"&"},"?");g.url=arangoHelper.databaseUrl("/_admin/aardvark/foxxes"+(d?"/"+d:"")+h.slice(0,h.length-1)),void 0!==e&&(g.data=JSON.stringify(e)),$.ajax(g).then(function(a){b(null,a)},function(a){window.xhr=a,b(_.extend(a.status?new Error(a.responseJSON?a.responseJSON.errorMessage:a.responseText):new Error("Network Error"),{statusCode:a.status}))})};window.Foxx=Backbone.Model.extend({idAttribute:"mount",defaults:{author:"Unknown Author",name:"",version:"Unknown Version",description:"No description",license:"Unknown License",contributors:[],scripts:{},config:{},deps:{},git:"",system:!1,development:!1},isNew:function(){return!1},encodedMount:function(){return encodeURIComponent(this.get("mount"))},destroy:function(b,c){a(this,c,"DELETE",void 0,void 0,b)},isBroken:function(){return!1},needsAttention:function(){return this.isBroken()||this.needsConfiguration()||this.hasUnconfiguredDependencies()},needsConfiguration:function(){return _.any(this.get("config"),function(a){return void 0===a.current&&a.required!==!1})},hasUnconfiguredDependencies:function(){return _.any(this.get("deps"),function(a){return void 0===a.current&&a.definition.required!==!1})},getConfiguration:function(b){a(this,function(a,c){a||this.set("config",c),"function"==typeof b&&b(a,c)}.bind(this),"GET","config")},setConfiguration:function(b,c){a(this,c,"PATCH","config",b)},getDependencies:function(b){a(this,function(a,c){a||this.set("deps",c),"function"==typeof b&&b(a,c)}.bind(this),"GET","deps")},setDependencies:function(b,c){a(this,c,"PATCH","deps",b)},toggleDevelopment:function(b,c){a(this,function(a,d){a||this.set("development",b),"function"==typeof c&&c(a,d)}.bind(this),"PATCH","devel",b)},runScript:function(b,c,d){a(this,d,"POST","scripts/"+b,c)},runTests:function(b,c){a(this,function(a,b){"function"==typeof c&&c(a?a.responseJSON:a,b)},"POST","tests",b)},isSystem:function(){return this.get("system")},isDevelopment:function(){return this.get("development")},download:function(){a(this,function(a,b){return a?void console.error(a.responseJSON):void(window.location.href=arangoHelper.databaseUrl("/_admin/aardvark/foxxes/download/zip?mount="+this.encodedMount()+"&nonce="+b.nonce))}.bind(this),"POST","download/nonce")},fetchThumbnail:function(a){var b=new XMLHttpRequest;b.responseType="blob",b.onload=function(){this.thumbnailUrl=URL.createObjectURL(b.response),a()}.bind(this),b.onerror=a,b.open("GET","foxxes/thumbnail?mount="+this.encodedMount()),window.arangoHelper.getCurrentJwt()&&b.setRequestHeader("Authorization","bearer "+window.arangoHelper.getCurrentJwt()),b.send()}})}(),function(){"use strict";window.Graph=Backbone.Model.extend({idAttribute:"_key",urlRoot:arangoHelper.databaseUrl("/_api/gharial"),isNew:function(){return!this.get("_id")},parse:function(a){return a.graph||a},addEdgeDefinition:function(a){$.ajax({async:!1,type:"POST",url:this.urlRoot+"/"+this.get("_key")+"/edge",data:JSON.stringify(a)})},deleteEdgeDefinition:function(a){$.ajax({async:!1,type:"DELETE",url:this.urlRoot+"/"+this.get("_key")+"/edge/"+a})},modifyEdgeDefinition:function(a){$.ajax({async:!1,type:"PUT",url:this.urlRoot+"/"+this.get("_key")+"/edge/"+a.collection,data:JSON.stringify(a)})},addVertexCollection:function(a){$.ajax({async:!1,type:"POST",url:this.urlRoot+"/"+this.get("_key")+"/vertex",data:JSON.stringify({collection:a})})},deleteVertexCollection:function(a){$.ajax({async:!1,type:"DELETE",url:this.urlRoot+"/"+this.get("_key")+"/vertex/"+a})},defaults:{name:"",edgeDefinitions:[],orphanCollections:[]}})}(),function(){"use strict";window.newArangoLog=Backbone.Model.extend({defaults:{lid:"",level:"",timestamp:"",text:"",totalAmount:""},getLogStatus:function(){switch(this.get("level")){case 1:return"Error";case 2:return"Warning";case 3:return"Info";case 4:return"Debug";default:return"Unknown"}}})}(),function(){"use strict";window.Notification=Backbone.Model.extend({defaults:{title:"",date:0,content:"",priority:"",tags:"",seen:!1}})}(),function(){"use strict";window.queryManagementModel=Backbone.Model.extend({defaults:{id:"",query:"",started:"",runTime:""}})}(),window.UserConfig=Backbone.Model.extend({defaults:{graphs:"",queries:[]},model:window.UserConfigModel,parse:function(a){return a.result},url:function(){return window.App.currentUser?this.username=window.App.currentUser:this.username="root",arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(this.username)+"/config")},setItem:function(a,b,c){var d=this;$.ajax({type:"PUT",cache:!1,url:arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(this.username)+"/config/"+encodeURIComponent(a)),contentType:"application/json",processData:!1,data:JSON.stringify({value:b}),async:!0,success:function(){d.set(a,b),c&&c()},error:function(){arangoHelper.arangoError("User configuration","Could not update user configuration for key: "+a)}})},getItem:function(a,b){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(this.username)+"/config/"+encodeURIComponent(a)),contentType:"application/json",processData:!1,async:!0,success:function(a){b(a)},error:function(){arangoHelper.arangoError("User configuration","Could not fetch user configuration for key: "+a)}})}}),function(){"use strict";window.workMonitorModel=Backbone.Model.extend({defaults:{name:"",number:"",status:"",type:""}})}(),function(){"use strict";window.AutomaticRetryCollection=Backbone.Collection.extend({_retryCount:0,checkRetries:function(){var a=this;return this.updateUrl(),this._retryCount>10?(window.setTimeout(function(){a._retryCount=0},1e4),window.App.clusterUnreachable(),!1):!0},successFullTry:function(){this._retryCount=0},failureTry:function(a,b,c){401===c.status?window.App.requestAuth():(window.App.clusterPlan.rotateCoordinator(),this._retryCount++,a())}})}(),function(){"use strict";window.PaginatedCollection=Backbone.Collection.extend({page:0,pagesize:10,totalAmount:0,getPage:function(){return this.page+1},setPage:function(a){return a>=this.getLastPageNumber()?void(this.page=this.getLastPageNumber()-1):1>a?void(this.page=0):void(this.page=a-1)},getLastPageNumber:function(){return Math.max(Math.ceil(this.totalAmount/this.pagesize),1)},getOffset:function(){return this.page*this.pagesize},getPageSize:function(){return this.pagesize},setPageSize:function(a){if("all"===a)this.pagesize="all";else try{a=parseInt(a,10),this.pagesize=a}catch(b){}},setToFirst:function(){this.page=0},setToLast:function(){this.setPage(this.getLastPageNumber())},setToPrev:function(){this.setPage(this.getPage()-1)},setToNext:function(){this.setPage(this.getPage()+1)},setTotal:function(a){this.totalAmount=a},getTotal:function(){return this.totalAmount},setTotalMinusOne:function(){this.totalAmount--}})}(),window.ClusterStatisticsCollection=Backbone.Collection.extend({model:window.Statistics,url:"/_admin/statistics",updateUrl:function(){this.url=window.App.getNewRoute(this.host)+this.url},initialize:function(a,b){this.host=b.host,window.App.registerForUpdate(this)}}),function(){"use strict";window.ArangoCollections=Backbone.Collection.extend({url:arangoHelper.databaseUrl("/_api/collection"),model:arangoCollectionModel,searchOptions:{searchPhrase:null,includeSystem:!1,includeDocument:!0,includeEdge:!0,includeLoaded:!0,includeUnloaded:!0,sortBy:"name",sortOrder:1},translateStatus:function(a){switch(a){case 0:return"corrupted";case 1:return"new born collection";case 2:return"unloaded";case 3:return"loaded";case 4:return"unloading";case 5:return"deleted";case 6:return"loading";default:return}},translateTypePicture:function(a){var b="";switch(a){case"document":b+="fa-file-text-o";break;case"edge":b+="fa-share-alt";break;case"unknown":b+="fa-question";break;default:b+="fa-cogs"}return b},parse:function(a){var b=this;return _.each(a.result,function(a){a.isSystem=arangoHelper.isSystemCollection(a),a.type=arangoHelper.collectionType(a),a.status=b.translateStatus(a.status),a.picture=b.translateTypePicture(a.type)}),a.result},getPosition:function(a){var b,c=this.getFiltered(this.searchOptions),d=null,e=null;for(b=0;b0&&(d=c[b-1]),b0){var e,f=d.get("name").toLowerCase();for(e=0;ed?-1:1):0}),b},newCollection:function(a,b){var c={};c.name=a.collName,c.waitForSync=a.wfs,a.journalSize>0&&(c.journalSize=a.journalSize),c.isSystem=a.isSystem,c.type=parseInt(a.collType,10),a.shards&&(c.numberOfShards=a.shards,c.shardKeys=a.keys),a.replicationFactor&&(c.replicationFactor=JSON.parse(a.replicationFactor)),$.ajax({cache:!1,type:"POST",url:arangoHelper.databaseUrl("/_api/collection"),data:JSON.stringify(c),contentType:"application/json",processData:!1,success:function(a){b(!1,a)},error:function(a){b(!0,a)}})}})}(),function(){"use strict";window.ArangoDatabase=Backbone.Collection.extend({model:window.DatabaseModel,sortOptions:{desc:!1},url:arangoHelper.databaseUrl("/_api/database"),comparator:function(a,b){var c=a.get("name").toLowerCase(),d=b.get("name").toLowerCase();return this.sortOptions.desc===!0?d>c?1:c>d?-1:0:c>d?1:d>c?-1:0},parse:function(a){return a?_.map(a.result,function(a){return{name:a}}):void 0},initialize:function(){var a=this;this.fetch().done(function(){a.sort()})},setSortingDesc:function(a){this.sortOptions.desc=a},getDatabases:function(){var a=this;return this.fetch().done(function(){a.sort()}),this.models},getDatabasesForUser:function(a){$.ajax({type:"GET",cache:!1,url:this.url+"/user",contentType:"application/json",processData:!1,success:function(b){a(!1,b.result.sort())},error:function(){a(!0,[])}})},createDatabaseURL:function(a,b,c){var d=window.location,e=window.location.hash;b=b?"SSL"===b||"https:"===b?"https:":"http:":d.protocol,c=c||d.port;var f=b+"//"+window.location.hostname+":"+c+"/_db/"+encodeURIComponent(a)+"/_admin/aardvark/standalone.html";if(e){var g=e.split("/")[0];0===g.indexOf("#collection")&&(g="#collections"),0===g.indexOf("#service")&&(g="#services"),f+=g}return f},getCurrentDatabase:function(a){$.ajax({type:"GET",cache:!1,url:this.url+"/current",contentType:"application/json",processData:!1,success:function(b){200===b.code?a(!1,b.result.name):a(!1,b)},error:function(b){a(!0,b)}})},hasSystemAccess:function(a){var b=function(b,c){b?arangoHelper.arangoError("DB","Could not fetch databases"):a(!1,_.includes(c,"_system"))};this.getDatabasesForUser(b)}})}(),window.ArangoDocument=Backbone.Collection.extend({url:"/_api/document/",model:arangoDocumentModel,collectionInfo:{},deleteEdge:function(a,b,c){this.deleteDocument(a,b,c)},deleteDocument:function(a,b,c){$.ajax({cache:!1,type:"DELETE",contentType:"application/json",url:arangoHelper.databaseUrl("/_api/document/"+encodeURIComponent(a)+"/"+encodeURIComponent(b)),success:function(){c(!1)},error:function(){c(!0)}})},addDocument:function(a,b){var c=this;c.createTypeDocument(a,b)},createTypeEdge:function(a,b,c,d,e){var f;f=d?JSON.stringify({_key:d,_from:b,_to:c}):JSON.stringify({_from:b,_to:c}),$.ajax({cache:!1,type:"POST",url:arangoHelper.databaseUrl("/_api/document?collection="+encodeURIComponent(a)),data:f,contentType:"application/json",processData:!1,success:function(a){e(!1,a)},error:function(a){e(!0,a)}})},createTypeDocument:function(a,b,c,d){var e;e=b?JSON.stringify({_key:b}):JSON.stringify({});var f=arangoHelper.databaseUrl("/_api/document?collection="+encodeURIComponent(a));d&&(f+="?returnNew=true"),$.ajax({cache:!1,type:"POST",url:f,data:e,contentType:"application/json",processData:!1,success:function(a){d?c(!1,a):c(!1,a._id)},error:function(a){c(!0,a._id,a.responseJSON)}})},getCollectionInfo:function(a,b,c){var d=this;$.ajax({cache:!1,type:"GET",url:arangoHelper.databaseUrl("/_api/collection/"+a+"?"+arangoHelper.getRandomToken()),contentType:"application/json",processData:!1,success:function(a){d.collectionInfo=a,b(!1,a,c)},error:function(a){b(!0,a,c)}})},getEdge:function(a,b,c){this.getDocument(a,b,c)},getDocument:function(a,b,c){var d=this;this.clearDocument(),$.ajax({cache:!1,type:"GET",url:arangoHelper.databaseUrl("/_api/document/"+encodeURIComponent(a)+"/"+encodeURIComponent(b)),contentType:"application/json",processData:!1,success:function(a){d.add(a),c(!1,a,"document")},error:function(a){d.add(!0,a)}})},saveEdge:function(a,b,c,d,e,f){var g;try{g=JSON.parse(e),g._to=d,g._from=c}catch(h){arangoHelper.arangoError("Edge","Could not parsed document.")}$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/document/"+encodeURIComponent(a)+"/"+encodeURIComponent(b))+"#replaceEdge",data:JSON.stringify(g),contentType:"application/json",processData:!1,success:function(a){f(!1,a)},error:function(a){f(!0,a)}})},saveDocument:function(a,b,c,d){$.ajax({cache:!1,type:"PUT",url:arangoHelper.databaseUrl("/_api/document/"+encodeURIComponent(a)+"/"+encodeURIComponent(b)),data:c,contentType:"application/json",processData:!1,success:function(a){d(!1,a)},error:function(a){d(!0,a)}})},updateLocalDocument:function(a){this.clearDocument(),this.add(a)},clearDocument:function(){this.reset()}}),function(){"use strict";window.ArangoDocuments=window.PaginatedCollection.extend({collectionID:1,filters:[],checkCursorTimer:void 0,MAX_SORT:12e3,lastQuery:{},sortAttribute:"",url:arangoHelper.databaseUrl("/_api/documents"),model:window.arangoDocumentModel,loadTotal:function(a){var b=this;$.ajax({cache:!1,type:"GET",url:arangoHelper.databaseUrl("/_api/collection/"+this.collectionID+"/count"),contentType:"application/json",processData:!1,success:function(c){b.setTotal(c.count),a(!1)},error:function(){a(!0)}})},setCollection:function(a){var b=function(a){a&&arangoHelper.arangoError("Documents","Could not fetch documents count")};this.resetFilter(),this.collectionID=a,this.setPage(1),this.loadTotal(b)},setSort:function(a){this.sortAttribute=a},getSort:function(){return this.sortAttribute},addFilter:function(a,b,c){this.filters.push({attr:a,op:b,val:c})},setFiltersForQuery:function(a){if(0===this.filters.length)return"";var b=" FILTER",c="",d=_.map(this.filters,function(b,d){return"LIKE"===b.op?(c=" "+b.op+"(x.`"+b.attr+"`, @param",c+=d,c+=")"):(c="IN"===b.op||"NOT IN"===b.op?" ":" x.`",c+=b.attr,c+="IN"===b.op||"NOT IN"===b.op?" ":"` ",c+=b.op,c+="IN"===b.op||"NOT IN"===b.op?" x.@param":" @param",c+=d),a["param"+d]=b.val,c});return b+d.join(" &&")},setPagesize:function(a){this.setPageSize(a)},resetFilter:function(){this.filters=[]},moveDocument:function(a,b,c,d){var e,f,g,h,i={"@collection":b,filterid:a};e="FOR x IN @@collection",e+=" FILTER x._key == @filterid",e+=" INSERT x IN ",e+=c,f="FOR x in @@collection",f+=" FILTER x._key == @filterid",f+=" REMOVE x IN @@collection",g={query:e,bindVars:i},h={query:f,bindVars:i},window.progressView.show(),$.ajax({cache:!1,type:"POST",url:arangoHelper.databaseUrl("/_api/cursor"),data:JSON.stringify(g),contentType:"application/json",success:function(){$.ajax({cache:!1,type:"POST",url:arangoHelper.databaseUrl("/_api/cursor"),data:JSON.stringify(h),contentType:"application/json",success:function(){d&&d(),window.progressView.hide()},error:function(){window.progressView.hide(),arangoHelper.arangoError("Document error","Documents inserted, but could not be removed.")}})},error:function(){window.progressView.hide(),arangoHelper.arangoError("Document error","Could not move selected documents.")}})},getDocuments:function(a){var b,c,d,e,f=this;c={"@collection":this.collectionID,offset:this.getOffset(),count:this.getPageSize()},b='FOR x IN @@collection LET att = APPEND(SLICE(ATTRIBUTES(x), 0, 25), "_key", true)',b+=this.setFiltersForQuery(c),this.getTotal()0&&(a+=" SORT x."+this.getSort()),a+=" RETURN x",b={query:a,bindVars:c}},uploadDocuments:function(a,b){$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_api/import?type=auto&collection="+encodeURIComponent(this.collectionID)+"&createCollection=false"),data:a,processData:!1,contentType:"json",dataType:"json",complete:function(a){if(4===a.readyState&&201===a.status)b(!1);else try{var c=JSON.parse(a.responseText);if(c.errors>0){var d="At least one error occurred during upload";b(!1,d)}}catch(e){console.log(e)}}})}})}(),function(){"use strict";window.ArangoLogs=window.PaginatedCollection.extend({upto:!1,loglevel:0,totalPages:0,parse:function(a){var b=[];return _.each(a.lid,function(c,d){b.push({level:a.level[d],lid:c,text:a.text[d],timestamp:a.timestamp[d],totalAmount:a.totalAmount})}),this.totalAmount=a.totalAmount,this.totalPages=Math.ceil(this.totalAmount/this.pagesize),b},initialize:function(a){a.upto===!0&&(this.upto=!0),this.loglevel=a.loglevel},model:window.newArangoLog,url:function(){var a,b,c,d=this.totalAmount-(this.page+1)*this.pagesize;return 0>d&&this.page===this.totalPages-1?(d=0,c=this.totalAmount%this.pagesize):c=this.pagesize,0===this.totalAmount&&(c=1),a=this.upto?"upto":"level",b="/_admin/log?"+a+"="+this.loglevel+"&size="+c+"&offset="+d,arangoHelper.databaseUrl(b)}})}(),function(){"use strict";window.ArangoQueries=Backbone.Collection.extend({initialize:function(a,b){var c=this;$.ajax("whoAmI?_="+Date.now(),{async:!0}).done(function(a){this.activeUser===!1||null===this.activeUser?c.activeUser="root":c.activeUser=a.user})},url:arangoHelper.databaseUrl("/_api/user/"),model:ArangoQuery,activeUser:null,parse:function(a){var b,c=this;return this.activeUser!==!1&&null!==this.activeUser||(this.activeUser="root"),_.each(a.result,function(a){if(a.user===c.activeUser)try{a.extra.queries&&(b=a.extra.queries)}catch(d){}}),b},saveCollectionQueries:function(a){if(this.activeUser===!1||null===this.activeUser)return!1;this.activeUser!==!1&&null!==this.activeUser||(this.activeUser="root");var b=[];this.each(function(a){b.push({value:a.attributes.value,parameter:a.attributes.parameter,name:a.attributes.name})}),$.ajax({cache:!1,type:"PATCH",url:arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(this.activeUser)),data:JSON.stringify({extra:{queries:b}}),contentType:"application/json",processData:!1,success:function(b){a(!1,b)},error:function(){a(!0)}})},saveImportQueries:function(a,b){return 0===this.activeUser?!1:(window.progressView.show("Fetching documents..."),void $.ajax({cache:!1,type:"POST",url:"query/upload/"+encodeURIComponent(this.activeUser),data:a,contentType:"application/json",processData:!1,success:function(){window.progressView.hide(),arangoHelper.arangoNotification("Queries successfully imported."),b()},error:function(){window.progressView.hide(),arangoHelper.arangoError("Query error","queries could not be imported")}}))}})}(),window.ArangoReplication=Backbone.Collection.extend({model:window.Replication,url:"../api/user",getLogState:function(a){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/replication/logger-state"),contentType:"application/json",processData:!1,success:function(b){a(!1,b)},error:function(b){a(!0,b)}})},getApplyState:function(a){$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/replication/applier-state"),contentType:"application/json",processData:!1,success:function(b){a(!1,b)},error:function(b){a(!0,b)}})}}),window.StatisticsCollection=Backbone.Collection.extend({model:window.Statistics,url:"/_admin/statistics"}),window.StatisticsDescriptionCollection=Backbone.Collection.extend({model:window.StatisticsDescription,url:"/_admin/statistics-description",parse:function(a){return a}}),window.ArangoUsers=Backbone.Collection.extend({model:window.Users,activeUser:null,activeUserSettings:{query:{},shell:{},testing:!0},sortOptions:{desc:!1},fetch:function(a){return window.App.currentUser&&"_system"!==window.App.currentDB.get("name")&&(this.url=frontendConfig.basePath+"/_api/user/"+encodeURIComponent(window.App.currentUser)),Backbone.Collection.prototype.fetch.call(this,a)},url:frontendConfig.basePath+"/_api/user",comparator:function(a,b){var c=a.get("user").toLowerCase(),d=b.get("user").toLowerCase();return this.sortOptions.desc===!0?d>c?1:c>d?-1:0:c>d?1:d>c?-1:0},login:function(a,b,c){var d=this;$.ajax({url:arangoHelper.databaseUrl("/_open/auth"),method:"POST",data:JSON.stringify({username:a,password:b}),dataType:"json"}).success(function(a){arangoHelper.setCurrentJwt(a.jwt);var b=a.jwt.split(".");if(!b[1])throw new Error("Invalid JWT");if(!window.atob)throw new Error("base64 support missing in browser");var e=JSON.parse(atob(b[1]));d.activeUser=e.preferred_username,c(!1,d.activeUser)}).error(function(){arangoHelper.setCurrentJwt(null),d.activeUser=null,c(!0,null)})},setSortingDesc:function(a){this.sortOptions.desc=a},logout:function(){arangoHelper.setCurrentJwt(null),this.activeUser=null,this.reset(),window.App.navigate(""),window.location.reload()},setUserSettings:function(a,b){this.activeUserSettings.identifier=b},loadUserSettings:function(a){var b=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(b.activeUser)),contentType:"application/json",processData:!1,success:function(c){b.activeUserSettings=c.extra,a(!1,c)},error:function(b){a(!0,b)}})},saveUserSettings:function(a){var b=this;$.ajax({cache:!1,type:"PUT",url:frontendConfig.basePath+"/_api/user/"+encodeURIComponent(b.activeUser),data:JSON.stringify({extra:b.activeUserSettings}),contentType:"application/json",processData:!1,success:function(b){a(!1,b)},error:function(b){a(!0,b)}})},parse:function(a){var b=[];return a.result?_.each(a.result,function(a){b.push(a)}):b.push({user:a.user,active:a.active,extra:a.extra,changePassword:a.changePassword}),b},whoAmI:function(a){return this.activeUser?void a(!1,this.activeUser):void $.ajax("whoAmI?_="+Date.now()).success(function(b){a(!1,b.user)}).error(function(){a(!0,null)})}}),function(){"use strict";window.ClusterCoordinators=window.AutomaticRetryCollection.extend({model:window.ClusterCoordinator,url:arangoHelper.databaseUrl("/_admin/aardvark/cluster/Coordinators"),updateUrl:function(){this.url=window.App.getNewRoute("Coordinators")},initialize:function(){},statusClass:function(a){switch(a){case"ok":return"success";case"warning":return"warning";case"critical":return"danger";case"missing":return"inactive";default:return"danger"}},getStatuses:function(a,b){if(this.checkRetries()){var c=this;this.fetch({beforeSend:window.App.addAuth.bind(window.App),error:c.failureTry.bind(c,c.getStatuses.bind(c,a,b))}).done(function(){c.successFullTry(),c.forEach(function(b){a(c.statusClass(b.get("status")),b.get("address"))}),b()})}},byAddress:function(a,b){if(this.checkRetries()){var c=this;this.fetch({beforeSend:window.App.addAuth.bind(window.App),error:c.failureTry.bind(c,c.byAddress.bind(c,a,b))}).done(function(){c.successFullTry(),a=a||{},c.forEach(function(b){var c=b.get("address");c=c.split(":")[0],a[c]=a[c]||{},a[c].coords=a[c].coords||[],a[c].coords.push(b)}),b(a)})}},checkConnection:function(a){var b=this;this.checkRetries()&&this.fetch({beforeSend:window.App.addAuth.bind(window.App),error:b.failureTry.bind(b,b.checkConnection.bind(b,a))}).done(function(){b.successFullTry(),a()})}})}(),function(){"use strict";window.ClusterServers=window.AutomaticRetryCollection.extend({model:window.ClusterServer,host:"",url:arangoHelper.databaseUrl("/_admin/aardvark/cluster/DBServers"),updateUrl:function(){this.url=window.App.getNewRoute(this.host)+this.url},initialize:function(a,b){this.host=b.host},statusClass:function(a){switch(a){case"ok":return"success";case"warning":return"warning";case"critical":return"danger";case"missing":return"inactive";default:return"danger"}},getStatuses:function(a){if(this.checkRetries()){var b=this,c=function(){b.successFullTry(),b._retryCount=0,b.forEach(function(c){a(b.statusClass(c.get("status")),c.get("address"))})};this.fetch({beforeSend:window.App.addAuth.bind(window.App),error:b.failureTry.bind(b,b.getStatuses.bind(b,a))}).done(c)}},byAddress:function(a,b){if(this.checkRetries()){var c=this;this.fetch({beforeSend:window.App.addAuth.bind(window.App),error:c.failureTry.bind(c,c.byAddress.bind(c,a,b))}).done(function(){c.successFullTry(),a=a||{},c.forEach(function(b){var c=b.get("address");c=c.split(":")[0],a[c]=a[c]||{},a[c].dbs=a[c].dbs||[],a[c].dbs.push(b)}),b(a)}).error(function(a){console.log("error"),console.log(a)})}},getList:function(){throw new Error("Do not use")},getOverview:function(){throw new Error("Do not use DbServer.getOverview")}})}(),function(){"use strict";window.CoordinatorCollection=Backbone.Collection.extend({model:window.Coordinator,url:arangoHelper.databaseUrl("/_admin/aardvark/cluster/Coordinators")
-})}(),function(){"use strict";window.FoxxCollection=Backbone.Collection.extend({model:window.Foxx,sortOptions:{desc:!1},url:arangoHelper.databaseUrl("/_admin/aardvark/foxxes"),comparator:function(a,b){var c,d;return this.sortOptions.desc===!0?(c=a.get("mount"),d=b.get("mount"),d>c?1:c>d?-1:0):(c=a.get("mount"),d=b.get("mount"),c>d?1:d>c?-1:0)},setSortingDesc:function(a){this.sortOptions.desc=a},installFromGithub:function(a,b,c,d){var e=arangoHelper.databaseUrl("/_admin/aardvark/foxxes/git?mount="+encodeURIComponent(b));void 0!==d&&(e+=d?"&replace=true":"&upgrade=true"),$.ajax({cache:!1,type:"PUT",url:e,data:JSON.stringify(a),contentType:"application/json",processData:!1,success:function(a){c(a)},error:function(a){c(a)}})},installFromStore:function(a,b,c,d){var e=arangoHelper.databaseUrl("/_admin/aardvark/foxxes/store?mount="+encodeURIComponent(b));void 0!==d&&(e+=d?"&replace=true":"&upgrade=true"),$.ajax({cache:!1,type:"PUT",url:e,data:JSON.stringify(a),contentType:"application/json",processData:!1,success:function(a){c(a)},error:function(a){c(a)}})},installFromZip:function(a,b,c,d){var e=arangoHelper.databaseUrl("/_admin/aardvark/foxxes/zip?mount="+encodeURIComponent(b));void 0!==d&&(e+=d?"&replace=true":"&upgrade=true"),$.ajax({cache:!1,type:"PUT",url:e,data:JSON.stringify({zipFile:a}),contentType:"application/json",processData:!1,success:function(a){c(a)},error:function(a){c(a)}})},generate:function(a,b,c,d){var e=arangoHelper.databaseUrl("/_admin/aardvark/foxxes/generate?mount="+encodeURIComponent(b));void 0!==d&&(e+=d?"&replace=true":"&upgrade=true"),$.ajax({cache:!1,type:"PUT",url:e,data:JSON.stringify(a),contentType:"application/json",processData:!1,success:function(a){c(a)},error:function(a){c(a)}})}})}(),function(){"use strict";window.GraphCollection=Backbone.Collection.extend({model:window.Graph,sortOptions:{desc:!1},url:arangoHelper.databaseUrl("/_api/gharial"),dropAndDeleteGraph:function(a,b){$.ajax({type:"DELETE",url:arangoHelper.databaseUrl("/_api/gharial/")+encodeURIComponent(a)+"?dropCollections=true",contentType:"application/json",processData:!0,success:function(){b(!0)},error:function(){b(!1)}})},comparator:function(a,b){var c=a.get("_key")||"",d=b.get("_key")||"";return c=c.toLowerCase(),d=d.toLowerCase(),this.sortOptions.desc===!0?d>c?1:c>d?-1:0:c>d?1:d>c?-1:0},setSortingDesc:function(a){this.sortOptions.desc=a},parse:function(a){return a.error?void 0:a.graphs}})}(),function(){"use strict";window.NotificationCollection=Backbone.Collection.extend({model:window.Notification,url:""})}(),function(){"use strict";window.QueryManagementActive=Backbone.Collection.extend({model:window.queryManagementModel,url:function(){var a=frontendConfig.basePath+"/_api/query/current";return"_system"!==window.frontendConfig.db&&(a=arangoHelper.databaseUrl("/_api/query/current")),a},killRunningQuery:function(a,b){var c=frontendConfig.basePath+"/_api/query/"+encodeURIComponent(a);"_system"!==window.frontendConfig.db&&(c=arangoHelper.databaseUrl("/_api/query/"+encodeURIComponent(a))),$.ajax({url:c,type:"DELETE",success:function(a){b()}})}})}(),function(){"use strict";window.QueryManagementSlow=Backbone.Collection.extend({model:window.queryManagementModel,url:function(){var a=frontendConfig.basePath+"/_api/query/slow";return"_system"!==window.frontendConfig.db&&(a=arangoHelper.databaseUrl("/_api/query/slow")),a},deleteSlowQueryHistory:function(a){var b=frontendConfig.basePath+"/_api/query/slow";"_system"!==window.frontendConfig.db&&(b=arangoHelper.databaseUrl("/_api/query/slow")),$.ajax({url:b,type:"DELETE",success:function(b){a()}})}})}(),function(){"use strict";window.WorkMonitorCollection=Backbone.Collection.extend({model:window.workMonitorModel,url:"/_admin/work-monitor",parse:function(a){return a.work}})}(),function(){"use strict";window.PaginationView=Backbone.View.extend({collection:null,paginationDiv:"",idPrefix:"",rerender:function(){},jumpTo:function(a){this.collection.setPage(a),this.rerender()},firstPage:function(){this.jumpTo(1)},lastPage:function(){this.jumpTo(this.collection.getLastPageNumber())},firstDocuments:function(){this.jumpTo(1)},lastDocuments:function(){this.jumpTo(this.collection.getLastPageNumber())},prevDocuments:function(){this.jumpTo(this.collection.getPage()-1)},nextDocuments:function(){this.jumpTo(this.collection.getPage()+1)},renderPagination:function(){$(this.paginationDiv).html("");var a=this,b=this.collection.getPage(),c=this.collection.getLastPageNumber(),d=$(this.paginationDiv),e={page:b,lastPage:c,click:function(b){var c=window.location.hash.split("/");"documents"===c[2]?(e.page=b,window.location.hash=c[0]+"/"+c[1]+"/"+c[2]+"/"+b):(a.jumpTo(b),e.page=b)}};d.html(""),d.pagination(e),$(this.paginationDiv).prepend('
"),$("#subNavigationBar .breadcrumb").html(a)},openApp:function(){var a=function(a,b){a?arangoHelper.arangoError("DB","Could not get current database"):window.open(this.appUrl(b),this.model.get("title")).focus()}.bind(this);arangoHelper.currentDatabase(a)},deleteApp:function(){var a=[window.modalView.createDeleteButton("Delete",function(){var a={teardown:$("#app_delete_run_teardown").is(":checked")};this.model.destroy(a,function(a,b){a||b.error!==!1||(window.modalView.hide(),window.App.navigate("services",{trigger:!0}))})}.bind(this))],b=[window.modalView.createCheckboxEntry("app_delete_run_teardown","Run teardown?",!0,"Should this app's teardown script be executed before removing the app?",!0)];window.modalView.show("modalTable.ejs",'Delete Foxx App mounted at "'+this.model.get("mount")+'"',a,b,void 0,"
Are you sure? There is no way back...
",!0)},appUrl:function(a){return arangoHelper.databaseUrl(this.model.get("mount"),a)},applyConfig:function(){var a={};_.each(this.model.get("config"),function(b,c){var d=$("#app_config_"+c),e=d.val();if("boolean"===b.type||"bool"===b.type)return void(a[c]=d.is(":checked"));if(""===e&&b.hasOwnProperty("default"))return a[c]=b["default"],void("json"===b.type&&(a[c]=JSON.stringify(b["default"])));if("number"===b.type)a[c]=parseFloat(e);else if("integer"===b.type||"int"===b.type)a[c]=parseInt(e,10);else{if("json"!==b.type)return void(a[c]=window.arangoHelper.escapeHtml(e));a[c]=e&&JSON.stringify(JSON.parse(e))}}),this.model.setConfiguration(a,function(){this.updateConfig(),arangoHelper.arangoNotification(this.model.get("name"),"Settings applied.")}.bind(this))},showConfigDialog:function(){if(_.isEmpty(this.model.get("config")))return void $("#settings .buttons").html($("#hidden_buttons").html());var a=_.map(this.model.get("config"),function(a,b){var c=void 0===a["default"]?"":String(a["default"]),d=void 0===a.current?"":String(a.current),e="createTextEntry",f=!1,g=[];return"boolean"===a.type||"bool"===a.type?(e="createCheckboxEntry",a["default"]=a["default"]||!1,c=a["default"]||!1,d=a.current||!1):"json"===a.type?(e="createBlobEntry",c=void 0===a["default"]?"":JSON.stringify(a["default"]),d=void 0===a.current?"":a.current,g.push({rule:function(a){return a&&JSON.parse(a)},msg:"Must be well-formed JSON or empty."})):"integer"===a.type||"int"===a.type?g.push({rule:Joi.number().integer().optional().allow(""),msg:"Has to be an integer."}):"number"===a.type?g.push({rule:Joi.number().optional().allow(""),msg:"Has to be a number."}):("password"===a.type&&(e="createPasswordEntry"),g.push({rule:Joi.string().optional().allow(""),msg:"Has to be a string."})),void 0===a["default"]&&a.required!==!1&&(f=!0,g.unshift({rule:Joi.any().required(),msg:"This field is required."})),window.modalView[e]("app_config_"+b,b,d,a.description,c,f,g)}),b=[window.modalView.createSuccessButton("Apply",this.applyConfig.bind(this))];window.modalView.show("modalTable.ejs","Configuration",b,a,null,null,null,null,null,"settings"),$(".modal-footer").prepend($("#hidden_buttons").html())},applyDeps:function(){var a={};_.each(this.model.get("deps"),function(b,c){var d=$("#app_deps_"+c);a[c]=window.arangoHelper.escapeHtml(d.val())}),this.model.setDependencies(a,function(){window.modalView.hide(),this.updateDeps()}.bind(this))},showDepsDialog:function(){if(!_.isEmpty(this.model.get("deps"))){var a=_.map(this.model.get("deps"),function(a,b){var c=void 0===a.current?"":String(a.current),d="",e=a.definition.name;"*"!==a.definition.version&&(e+="@"+a.definition.version);var f=[{rule:Joi.string().optional().allow(""),msg:"Has to be a string."}];return a.definition.required&&f.push({rule:Joi.string().required(),msg:"This value is required."}),window.modalView.createTextEntry("app_deps_"+b,a.title,c,e,d,a.definition.required,f)}),b=[window.modalView.createSuccessButton("Apply",this.applyDeps.bind(this))];window.modalView.show("modalTable.ejs","Dependencies",b,a)}},showDropdown:function(){_.isEmpty(this.model.get("scripts"))||$("#scripts_dropdown").show(200)},hideDropdown:function(){$("#scripts_dropdown").hide()}})}(),function(){"use strict";window.ApplicationsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("applicationsView.ejs"),events:{"click #addApp":"createInstallModal","click #foxxToggle":"slideToggle","click #checkDevel":"toggleDevel","click #checkProduction":"toggleProduction","click #checkSystem":"toggleSystem"},fixCheckboxes:function(){this._showDevel?$("#checkDevel").attr("checked","checked"):$("#checkDevel").removeAttr("checked"),this._showSystem?$("#checkSystem").attr("checked","checked"):$("#checkSystem").removeAttr("checked"),this._showProd?$("#checkProduction").attr("checked","checked"):$("#checkProduction").removeAttr("checked"),$("#checkDevel").next().removeClass("fa fa-check-square-o fa-square-o").addClass("fa"),$("#checkSystem").next().removeClass("fa fa-check-square-o fa-square-o").addClass("fa"),$("#checkProduction").next().removeClass("fa fa-check-square-o fa-square-o").addClass("fa"),arangoHelper.setCheckboxStatus("#foxxDropdown")},toggleDevel:function(){var a=this;this._showDevel=!this._showDevel,_.each(this._installedSubViews,function(b){b.toggle("devel",a._showDevel)}),this.fixCheckboxes()},toggleProduction:function(){var a=this;this._showProd=!this._showProd,_.each(this._installedSubViews,function(b){b.toggle("production",a._showProd)}),this.fixCheckboxes()},toggleSystem:function(){this._showSystem=!this._showSystem;var a=this;_.each(this._installedSubViews,function(b){b.toggle("system",a._showSystem)}),this.fixCheckboxes()},reload:function(){var a=this;_.each(this._installedSubViews,function(a){a.undelegateEvents()}),this.collection.fetch({success:function(){a.createSubViews(),a.render()}})},createSubViews:function(){var a=this;this._installedSubViews={},a.collection.each(function(b){var c=new window.FoxxActiveView({model:b,appsView:a});a._installedSubViews[b.get("mount")]=c})},initialize:function(){this._installedSubViews={},this._showDevel=!0,this._showProd=!0,this._showSystem=!1},slideToggle:function(){$("#foxxToggle").toggleClass("activated"),$("#foxxDropdownOut").slideToggle(200)},createInstallModal:function(a){a.preventDefault(),window.foxxInstallView.install(this.reload.bind(this))},render:function(){this.collection.sort(),$(this.el).html(this.template.render({})),_.each(this._installedSubViews,function(a){$("#installedList").append(a.render())}),this.delegateEvents(),$("#checkDevel").attr("checked",this._showDevel),$("#checkProduction").attr("checked",this._showProd),$("#checkSystem").attr("checked",this._showSystem),arangoHelper.setCheckboxStatus("#foxxDropdown");var a=this;return _.each(this._installedSubViews,function(b){b.toggle("devel",a._showDevel),b.toggle("system",a._showSystem)}),arangoHelper.fixTooltips("icon_arangodb","left"),this}})}(),function(){"use strict";window.ClusterView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("clusterView.ejs"),events:{},statsEnabled:!1,historyInit:!1,initDone:!1,interval:5e3,maxValues:100,knownServers:[],chartData:{},charts:{},nvcharts:[],startHistory:{},startHistoryAccumulated:{},initialize:function(a){var b=this;window.App.isCluster&&(this.dbServers=a.dbServers,this.coordinators=a.coordinators,this.updateServerTime(),window.setInterval(function(){if("#cluster"===window.location.hash||""===window.location.hash||"#"===window.location.hash){var a=function(a){b.rerenderValues(a),b.rerenderGraphs(a)};b.getCoordStatHistory(a)}},this.interval))},render:function(){this.$el.html(this.template.render({})),this.initDone||(void 0!==this.coordinators.first()?this.getServerStatistics():this.waitForCoordinators(),this.initDone=!0),this.initGraphs()},waitForCoordinators:function(){var a=this;window.setTimeout(function(){a.coordinators?a.getServerStatistics():a.waitForCoordinators()},500)},updateServerTime:function(){this.serverTime=(new Date).getTime()},getServerStatistics:function(){var a=this;this.data=void 0;var b=this.coordinators.first();this.statCollectCoord=new window.ClusterStatisticsCollection([],{host:b.get("address")}),this.statCollectDBS=new window.ClusterStatisticsCollection([],{host:b.get("address")});var c=[];_.each(this.dbServers,function(a){a.each(function(a){c.push(a)})}),_.each(c,function(c){if("ok"===c.get("status")){-1===a.knownServers.indexOf(c.id)&&a.knownServers.push(c.id);var d=new window.Statistics({name:c.id});d.url=b.get("protocol")+"://"+b.get("address")+"/_admin/clusterStatistics?DBserver="+c.get("name"),a.statCollectDBS.add(d)}}),this.coordinators.forEach(function(b){if("ok"===b.get("status")){-1===a.knownServers.indexOf(b.id)&&a.knownServers.push(b.id);var c=new window.Statistics({name:b.id});c.url=b.get("protocol")+"://"+b.get("address")+"/_admin/statistics",a.statCollectCoord.add(c)}});var d=function(b){a.rerenderValues(b),a.rerenderGraphs(b)};a.getCoordStatHistory(d),a.renderNodes()},rerenderValues:function(a){var b=this;b.renderNodes(),this.renderValue("#clusterConnections",Math.round(a.clientConnectionsCurrent)),this.renderValue("#clusterConnectionsAvg",Math.round(a.clientConnections15M));var c=a.physicalMemory,d=a.residentSizeCurrent;this.renderValue("#clusterRam",[d,c])},renderValue:function(a,b,c,d){if("number"==typeof b)$(a).html(b);else if($.isArray(b)){var e=b[0],f=b[1],g=1/(f/e)*100;g>90?c=!0:g>70&&90>g&&(d=!0),$(a).html(g.toFixed(1)+" %")}else"string"==typeof b&&$(a).html(b);c?($(a).addClass("negative"),$(a).removeClass("warning"),$(a).removeClass("positive")):d?($(a).addClass("warning"),$(a).removeClass("positive"),$(a).removeClass("negative")):($(a).addClass("positive"),$(a).removeClass("negative"),$(a).removeClass("warning"))},renderNodes:function(){var a=this,b=function(a){var b=0,c=0,d=0,e=0;_.each(a,function(a){"Coordinator"===a.Role?(b++,"GOOD"!==a.Status&&c++):"DBServer"===a.Role&&(d++,"GOOD"!==a.Status&&e++)}),c>0?this.renderValue("#clusterCoordinators",b-c+"/"+b,!0):this.renderValue("#clusterCoordinators",b),e>0?this.renderValue("#clusterDBServers",d-e+"/"+d,!0):this.renderValue("#clusterDBServers",d)}.bind(this);$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,async:!0,success:function(a){b(a.Health)},error:function(){a.renderValue("#clusterCoordinators","N/A",!0),a.renderValue("#clusterDBServers","N/A",!0)}})},initValues:function(){var a=["#clusterNodes","#clusterRam","#clusterConnections","#clusterConnectionsAvg"];_.each(a,function(a){$(a).html('')})},graphData:{data:{sent:[],received:[]},http:[],average:[]},checkArraySizes:function(){var a=this;_.each(a.chartsOptions,function(b,c){_.each(b.options,function(b,d){b.values.length>a.maxValues-1&&a.chartsOptions[c].options[d].values.shift()})})},formatDataForGraph:function(a){var b=this;b.historyInit?(b.checkArraySizes(),b.chartsOptions[0].options[0].values.push({x:a.times[a.times.length-1],y:a.bytesSentPerSecond[a.bytesSentPerSecond.length-1]}),b.chartsOptions[0].options[1].values.push({x:a.times[a.times.length-1],y:a.bytesReceivedPerSecond[a.bytesReceivedPerSecond.length-1]}),b.chartsOptions[1].options[0].values.push({x:a.times[a.times.length-1],y:b.calcTotalHttp(a.http,a.bytesSentPerSecond.length-1)}),b.chartsOptions[2].options[0].values.push({x:a.times[a.times.length-1],y:a.avgRequestTime[a.bytesSentPerSecond.length-1]/b.coordinators.length})):(_.each(a.times,function(c,d){b.chartsOptions[0].options[0].values.push({x:c,y:a.bytesSentPerSecond[d]}),b.chartsOptions[0].options[1].values.push({x:c,y:a.bytesReceivedPerSecond[d]}),b.chartsOptions[1].options[0].values.push({x:c,y:b.calcTotalHttp(a.http,d)}),b.chartsOptions[2].options[0].values.push({x:c,y:a.avgRequestTime[d]/b.coordinators.length})}),b.historyInit=!0)},chartsOptions:[{id:"#clusterData",type:"bytes",count:2,options:[{area:!0,values:[],key:"Bytes out",color:"rgb(23,190,207)",strokeWidth:2,fillOpacity:.1},{area:!0,values:[],key:"Bytes in",color:"rgb(188, 189, 34)",strokeWidth:2,fillOpacity:.1}]},{id:"#clusterHttp",type:"bytes",options:[{area:!0,values:[],key:"Bytes",color:"rgb(0, 166, 90)",fillOpacity:.1}]},{id:"#clusterAverage",data:[],type:"seconds",options:[{area:!0,values:[],key:"Seconds",color:"rgb(243, 156, 18)",fillOpacity:.1}]}],initGraphs:function(){var a=this,b="No data...";_.each(a.chartsOptions,function(c){nv.addGraph(function(){a.charts[c.id]=nv.models.stackedAreaChart().options({useInteractiveGuideline:!0,showControls:!1,noData:b,duration:0}),a.charts[c.id].xAxis.axisLabel("").tickFormat(function(a){var b=new Date(1e3*a);return(b.getHours()<10?"0":"")+b.getHours()+":"+(b.getMinutes()<10?"0":"")+b.getMinutes()+":"+(b.getSeconds()<10?"0":"")+b.getSeconds()}).staggerLabels(!1),a.charts[c.id].yAxis.axisLabel("").tickFormat(function(a){var b;return"bytes"===c.type?null===a?"N/A":(b=parseFloat(d3.format(".2f")(a)),prettyBytes(b)):"seconds"===c.type?null===a?"N/A":b=parseFloat(d3.format(".3f")(a)):void 0});var d,e=a.returnGraphOptions(c.id);return e.length>0?_.each(e,function(a,b){c.options[b].values=a}):c.options[0].values=[],d=c.options,a.chartData[c.id]=d3.select(c.id).append("svg").datum(d).transition().duration(300).call(a.charts[c.id]).each("start",function(){window.setTimeout(function(){d3.selectAll(c.id+" *").each(function(){this.__transition__&&(this.__transition__.duration=0)})},0)}),nv.utils.windowResize(a.charts[c.id].update),a.nvcharts.push(a.charts[c.id]),a.charts[c.id]})})},returnGraphOptions:function(a){var b=[];return b="#clusterData"===a?[this.chartsOptions[0].options[0].values,this.chartsOptions[0].options[1].values]:"#clusterHttp"===a?[this.chartsOptions[1].options[0].values]:"#clusterAverage"===a?[this.chartsOptions[2].options[0].values]:[]},rerenderGraphs:function(a){if(this.statsEnabled){var b,c,d=this;this.formatDataForGraph(a),_.each(d.chartsOptions,function(a){c=d.returnGraphOptions(a.id),c.length>0?_.each(c,function(b,c){a.options[c].values=b}):a.options[0].values=[],b=a.options,b[0].values.length>0&&d.historyInit&&d.charts[a.id]&&d.charts[a.id].update()})}},calcTotalHttp:function(a,b){var c=0;return _.each(a,function(a){c+=a[b]}),c},getCoordStatHistory:function(a){$.ajax({url:"statistics/coordshort",json:!0}).success(function(b){this.statsEnabled=b.enabled,a(b.data)}.bind(this))}})}(),function(){"use strict";window.CollectionListItemView=Backbone.View.extend({tagName:"div",className:"tile pure-u-1-1 pure-u-sm-1-2 pure-u-md-1-3 pure-u-lg-1-4 pure-u-xl-1-6",template:templateEngine.createTemplate("collectionsItemView.ejs"),initialize:function(a){this.collectionsView=a.collectionsView},events:{"click .iconSet.icon_arangodb_settings2":"createEditPropertiesModal","click .pull-left":"noop","click .icon_arangodb_settings2":"editProperties","click .spanInfo":"showProperties",click:"selectCollection"},render:function(){return this.model.get("locked")?($(this.el).addClass("locked"),$(this.el).addClass(this.model.get("lockType"))):$(this.el).removeClass("locked"),"loading"!==this.model.get("status")&&"unloading"!==this.model.get("status")||$(this.el).addClass("locked"),$(this.el).html(this.template.render({model:this.model})),$(this.el).attr("id","collection_"+this.model.get("name")),this},editProperties:function(a){return this.model.get("locked")?0:(a.stopPropagation(),void this.createEditPropertiesModal())},showProperties:function(a){return this.model.get("locked")?0:(a.stopPropagation(),void this.createInfoModal())},selectCollection:function(a){return $(a.target).hasClass("disabled")?0:this.model.get("locked")?0:"loading"===this.model.get("status")?0:void("unloaded"===this.model.get("status")?this.loadCollection():window.App.navigate("collection/"+encodeURIComponent(this.model.get("name"))+"/documents/1",{trigger:!0}))},noop:function(a){a.stopPropagation()},unloadCollection:function(){var a=function(a){a?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be unloaded."):void 0===a?(this.model.set("status","unloading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","unloaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" unloaded.")}.bind(this);this.model.unloadCollection(a),window.modalView.hide()},loadCollection:function(){var a=function(a){a?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be loaded."):void 0===a?(this.model.set("status","loading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","loaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" loaded.")}.bind(this);this.model.loadCollection(a),window.modalView.hide()},truncateCollection:function(){this.model.truncateCollection(),window.modalView.hide()},deleteCollection:function(){this.model.destroy({error:function(){arangoHelper.arangoError("Could not delete collection.")},success:function(){window.modalView.hide()}}),this.collectionsView.render()},saveModifiedCollection:function(){var a=function(a,b){if(a)arangoHelper.arangoError("Error","Could not get coordinator info");else{var c;c=b?this.model.get("name"):$("#change-collection-name").val();var d=this.model.get("status");if("loaded"===d){var e;try{e=JSON.parse(1024*$("#change-collection-size").val()*1024)}catch(f){return arangoHelper.arangoError("Please enter a valid number"),0}var g;try{if(g=JSON.parse($("#change-index-buckets").val()),1>g||parseInt(g,10)!==Math.pow(2,Math.log2(g)))throw new Error("invalid indexBuckets value")}catch(f){return arangoHelper.arangoError("Please enter a valid number of index buckets"),0}var h=function(a){a?arangoHelper.arangoError("Collection error: "+a.responseText):(this.collectionsView.render(),window.modalView.hide())}.bind(this),i=function(a){if(a)arangoHelper.arangoError("Collection error: "+a.responseText);else{var b=$("#change-collection-sync").val();this.model.changeCollection(b,e,g,h)}}.bind(this);frontendConfig.isCluster===!1?this.model.renameCollection(c,i):i()}else if("unloaded"===d)if(this.model.get("name")!==c){var j=function(a,b){a?arangoHelper.arangoError("Collection error: "+b.responseText):(this.collectionsView.render(),window.modalView.hide())}.bind(this);frontendConfig.isCluster===!1?this.model.renameCollection(c,j):j()}else window.modalView.hide()}}.bind(this);window.isCoordinator(a)},createEditPropertiesModal:function(){var a=function(a,b){if(a)arangoHelper.arangoError("Error","Could not get coordinator info");else{var c=!1;"loaded"===this.model.get("status")&&(c=!0);var d=[],e=[];b||e.push(window.modalView.createTextEntry("change-collection-name","Name",this.model.get("name"),!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}]));var f=function(){e.push(window.modalView.createReadOnlyEntry("change-collection-id","ID",this.model.get("id"),"")),e.push(window.modalView.createReadOnlyEntry("change-collection-type","Type",this.model.get("type"),"")),e.push(window.modalView.createReadOnlyEntry("change-collection-status","Status",this.model.get("status"),"")),d.push(window.modalView.createDeleteButton("Delete",this.deleteCollection.bind(this))),d.push(window.modalView.createDeleteButton("Truncate",this.truncateCollection.bind(this))),c?d.push(window.modalView.createNotificationButton("Unload",this.unloadCollection.bind(this))):d.push(window.modalView.createNotificationButton("Load",this.loadCollection.bind(this))),d.push(window.modalView.createSuccessButton("Save",this.saveModifiedCollection.bind(this)));var a=["General","Indices"],b=["modalTable.ejs","indicesView.ejs"];window.modalView.show(b,"Modify Collection",d,e,null,null,this.events,null,a),"loaded"===this.model.get("status")?this.getIndex():$($("#infoTab").children()[1]).remove();
-}.bind(this);if(c){var g=function(a,b){if(a)arangoHelper.arangoError("Collection","Could not fetch properties");else{var c=b.journalSize/1048576,d=b.indexBuckets,g=b.waitForSync;e.push(window.modalView.createTextEntry("change-collection-size","Journal size",c,"The maximal size of a journal or datafile (in MB). Must be at least 1.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),e.push(window.modalView.createTextEntry("change-index-buckets","Index buckets",d,"The number of index buckets for this collection. Must be at least 1 and a power of 2.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[1-9][0-9]*$/),msg:"Must be a number greater than 1 and a power of 2."}])),e.push(window.modalView.createSelectEntry("change-collection-sync","Wait for sync",g,"Synchronize to disk before returning from a create or update of a document.",[{value:!1,label:"No"},{value:!0,label:"Yes"}]))}f()};this.model.getProperties(g)}else f()}}.bind(this);window.isCoordinator(a)},bindIndexEvents:function(){this.unbindIndexEvents();var a=this;$("#indexEditView #addIndex").bind("click",function(){a.toggleNewIndexView(),$("#cancelIndex").unbind("click"),$("#cancelIndex").bind("click",function(){a.toggleNewIndexView()}),$("#createIndex").unbind("click"),$("#createIndex").bind("click",function(){a.createIndex()})}),$("#newIndexType").bind("change",function(){a.selectIndexType()}),$(".deleteIndex").bind("click",function(b){a.prepDeleteIndex(b)}),$("#infoTab a").bind("click",function(a){if($("#indexDeleteModal").remove(),"Indices"!==$(a.currentTarget).html()||$(a.currentTarget).parent().hasClass("active")||($("#newIndexView").hide(),$("#indexEditView").show(),$("#modal-dialog .modal-footer .button-danger").hide(),$("#modal-dialog .modal-footer .button-success").hide(),$("#modal-dialog .modal-footer .button-notification").hide()),"General"===$(a.currentTarget).html()&&!$(a.currentTarget).parent().hasClass("active")){$("#modal-dialog .modal-footer .button-danger").show(),$("#modal-dialog .modal-footer .button-success").show(),$("#modal-dialog .modal-footer .button-notification").show();var b=$(".index-button-bar2")[0];$("#cancelIndex").is(":visible")&&($("#cancelIndex").detach().appendTo(b),$("#createIndex").detach().appendTo(b))}})},unbindIndexEvents:function(){$("#indexEditView #addIndex").unbind("click"),$("#newIndexType").unbind("change"),$("#infoTab a").unbind("click"),$(".deleteIndex").unbind("click")},createInfoModal:function(){var a=function(a,b,c){if(a)arangoHelper.arangoError("Figures","Could not get revision.");else{var d=[],e={figures:c,revision:b,model:this.model};window.modalView.show("modalCollectionInfo.ejs","Collection: "+this.model.get("name"),d,e)}}.bind(this),b=function(b,c){if(b)arangoHelper.arangoError("Figures","Could not get figures.");else{var d=c;this.model.getRevision(a,d)}}.bind(this);this.model.getFigures(b)},resetIndexForms:function(){$("#indexHeader input").val("").prop("checked",!1),$("#newIndexType").val("Geo").prop("selected",!0),this.selectIndexType()},createIndex:function(){var a,b,c,d=this,e=$("#newIndexType").val(),f={};switch(e){case"Geo":a=$("#newGeoFields").val();var g=d.checkboxToValue("#newGeoJson"),h=d.checkboxToValue("#newGeoConstraint"),i=d.checkboxToValue("#newGeoIgnoreNull");f={type:"geo",fields:d.stringToArray(a),geoJson:g,constraint:h,ignoreNull:i};break;case"Hash":a=$("#newHashFields").val(),b=d.checkboxToValue("#newHashUnique"),c=d.checkboxToValue("#newHashSparse"),f={type:"hash",fields:d.stringToArray(a),unique:b,sparse:c};break;case"Fulltext":a=$("#newFulltextFields").val();var j=parseInt($("#newFulltextMinLength").val(),10)||0;f={type:"fulltext",fields:d.stringToArray(a),minLength:j};break;case"Skiplist":a=$("#newSkiplistFields").val(),b=d.checkboxToValue("#newSkiplistUnique"),c=d.checkboxToValue("#newSkiplistSparse"),f={type:"skiplist",fields:d.stringToArray(a),unique:b,sparse:c}}var k=function(a,b){if(a)if(b){var c=JSON.parse(b.responseText);arangoHelper.arangoError("Document error",c.errorMessage)}else arangoHelper.arangoError("Document error","Could not create index.");d.refreshCollectionsView()};window.modalView.hide(),d.model.createIndex(f,k)},lastTarget:null,prepDeleteIndex:function(a){var b=this;this.lastTarget=a,this.lastId=$(this.lastTarget.currentTarget).parent().parent().first().children().first().text(),$("#modal-dialog .modal-footer").after('
")})}this.bindIndexEvents()},toggleNewIndexView:function(){var a=$(".index-button-bar2")[0];$("#indexEditView").is(":visible")?($("#indexEditView").hide(),$("#newIndexView").show(),$("#cancelIndex").detach().appendTo("#modal-dialog .modal-footer"),$("#createIndex").detach().appendTo("#modal-dialog .modal-footer")):($("#indexEditView").show(),$("#newIndexView").hide(),$("#cancelIndex").detach().appendTo(a),$("#createIndex").detach().appendTo(a)),arangoHelper.fixTooltips(".icon_arangodb, .arangoicon","right"),this.resetIndexForms()},stringToArray:function(a){var b=[];return a.split(",").forEach(function(a){a=a.replace(/(^\s+|\s+$)/g,""),""!==a&&b.push(a)}),b},checkboxToValue:function(a){return $(a).prop("checked")}})}(),function(){"use strict";window.CollectionsView=Backbone.View.extend({el:"#content",el2:"#collectionsThumbnailsIn",searchTimeout:null,refreshRate:1e4,template:templateEngine.createTemplate("collectionsView.ejs"),refetchCollections:function(){var a=this;this.collection.fetch({cache:!1,success:function(){a.checkLockedCollections()}})},checkLockedCollections:function(){var a=function(a,b){var c=this;a?console.log("Could not check locked collections"):(this.collection.each(function(a){a.set("locked",!1)}),_.each(b,function(a){var b=c.collection.findWhere({id:a.collection});b.set("locked",!0),b.set("lockType",a.type),b.set("desc",a.desc)}),this.collection.each(function(a){a.get("locked")||($("#collection_"+a.get("name")).find(".corneredBadge").removeClass("loaded unloaded"),$("#collection_"+a.get("name")+" .corneredBadge").text(a.get("status")),$("#collection_"+a.get("name")+" .corneredBadge").addClass(a.get("status"))),a.get("locked")||"loading"===a.get("status")?($("#collection_"+a.get("name")).addClass("locked"),a.get("locked")?($("#collection_"+a.get("name")).find(".corneredBadge").removeClass("loaded unloaded"),$("#collection_"+a.get("name")).find(".corneredBadge").addClass("inProgress"),$("#collection_"+a.get("name")+" .corneredBadge").text(a.get("desc"))):$("#collection_"+a.get("name")+" .corneredBadge").text(a.get("status"))):($("#collection_"+a.get("name")).removeClass("locked"),$("#collection_"+a.get("name")+" .corneredBadge").text(a.get("status")),$("#collection_"+a.get("name")+" .corneredBadge").hasClass("inProgress")&&($("#collection_"+a.get("name")+" .corneredBadge").text(a.get("status")),$("#collection_"+a.get("name")+" .corneredBadge").removeClass("inProgress"),$("#collection_"+a.get("name")+" .corneredBadge").addClass("loaded")),"unloaded"===a.get("status")&&$("#collection_"+a.get("name")+" .icon_arangodb_info").addClass("disabled"))}))}.bind(this);window.arangoHelper.syncAndReturnUninishedAardvarkJobs("index",a)},initialize:function(){var a=this;window.setInterval(function(){"#collections"===window.location.hash&&window.VISIBLE&&a.refetchCollections()},a.refreshRate)},render:function(){this.checkLockedCollections();var a=!1;$("#collectionsDropdown").is(":visible")&&(a=!0),$(this.el).html(this.template.render({})),this.setFilterValues(),a===!0&&$("#collectionsDropdown2").show();var b=this.collection.searchOptions;this.collection.getFiltered(b).forEach(function(a){$("#collectionsThumbnailsIn",this.el).append(new window.CollectionListItemView({model:a,collectionsView:this}).render().el)},this),"none"===$("#collectionsDropdown2").css("display")?$("#collectionsToggle").removeClass("activated"):$("#collectionsToggle").addClass("activated");var c;arangoHelper.setCheckboxStatus("#collectionsDropdown");try{c=b.searchPhrase.length}catch(d){}return $("#searchInput").val(b.searchPhrase),$("#searchInput").focus(),$("#searchInput")[0].setSelectionRange(c,c),arangoHelper.fixTooltips(".icon_arangodb, .arangoicon","left"),this},events:{"click #createCollection":"createCollection","keydown #searchInput":"restrictToSearchPhraseKey","change #searchInput":"restrictToSearchPhrase","click #searchSubmit":"restrictToSearchPhrase","click .checkSystemCollections":"checkSystem","click #checkLoaded":"checkLoaded","click #checkUnloaded":"checkUnloaded","click #checkDocument":"checkDocument","click #checkEdge":"checkEdge","click #sortName":"sortName","click #sortType":"sortType","click #sortOrder":"sortOrder","click #collectionsToggle":"toggleView","click .css-label":"checkBoxes"},updateCollectionsView:function(){var a=this;this.collection.fetch({cache:!1,success:function(){a.render()}})},toggleView:function(){$("#collectionsToggle").toggleClass("activated"),$("#collectionsDropdown2").slideToggle(200)},checkBoxes:function(a){var b=a.currentTarget.id;$("#"+b).click()},checkSystem:function(){var a=this.collection.searchOptions,b=a.includeSystem;a.includeSystem=$(".checkSystemCollections").is(":checked")===!0,b!==a.includeSystem&&this.render()},checkEdge:function(){var a=this.collection.searchOptions,b=a.includeEdge;a.includeEdge=$("#checkEdge").is(":checked")===!0,b!==a.includeEdge&&this.render()},checkDocument:function(){var a=this.collection.searchOptions,b=a.includeDocument;a.includeDocument=$("#checkDocument").is(":checked")===!0,b!==a.includeDocument&&this.render()},checkLoaded:function(){var a=this.collection.searchOptions,b=a.includeLoaded;a.includeLoaded=$("#checkLoaded").is(":checked")===!0,b!==a.includeLoaded&&this.render()},checkUnloaded:function(){var a=this.collection.searchOptions,b=a.includeUnloaded;a.includeUnloaded=$("#checkUnloaded").is(":checked")===!0,b!==a.includeUnloaded&&this.render()},sortName:function(){var a=this.collection.searchOptions,b=a.sortBy;a.sortBy=$("#sortName").is(":checked")===!0?"name":"type",b!==a.sortBy&&this.render()},sortType:function(){var a=this.collection.searchOptions,b=a.sortBy;a.sortBy=$("#sortType").is(":checked")===!0?"type":"name",b!==a.sortBy&&this.render()},sortOrder:function(){var a=this.collection.searchOptions,b=a.sortOrder;a.sortOrder=$("#sortOrder").is(":checked")===!0?-1:1,b!==a.sortOrder&&this.render()},setFilterValues:function(){var a=this.collection.searchOptions;$("#checkLoaded").attr("checked",a.includeLoaded),$("#checkUnloaded").attr("checked",a.includeUnloaded),$(".checkSystemCollections").attr("checked",a.includeSystem),$("#checkEdge").attr("checked",a.includeEdge),$("#checkDocument").attr("checked",a.includeDocument),$("#sortName").attr("checked","type"!==a.sortBy),$("#sortType").attr("checked","type"===a.sortBy),$("#sortOrder").attr("checked",1!==a.sortOrder)},search:function(){var a=this.collection.searchOptions,b=$("#searchInput").val();b!==a.searchPhrase&&(a.searchPhrase=b,this.render())},resetSearch:function(){this.searchTimeout&&(clearTimeout(this.searchTimeout),this.searchTimeout=null);var a=this.collection.searchOptions;a.searchPhrase=null},restrictToSearchPhraseKey:function(){var a=this;this.resetSearch(),a.searchTimeout=setTimeout(function(){a.search()},200)},restrictToSearchPhrase:function(){this.resetSearch(),this.search()},createCollection:function(a){a.preventDefault(),this.createNewCollectionModal()},submitCreateCollection:function(){var a=function(a,b){if(a)arangoHelper.arangoError("DB","Could not check coordinator state");else{var c=$("#new-collection-name").val(),d=$("#new-collection-size").val(),e=$("#new-replication-factor").val(),f=$("#new-collection-type").val(),g=$("#new-collection-sync").val(),h=1,i=[];if(""===e&&(e=1),b){if(h=$("#new-collection-shards").val(),""===h&&(h=1),h=parseInt(h,10),1>h)return arangoHelper.arangoError("Number of shards has to be an integer value greater or equal 1"),0;i=_.pluck($("#new-collection-shardBy").select2("data"),"text"),0===i.length&&i.push("_key")}if("_"===c.substr(0,1))return arangoHelper.arangoError('No "_" allowed as first character!'),0;var j=!1,k="true"===g;if(d>0)try{d=1024*JSON.parse(d)*1024}catch(l){return arangoHelper.arangoError("Please enter a valid number"),0}if(""===c)return arangoHelper.arangoError("No collection name entered!"),0;var m=function(a,b){if(a)try{b=JSON.parse(b.responseText),arangoHelper.arangoError("Error",b.errorMessage)}catch(c){}else this.updateCollectionsView();window.modalView.hide()}.bind(this);this.collection.newCollection({collName:c,wfs:k,isSystem:j,collSize:d,replicationFactor:e,collType:f,shards:h,shardBy:i},m)}}.bind(this);window.isCoordinator(a)},createNewCollectionModal:function(){var a=function(a,b){if(a)arangoHelper.arangoError("DB","Could not check coordinator state");else{var c=[],d=[],e={},f=[];d.push(window.modalView.createTextEntry("new-collection-name","Name","",!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only symbols, "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])),d.push(window.modalView.createSelectEntry("new-collection-type","Type","","The type of the collection to create.",[{value:2,label:"Document"},{value:3,label:"Edge"}])),b&&(d.push(window.modalView.createTextEntry("new-collection-shards","Shards","","The number of shards to create. You cannot change this afterwards. Recommended: DBServers squared","",!0)),d.push(window.modalView.createSelect2Entry("new-collection-shardBy","shardBy","","The keys used to distribute documents on shards. Type the key and press return to add it.","_key",!1))),c.push(window.modalView.createSuccessButton("Save",this.submitCreateCollection.bind(this))),f.push(window.modalView.createTextEntry("new-collection-size","Journal size","","The maximal size of a journal or datafile (in MB). Must be at least 1.","",!1,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),window.App.isCluster&&f.push(window.modalView.createTextEntry("new-replication-factor","Replication factor","","Numeric value. Must be at least 1. Description: TODO","",!1,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),f.push(window.modalView.createSelectEntry("new-collection-sync","Wait for sync","","Synchronize to disk before returning from a create or update of a document.",[{value:!1,label:"No"},{value:!0,label:"Yes"}])),e.header="Advanced",e.content=f,window.modalView.show("modalTable.ejs","New Collection",c,d,e),$("#s2id_new-collection-shardBy .select2-search-field input").on("focusout",function(a){$(".select2-drop").is(":visible")&&($("#select2-search-field input").is(":focus")||window.setTimeout(function(){$(a.currentTarget).parent().parent().parent().select2("close")},200))})}}.bind(this);window.isCoordinator(a)}})}(),function(){"use strict";function a(a,b){return void 0!==a&&null!==a||(a=0),a.toFixed(b)}window.DashboardView=Backbone.View.extend({el:"#content",interval:1e4,defaultTimeFrame:12e5,defaultDetailFrame:1728e5,history:{},graphs:{},events:{"click .subViewNavbar .subMenuEntry":"toggleViews"},tendencies:{asyncPerSecondCurrent:["asyncPerSecondCurrent","asyncPerSecondPercentChange"],syncPerSecondCurrent:["syncPerSecondCurrent","syncPerSecondPercentChange"],clientConnectionsCurrent:["clientConnectionsCurrent","clientConnectionsPercentChange"],clientConnectionsAverage:["clientConnections15M","clientConnections15MPercentChange"],numberOfThreadsCurrent:["numberOfThreadsCurrent","numberOfThreadsPercentChange"],numberOfThreadsAverage:["numberOfThreads15M","numberOfThreads15MPercentChange"],virtualSizeCurrent:["virtualSizeCurrent","virtualSizePercentChange"],virtualSizeAverage:["virtualSize15M","virtualSize15MPercentChange"]},barCharts:{totalTimeDistribution:["queueTimeDistributionPercent","requestTimeDistributionPercent"],dataTransferDistribution:["bytesSentDistributionPercent","bytesReceivedDistributionPercent"]},barChartsElementNames:{queueTimeDistributionPercent:"Queue",requestTimeDistributionPercent:"Computation",bytesSentDistributionPercent:"Bytes sent",bytesReceivedDistributionPercent:"Bytes received"},getDetailFigure:function(a){var b=$(a.currentTarget).attr("id").replace(/ChartButton/g,"");return b},showDetail:function(a){var b,c=this,d=this.getDetailFigure(a);b=this.dygraphConfig.getDetailChartConfig(d),this.getHistoryStatistics(d),this.detailGraphFigure=d,window.modalView.hideFooter=!0,window.modalView.hide(),window.modalView.show("modalGraph.ejs",b.header,void 0,void 0,void 0,void 0,this.events),window.modalView.hideFooter=!1,$("#modal-dialog").on("hidden",function(){c.hidden()}),$("#modal-dialog").toggleClass("modal-chart-detail",!0),b.height=.7*$(window).height(),b.width=$(".modal-inner-detail").width(),b.labelsDiv=$(b.labelsDiv)[0],this.detailGraph=new Dygraph(document.getElementById("lineChartDetail"),this.history[this.server][d],b)},hidden:function(){this.detailGraph.destroy(),delete this.detailGraph,delete this.detailGraphFigure},getCurrentSize:function(a){"#"!==a.substr(0,1)&&(a="#"+a);var b,c;return $(a).attr("style",""),b=$(a).height(),c=$(a).width(),{height:b,width:c}},prepareDygraphs:function(){var a,b=this;this.dygraphConfig.getDashBoardFigures().forEach(function(c){a=b.dygraphConfig.getDefaultConfig(c);var d=b.getCurrentSize(a.div);a.height=d.height,a.width=d.width,b.graphs[c]=new Dygraph(document.getElementById(a.div),b.history[b.server][c]||[],a)})},initialize:function(a){this.options=a,this.dygraphConfig=a.dygraphConfig,this.d3NotInitialized=!0,this.events["click .dashboard-sub-bar-menu-sign"]=this.showDetail.bind(this),this.events["mousedown .dygraph-rangesel-zoomhandle"]=this.stopUpdating.bind(this),this.events["mouseup .dygraph-rangesel-zoomhandle"]=this.startUpdating.bind(this),this.serverInfo=a.serverToShow,this.serverInfo?this.server=this.serverInfo.target:this.server="-local-",this.history[this.server]={}},toggleViews:function(a){var b=a.currentTarget.id.split("-")[0],c=this,d=["replication","requests","system"];_.each(d,function(a){b!==a?$("#"+a).hide():($("#"+a).show(),c.resize(),$(window).resize())}),$(".subMenuEntries").children().removeClass("active"),$("#"+b+"-statistics").addClass("active"),window.setTimeout(function(){c.resize(),$(window).resize()},200)},updateCharts:function(){var a=this;return this.detailGraph?void this.updateLineChart(this.detailGraphFigure,!0):(this.prepareD3Charts(this.isUpdating),this.prepareResidentSize(this.isUpdating),this.updateTendencies(),void Object.keys(this.graphs).forEach(function(b){a.updateLineChart(b,!1)}))},updateTendencies:function(){var a=this,b=this.tendencies,c="";Object.keys(b).forEach(function(b){var d="",e=0;a.history.hasOwnProperty(a.server)&&a.history[a.server].hasOwnProperty(b)&&(e=a.history[a.server][b][1]),0>e?c="#d05448":(c="#77DB99",d="+"),a.history.hasOwnProperty(a.server)&&a.history[a.server].hasOwnProperty(b)?$("#"+b).html(a.history[a.server][b][0]+' '+d+e+"%"):$("#"+b).html('
")}.bind(this);if("_system"!==frontendConfig.db)return void c();var d=function(d,e){d||(e?this.getStatistics(b,a):c())}.bind(this);void 0===window.App.currentDB.get("name")?window.setTimeout(function(){return"_system"!==window.App.currentDB.get("name")?void c():void this.options.database.hasSystemAccess(d)}.bind(this),300):this.options.database.hasSystemAccess(d)}})}(),function(){"use strict";window.DatabaseView=Backbone.View.extend({users:null,el:"#content",template:templateEngine.createTemplate("databaseView.ejs"),dropdownVisible:!1,currentDB:"",events:{"click #createDatabase":"createDatabase","click #submitCreateDatabase":"submitCreateDatabase","click .editDatabase":"editDatabase","click #userManagementView .icon":"editDatabase","click #selectDatabase":"updateDatabase","click #submitDeleteDatabase":"submitDeleteDatabase","click .contentRowInactive a":"changeDatabase","keyup #databaseSearchInput":"search","click #databaseSearchSubmit":"search","click #databaseToggle":"toggleSettingsDropdown","click .css-label":"checkBoxes","click #dbSortDesc":"sorting"},sorting:function(){$("#dbSortDesc").is(":checked")?this.collection.setSortingDesc(!0):this.collection.setSortingDesc(!1),$("#databaseDropdown").is(":visible")?this.dropdownVisible=!0:this.dropdownVisible=!1,this.render()},initialize:function(){this.collection.fetch({async:!0,cache:!1})},checkBoxes:function(a){var b=a.currentTarget.id;$("#"+b).click()},render:function(){var a=function(a,b){a?arangoHelper.arangoError("DB","Could not get current db properties"):(this.currentDB=b,this.collection.sort(),$(this.el).html(this.template.render({collection:this.collection,searchString:"",currentDB:this.currentDB})),this.dropdownVisible===!0&&($("#dbSortDesc").attr("checked",this.collection.sortOptions.desc),$("#databaseToggle").toggleClass("activated"),$("#databaseDropdown2").show()),arangoHelper.setCheckboxStatus("#databaseDropdown"),this.replaceSVGs())}.bind(this);return this.collection.getCurrentDatabase(a),this},toggleSettingsDropdown:function(){$("#dbSortDesc").attr("checked",this.collection.sortOptions.desc),$("#databaseToggle").toggleClass("activated"),$("#databaseDropdown2").slideToggle(200)},selectedDatabase:function(){return $("#selectDatabases").val()},handleError:function(a,b,c){return 409===a?void arangoHelper.arangoError("DB","Database "+c+" already exists."):400===a?void arangoHelper.arangoError("DB","Invalid Parameters"):403===a?void arangoHelper.arangoError("DB","Insufficent rights. Execute this from _system database"):void 0},validateDatabaseInfo:function(a,b){return""===b?(arangoHelper.arangoError("DB","You have to define an owner for the new database"),!1):""===a?(arangoHelper.arangoError("DB","You have to define a name for the new database"),!1):0===a.indexOf("_")?(arangoHelper.arangoError("DB ","Databasename should not start with _"),!1):a.match(/^[a-zA-Z][a-zA-Z0-9_\-]*$/)?!0:(arangoHelper.arangoError("DB","Databasename may only contain numbers, letters, _ and -"),!1)},createDatabase:function(a){a.preventDefault(),this.createAddDatabaseModal()},switchDatabase:function(a){if(!$(a.target).parent().hasClass("iconSet")){var b=$(a.currentTarget).find("h5").text();if(""!==b){var c=this.collection.createDatabaseURL(b);window.location.replace(c)}}},submitCreateDatabase:function(){var a=this,b=$("#newDatabaseName").val(),c=$("#newUser").val(),d={name:b};this.collection.create(d,{error:function(c,d){a.handleError(d.status,d.statusText,b)},success:function(d){"root"!==c&&$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(c)+"/database/"+encodeURIComponent(b)),contentType:"application/json",data:JSON.stringify({grant:"rw"})}),$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_api/user/root/database/"+encodeURIComponent(b)),contentType:"application/json",data:JSON.stringify({grant:"rw"})}),"#databases"===window.location.hash&&a.updateDatabases(),arangoHelper.arangoNotification("Database "+d.get("name")+" created.")}}),arangoHelper.arangoNotification("Database creation in progress."),window.modalView.hide()},submitDeleteDatabase:function(a){var b=this.collection.where({name:a});b[0].destroy({wait:!0,url:arangoHelper.databaseUrl("/_api/database/"+a)}),this.updateDatabases(),window.App.naviView.dbSelectionView.render($("#dbSelect")),window.modalView.hide()},changeDatabase:function(a){var b=$(a.currentTarget).attr("id"),c=this.collection.createDatabaseURL(b);window.location.replace(c)},updateDatabases:function(){var a=this;this.collection.fetch({cache:!1,success:function(){a.render(),window.App.handleSelectDatabase()}})},editDatabase:function(a){var b=this.evaluateDatabaseName($(a.currentTarget).attr("id"),"_edit-database"),c=!0;b===this.currentDB&&(c=!1),this.createEditDatabaseModal(b,c)},search:function(){var a,b,c,d;a=$("#databaseSearchInput"),b=$("#databaseSearchInput").val(),d=this.collection.filter(function(a){return-1!==a.get("name").indexOf(b)}),$(this.el).html(this.template.render({collection:d,searchString:b,currentDB:this.currentDB})),this.replaceSVGs(),a=$("#databaseSearchInput"),c=a.val().length,a.focus(),a[0].setSelectionRange(c,c)},replaceSVGs:function(){$(".svgToReplace").each(function(){var a=$(this),b=a.attr("id"),c=a.attr("src");$.get(c,function(c){var d=$(c).find("svg");d.attr("id",b).attr("class","tile-icon-svg").removeAttr("xmlns:a"),a.replaceWith(d)},"xml")})},evaluateDatabaseName:function(a,b){var c=a.lastIndexOf(b);return a.substring(0,c)},createEditDatabaseModal:function(a,b){var c=[],d=[];d.push(window.modalView.createReadOnlyEntry("id_name","Name",a,"")),b?c.push(window.modalView.createDeleteButton("Delete",this.submitDeleteDatabase.bind(this,a))):c.push(window.modalView.createDisabledButton("Delete")),window.modalView.show("modalTable.ejs","Delete database",c,d)},createAddDatabaseModal:function(){var a=[],b=[];b.push(window.modalView.createTextEntry("newDatabaseName","Name","",!1,"Database Name",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Database name must start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No database name given."}]));var c=[];window.App.userCollection.each(function(a){c.push({value:a.get("user"),label:a.get("user")})}),b.push(window.modalView.createSelectEntry("newUser","Username",null!==this.users?this.users.whoAmI():"root","Please define the owner of this database. This will be the only user having initial access to this database if authentication is turned on. Please note that if you specify a username different to your account you will not be able to access the database with your account after having creating it. Specifying a username is mandatory even with authentication turned off. If there is a failure you will be informed.",c)),a.push(window.modalView.createSuccessButton("Create",this.submitCreateDatabase.bind(this))),window.modalView.show("modalTable.ejs","Create Database",a,b),$("#useDefaultPassword").change(function(){"true"===$("#useDefaultPassword").val()?$("#row_newPassword").hide():$("#row_newPassword").show()}),$("#row_newPassword").hide()}})}(),function(){"use strict";window.DBSelectionView=Backbone.View.extend({template:templateEngine.createTemplate("dbSelectionView.ejs"),events:{"click .dbSelectionLink":"changeDatabase"},initialize:function(a){this.current=a.current},changeDatabase:function(a){var b=$(a.currentTarget).closest(".dbSelectionLink.tab").attr("id"),c=this.collection.createDatabaseURL(b);window.location.replace(c)},render:function(a){var b=function(b,c){b?arangoHelper.arangoError("DB","Could not fetch databases"):(this.$el=a,this.$el.html(this.template.render({list:c,current:this.current.get("name")})),this.delegateEvents())}.bind(this);return this.collection.getDatabasesForUser(b),this.el}})}(),function(){"use strict";window.DocumentsView=window.PaginationView.extend({filters:{0:!0},filterId:0,paginationDiv:"#documentsToolbarF",idPrefix:"documents",addDocumentSwitch:!0,activeFilter:!1,lastCollectionName:void 0,restoredFilters:[],editMode:!1,allowUpload:!1,el:"#content",table:"#documentsTableID",template:templateEngine.createTemplate("documentsView.ejs"),collectionContext:{prev:null,next:null},editButtons:["#deleteSelected","#moveSelected"],initialize:function(a){this.documentStore=a.documentStore,this.collectionsStore=a.collectionsStore,this.tableView=new window.TableView({el:this.table,collection:this.collection}),this.tableView.setRowClick(this.clicked.bind(this)),this.tableView.setRemoveClick(this.remove.bind(this))},resize:function(){$("#docPureTable").height($(".centralRow").height()-210),$("#docPureTable .pure-table-body").css("max-height",$("#docPureTable").height()-47)},setCollectionId:function(a,b){this.collection.setCollection(a),this.collection.setPage(b),this.page=b;var c=function(b,c){b?arangoHelper.arangoError("Error","Could not get collection properties."):(this.type=c,this.collection.getDocuments(this.getDocsCallback.bind(this)),this.collectionModel=this.collectionsStore.get(a))}.bind(this);arangoHelper.collectionApiType(a,null,c)},getDocsCallback:function(a){$("#documents_last").css("visibility","hidden"),$("#documents_first").css("visibility","hidden"),a?(window.progressView.hide(),arangoHelper.arangoError("Document error","Could not fetch requested documents.")):a&&void 0===a||(window.progressView.hide(),this.drawTable(),this.renderPaginationElements())},events:{"click #collectionPrev":"prevCollection","click #collectionNext":"nextCollection","click #filterCollection":"filterCollection","click #markDocuments":"editDocuments","click #importCollection":"importCollection","click #exportCollection":"exportCollection","click #filterSend":"sendFilter","click #addFilterItem":"addFilterItem","click .removeFilterItem":"removeFilterItem","click #deleteSelected":"deleteSelectedDocs","click #moveSelected":"moveSelectedDocs","click #addDocumentButton":"addDocumentModal","click #documents_first":"firstDocuments","click #documents_last":"lastDocuments","click #documents_prev":"prevDocuments","click #documents_next":"nextDocuments","click #confirmDeleteBtn":"confirmDelete","click .key":"nop",keyup:"returnPressedHandler","keydown .queryline input":"filterValueKeydown","click #importModal":"showImportModal","click #resetView":"resetView","click #confirmDocImport":"startUpload","click #exportDocuments":"startDownload","change #documentSize":"setPagesize","change #docsSort":"setSorting"},showSpinner:function(){$("#uploadIndicator").show()},hideSpinner:function(){$("#uploadIndicator").hide()},showImportModal:function(){$("#docImportModal").modal("show")},hideImportModal:function(){$("#docImportModal").modal("hide")},setPagesize:function(){var a=$("#documentSize").find(":selected").val();this.collection.setPagesize(a),this.collection.getDocuments(this.getDocsCallback.bind(this))},setSorting:function(){var a=$("#docsSort").val();""!==a&&void 0!==a&&null!==a||(a="_key"),this.collection.setSort(a)},returnPressedHandler:function(a){13===a.keyCode&&$(a.target).is($("#docsSort"))&&this.collection.getDocuments(this.getDocsCallback.bind(this)),13===a.keyCode&&$("#confirmDeleteBtn").attr("disabled")===!1&&this.confirmDelete()},nop:function(a){a.stopPropagation()},resetView:function(){var a=function(a){a&&arangoHelper.arangoError("Document","Could not fetch documents count")};$("input").val(""),$("select").val("=="),this.removeAllFilterItems(),$("#documentSize").val(this.collection.getPageSize()),$("#documents_last").css("visibility","visible"),$("#documents_first").css("visibility","visible"),this.addDocumentSwitch=!0,this.collection.resetFilter(),this.collection.loadTotal(a),this.restoredFilters=[],this.allowUpload=!1,this.files=void 0,this.file=void 0,$("#confirmDocImport").attr("disabled",!0),this.markFilterToggle(),this.collection.getDocuments(this.getDocsCallback.bind(this))},startDownload:function(){var a=this.collection.buildDownloadDocumentQuery();""!==a||void 0!==a||null!==a?window.open(encodeURI("query/result/download/"+btoa(JSON.stringify(a)))):arangoHelper.arangoError("Document error","could not download documents")},startUpload:function(){var a=function(a,b){a?(arangoHelper.arangoError("Upload",b),this.hideSpinner()):(this.hideSpinner(),this.hideImportModal(),this.resetView())}.bind(this);this.allowUpload===!0&&(this.showSpinner(),this.collection.uploadDocuments(this.file,a))},uploadSetup:function(){var a=this;$("#importDocuments").change(function(b){a.files=b.target.files||b.dataTransfer.files,a.file=a.files[0],$("#confirmDocImport").attr("disabled",!1),a.allowUpload=!0})},buildCollectionLink:function(a){return"collection/"+encodeURIComponent(a.get("name"))+"/documents/1"},markFilterToggle:function(){this.restoredFilters.length>0?$("#filterCollection").addClass("activated"):$("#filterCollection").removeClass("activated")},editDocuments:function(){$("#importCollection").removeClass("activated"),$("#exportCollection").removeClass("activated"),this.markFilterToggle(),$("#markDocuments").toggleClass("activated"),this.changeEditMode(),$("#filterHeader").hide(),$("#importHeader").hide(),$("#editHeader").slideToggle(200),$("#exportHeader").hide()},filterCollection:function(){$("#importCollection").removeClass("activated"),$("#exportCollection").removeClass("activated"),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),this.markFilterToggle(),this.activeFilter=!0,$("#importHeader").hide(),$("#editHeader").hide(),$("#exportHeader").hide(),$("#filterHeader").slideToggle(200);var a;for(a in this.filters)if(this.filters.hasOwnProperty(a))return void $("#attribute_name"+a).focus()},exportCollection:function(){$("#importCollection").removeClass("activated"),$("#filterHeader").removeClass("activated"),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),$("#exportCollection").toggleClass("activated"),this.markFilterToggle(),$("#exportHeader").slideToggle(200),$("#importHeader").hide(),$("#filterHeader").hide(),$("#editHeader").hide()},importCollection:function(){this.markFilterToggle(),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),$("#importCollection").toggleClass("activated"),$("#exportCollection").removeClass("activated"),$("#importHeader").slideToggle(200),$("#filterHeader").hide(),$("#editHeader").hide(),$("#exportHeader").hide()},changeEditMode:function(a){a===!1||this.editMode===!0?($("#docPureTable .pure-table-body .pure-table-row").css("cursor","default"),$(".deleteButton").fadeIn(),$(".addButton").fadeIn(),$(".selected-row").removeClass("selected-row"),this.editMode=!1,this.tableView.setRowClick(this.clicked.bind(this))):($("#docPureTable .pure-table-body .pure-table-row").css("cursor","copy"),$(".deleteButton").fadeOut(),$(".addButton").fadeOut(),$(".selectedCount").text(0),this.editMode=!0,this.tableView.setRowClick(this.editModeClick.bind(this)))},getFilterContent:function(){var a,b,c=[];for(a in this.filters)if(this.filters.hasOwnProperty(a)){b=$("#attribute_value"+a).val();try{b=JSON.parse(b)}catch(d){b=String(b)}""!==$("#attribute_name"+a).val()&&c.push({attribute:$("#attribute_name"+a).val(),operator:$("#operator"+a).val(),value:b})}return c},sendFilter:function(){this.restoredFilters=this.getFilterContent();var a=this;this.collection.resetFilter(),this.addDocumentSwitch=!1,_.each(this.restoredFilters,function(b){void 0!==b.operator&&a.collection.addFilter(b.attribute,b.operator,b.value)}),this.collection.setToFirst(),this.collection.getDocuments(this.getDocsCallback.bind(this)),this.markFilterToggle()},restoreFilter:function(){var a=this,b=0;this.filterId=0,$("#docsSort").val(this.collection.getSort()),_.each(this.restoredFilters,function(c){0!==b&&a.addFilterItem(),void 0!==c.operator&&($("#attribute_name"+b).val(c.attribute),$("#operator"+b).val(c.operator),$("#attribute_value"+b).val(c.value)),b++,a.collection.addFilter(c.attribute,c.operator,c.value)})},addFilterItem:function(){var a=++this.filterId;$("#filterHeader").append('
'),this.filters[a]=!0,this.checkFilterState()},filterValueKeydown:function(a){13===a.keyCode&&this.sendFilter()},checkFilterState:function(){var a=$("#filterHeader .queryline").length;if(1===a)$("#filterHeader .removeFilterItem").remove();else if(0===$("#filterHeader .queryline").first().find(".removeFilterItem").length){var b=$("#filterHeader .queryline").first().children().first().attr("id"),c=b.substr(14,b.length);$("#filterHeader .queryline").first().find(".add-filter-item").after(' ')}0===$("#filterHeader .queryline").first().find(".add-filter-item").length&&$("#filterHeader .queryline").first().find(".filterValue").after('')},removeFilterItem:function(a){var b=a.currentTarget,c=b.id.replace(/^removeFilter/,"");delete this.filters[c],delete this.restoredFilters[c],$(b.parentElement).remove(),this.checkFilterState()},removeAllFilterItems:function(){var a,b=$("#filterHeader").children().length;for(a=1;b>=a;a++)$("#removeFilter"+a).parent().remove();this.filters={0:!0},this.filterId=0},addDocumentModal:function(){var a=window.location.hash.split("/")[1],b=[],c=[],d=function(a,d){a?arangoHelper.arangoError("Error","Could not fetch collection type"):"edge"===d?(c.push(window.modalView.createTextEntry("new-edge-from-attr","_from","","document _id: document handle of the linked vertex (incoming relation)",void 0,!1,[{rule:Joi.string().required(),msg:"No _from attribute given."}])),c.push(window.modalView.createTextEntry("new-edge-to","_to","","document _id: document handle of the linked vertex (outgoing relation)",void 0,!1,[{rule:Joi.string().required(),msg:"No _to attribute given."}])),c.push(window.modalView.createTextEntry("new-edge-key-attr","_key",void 0,"the edges unique key(optional attribute, leave empty for autogenerated key","is optional: leave empty for autogenerated key",!1,[{rule:Joi.string().allow("").optional(),msg:""}])),b.push(window.modalView.createSuccessButton("Create",this.addEdge.bind(this))),window.modalView.show("modalTable.ejs","Create edge",b,c)):(c.push(window.modalView.createTextEntry("new-document-key-attr","_key",void 0,"the documents unique key(optional attribute, leave empty for autogenerated key","is optional: leave empty for autogenerated key",!1,[{rule:Joi.string().allow("").optional(),msg:""}])),b.push(window.modalView.createSuccessButton("Create",this.addDocument.bind(this))),window.modalView.show("modalTable.ejs","Create document",b,c))}.bind(this);arangoHelper.collectionApiType(a,!0,d)},addEdge:function(){var a,b=window.location.hash.split("/")[1],c=$(".modal-body #new-edge-from-attr").last().val(),d=$(".modal-body #new-edge-to").last().val(),e=$(".modal-body #new-edge-key-attr").last().val(),f=function(b,c){if(b)arangoHelper.arangoError("Error","Could not create edge");else{window.modalView.hide(),c=c._id.split("/");try{a="collection/"+c[0]+"/"+c[1],decodeURI(a)}catch(d){a="collection/"+c[0]+"/"+encodeURIComponent(c[1])}window.location.hash=a}};""!==e||void 0!==e?this.documentStore.createTypeEdge(b,c,d,e,f):this.documentStore.createTypeEdge(b,c,d,null,f)},addDocument:function(){var a,b=window.location.hash.split("/")[1],c=$(".modal-body #new-document-key-attr").last().val(),d=function(b,c){if(b)arangoHelper.arangoError("Error","Could not create document");else{window.modalView.hide(),c=c.split("/");try{a="collection/"+c[0]+"/"+c[1],decodeURI(a)}catch(d){a="collection/"+c[0]+"/"+encodeURIComponent(c[1])}window.location.hash=a}};""!==c||void 0!==c?this.documentStore.createTypeDocument(b,c,d):this.documentStore.createTypeDocument(b,null,d)},moveSelectedDocs:function(){var a=[],b=[],c=this.getSelectedDocs();0!==c.length&&(b.push(window.modalView.createTextEntry("move-documents-to","Move to","",!1,"collection-name",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])),a.push(window.modalView.createSuccessButton("Move",this.confirmMoveSelectedDocs.bind(this))),window.modalView.show("modalTable.ejs","Move documents",a,b))},confirmMoveSelectedDocs:function(){var a=this.getSelectedDocs(),b=this,c=$(".modal-body").last().find("#move-documents-to").val(),d=function(){this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide()}.bind(this);_.each(a,function(a){b.collection.moveDocument(a,b.collection.collectionID,c,d)})},deleteSelectedDocs:function(){var a=[],b=[],c=this.getSelectedDocs();0!==c.length&&(b.push(window.modalView.createReadOnlyEntry(void 0,c.length+" documents selected","Do you want to delete all selected documents?",void 0,void 0,!1,void 0)),a.push(window.modalView.createDeleteButton("Delete",this.confirmDeleteSelectedDocs.bind(this))),window.modalView.show("modalTable.ejs","Delete documents",a,b))},confirmDeleteSelectedDocs:function(){var a=this.getSelectedDocs(),b=[],c=this;_.each(a,function(a){if("document"===c.type){var d=function(a){a?(b.push(!1),arangoHelper.arangoError("Document error","Could not delete document.")):(b.push(!0),c.collection.setTotalMinusOne(),c.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(c);c.documentStore.deleteDocument(c.collection.collectionID,a,d)}else if("edge"===c.type){var e=function(a){a?(b.push(!1),arangoHelper.arangoError("Edge error","Could not delete edge")):(c.collection.setTotalMinusOne(),b.push(!0),c.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(c);c.documentStore.deleteEdge(c.collection.collectionID,a,e)}})},getSelectedDocs:function(){var a=[];return _.each($("#docPureTable .pure-table-body .pure-table-row"),function(b){$(b).hasClass("selected-row")&&a.push($($(b).children()[1]).find(".key").text())}),a},remove:function(a){this.docid=$(a.currentTarget).parent().parent().prev().find(".key").text(),$("#confirmDeleteBtn").attr("disabled",!1),$("#docDeleteModal").modal("show")},confirmDelete:function(){$("#confirmDeleteBtn").attr("disabled",!0);var a=window.location.hash.split("/"),b=a[3];"source"!==b&&this.reallyDelete()},reallyDelete:function(){if("document"===this.type){var a=function(a){a?arangoHelper.arangoError("Error","Could not delete document"):(this.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#docDeleteModal").modal("hide"))}.bind(this);this.documentStore.deleteDocument(this.collection.collectionID,this.docid,a)}else if("edge"===this.type){var b=function(a){a?arangoHelper.arangoError("Edge error","Could not delete edge"):(this.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#docDeleteModal").modal("hide"))}.bind(this);this.documentStore.deleteEdge(this.collection.collectionID,this.docid,b)}},editModeClick:function(a){var b=$(a.currentTarget);b.hasClass("selected-row")?b.removeClass("selected-row"):b.addClass("selected-row");var c=this.getSelectedDocs();$(".selectedCount").text(c.length),_.each(this.editButtons,function(a){c.length>0?($(a).prop("disabled",!1),$(a).removeClass("button-neutral"),$(a).removeClass("disabled"),"#moveSelected"===a?$(a).addClass("button-success"):$(a).addClass("button-danger")):($(a).prop("disabled",!0),$(a).addClass("disabled"),$(a).addClass("button-neutral"),"#moveSelected"===a?$(a).removeClass("button-success"):$(a).removeClass("button-danger"))})},clicked:function(a){var b,c=a.currentTarget,d=$(c).attr("id").substr(4);try{b="collection/"+this.collection.collectionID+"/"+d,decodeURI(d)}catch(e){b="collection/"+this.collection.collectionID+"/"+encodeURIComponent(d)}window.location.hash=b},drawTable:function(){this.tableView.setElement($("#docPureTable")).render(),arangoHelper.fixTooltips(".icon_arangodb, .arangoicon","top"),$(".prettify").snippet("javascript",{style:"nedit",menu:!1,startText:!1,transparent:!0,showNum:!1}),this.resize()},checkCollectionState:function(){this.lastCollectionName===this.collectionName?this.activeFilter&&(this.filterCollection(),this.restoreFilter()):void 0!==this.lastCollectionName&&(this.collection.resetFilter(),this.collection.setSort(""),this.restoredFilters=[],this.activeFilter=!1)},render:function(){return $(this.el).html(this.template.render({})),2===this.type?this.type="document":3===this.type&&(this.type="edge"),this.tableView.setElement($(this.table)).drawLoading(),this.collectionContext=this.collectionsStore.getPosition(this.collection.collectionID),this.collectionName=window.location.hash.split("/")[1],this.breadcrumb(),window.arangoHelper.buildCollectionSubNav(this.collectionName,"Content"),this.checkCollectionState(),this.lastCollectionName=this.collectionName,this.uploadSetup(),$("[data-toggle=tooltip]").tooltip(),$(".upload-info").tooltip(),arangoHelper.fixTooltips(".icon_arangodb, .arangoicon","top"),this.renderPaginationElements(),this.selectActivePagesize(),this.markFilterToggle(),this.resize(),this},rerender:function(){this.collection.getDocuments(this.getDocsCallback.bind(this)),this.resize()},selectActivePagesize:function(){$("#documentSize").val(this.collection.getPageSize())},renderPaginationElements:function(){this.renderPagination();var a=$("#totalDocuments");0===a.length&&($("#documentsToolbarFL").append(''),a=$("#totalDocuments")),"document"===this.type&&a.html(numeral(this.collection.getTotal()).format("0,0")+" doc(s)"),"edge"===this.type&&a.html(numeral(this.collection.getTotal()).format("0,0")+" edge(s)")},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)}})}(),function(){"use strict";var a=function(a){var b=a.split("/");return"collection/"+encodeURIComponent(b[0])+"/"+encodeURIComponent(b[1])};window.DocumentView=Backbone.View.extend({el:"#content",colid:0,docid:0,customView:!1,defaultMode:"tree",template:templateEngine.createTemplate("documentView.ejs"),events:{"click #saveDocumentButton":"saveDocument","click #deleteDocumentButton":"deleteDocumentModal","click #confirmDeleteDocument":"deleteDocument","click #document-from":"navigateToDocument","click #document-to":"navigateToDocument","keydown #documentEditor .ace_editor":"keyPress","keyup .jsoneditor .search input":"checkSearchBox","click .jsoneditor .modes":"storeMode","click #addDocument":"addDocument"},checkSearchBox:function(a){""===$(a.currentTarget).val()&&this.editor.expandAll()},addDocument:function(){window.App.documentsView.addDocumentModal()},storeMode:function(){var a=this;$(".type-modes").on("click",function(b){a.defaultMode=$(b.currentTarget).text().toLowerCase()})},keyPress:function(a){a.ctrlKey&&13===a.keyCode?(a.preventDefault(),this.saveDocument()):a.metaKey&&13===a.keyCode&&(a.preventDefault(),this.saveDocument())},editor:0,setType:function(a){a=2===a?"document":"edge";var b=function(a,b){if(a)arangoHelper.arangoError("Error","Could not fetch data.");else{var c=b+": ";this.type=b,this.fillInfo(c),this.fillEditor()}}.bind(this);"edge"===a?this.collection.getEdge(this.colid,this.docid,b):"document"===a&&this.collection.getDocument(this.colid,this.docid,b)},deleteDocumentModal:function(){var a=[],b=[];b.push(window.modalView.createReadOnlyEntry("doc-delete-button","Confirm delete, document id is",this.type._id,void 0,void 0,!1,/[<>&'"]/)),a.push(window.modalView.createDeleteButton("Delete",this.deleteDocument.bind(this))),window.modalView.show("modalTable.ejs","Delete Document",a,b)},deleteDocument:function(){var a=function(){if(this.customView)this.customDeleteFunction();else{var a="collection/"+encodeURIComponent(this.colid)+"/documents/1";window.modalView.hide(),window.App.navigate(a,{trigger:!0})}}.bind(this);if(this.type._from&&this.type._to){var b=function(b){b?arangoHelper.arangoError("Edge error","Could not delete edge"):a()};this.collection.deleteEdge(this.colid,this.docid,b)}else{var c=function(b){b?arangoHelper.arangoError("Error","Could not delete document"):a()};this.collection.deleteDocument(this.colid,this.docid,c)}},navigateToDocument:function(a){var b=$(a.target).attr("documentLink");b&&window.App.navigate(b,{trigger:!0})},fillInfo:function(){var b=this.collection.first(),c=b.get("_id"),d=b.get("_key"),e=b.get("_rev"),f=b.get("_from"),g=b.get("_to");if($("#document-type").css("margin-left","10px"),$("#document-type").text("_id:"),$("#document-id").css("margin-left","0"),$("#document-id").text(c),$("#document-key").text(d),$("#document-rev").text(e),f&&g){var h=a(f),i=a(g);$("#document-from").text(f),$("#document-from").attr("documentLink",h),$("#document-to").text(g),$("#document-to").attr("documentLink",i)}else $(".edge-info-container").hide()},fillEditor:function(){var a=this.removeReadonlyKeys(this.collection.first().attributes);$(".disabledBread").last().text(this.collection.first().get("_key")),this.editor.set(a),$(".ace_content").attr("font-size","11pt")},jsonContentChanged:function(){this.enableSaveButton()},resize:function(){$("#documentEditor").height($(".centralRow").height()-300)},render:function(){$(this.el).html(this.template.render({})),$("#documentEditor").height($(".centralRow").height()-300),this.disableSaveButton(),this.breadcrumb();var a=this,b=document.getElementById("documentEditor"),c={change:function(){a.jsonContentChanged()},search:!0,mode:"tree",modes:["tree","code"],iconlib:"fontawesome4"};return this.editor=new JSONEditor(b,c),this.editor.setMode(this.defaultMode),this},removeReadonlyKeys:function(a){return _.omit(a,["_key","_id","_from","_to","_rev"])},saveDocument:function(){if(void 0===$("#saveDocumentButton").attr("disabled"))if("_"===this.collection.first().attributes._id.substr(0,1)){var a=[],b=[];b.push(window.modalView.createReadOnlyEntry("doc-save-system-button","Caution","You are modifying a system collection. Really continue?",void 0,void 0,!1,/[<>&'"]/)),a.push(window.modalView.createSuccessButton("Save",this.confirmSaveDocument.bind(this))),window.modalView.show("modalTable.ejs","Modify System Collection",a,b)}else this.confirmSaveDocument()},confirmSaveDocument:function(){window.modalView.hide();
-var a;try{a=this.editor.get()}catch(b){return this.errorConfirmation(b),void this.disableSaveButton()}if(a=JSON.stringify(a),this.type._from&&this.type._to){var c=function(a){a?arangoHelper.arangoError("Error","Could not save edge."):(this.successConfirmation(),this.disableSaveButton())}.bind(this);this.collection.saveEdge(this.colid,this.docid,this.type._from,this.type._to,a,c)}else{var d=function(a){a?arangoHelper.arangoError("Error","Could not save document."):(this.successConfirmation(),this.disableSaveButton())}.bind(this);this.collection.saveDocument(this.colid,this.docid,a,d)}},successConfirmation:function(){arangoHelper.arangoNotification("Document saved.")},errorConfirmation:function(a){arangoHelper.arangoError("Document editor: ",a)},enableSaveButton:function(){$("#saveDocumentButton").prop("disabled",!1),$("#saveDocumentButton").addClass("button-success"),$("#saveDocumentButton").removeClass("button-close")},disableSaveButton:function(){$("#saveDocumentButton").prop("disabled",!0),$("#saveDocumentButton").addClass("button-close"),$("#saveDocumentButton").removeClass("button-success")},breadcrumb:function(){var a=window.location.hash.split("/");$("#subNavigationBar .breadcrumb").html('Collection: '+a[1]+'Document: '+a[2])},escaped:function(a){return a.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}})}(),function(){"use strict";window.FooterView=Backbone.View.extend({el:"#footerBar",system:{},isOffline:!0,isOfflineCounter:0,firstLogin:!0,timer:15e3,lap:0,timerFunction:null,events:{"click .footer-center p":"showShortcutModal"},initialize:function(){var a=this;window.setInterval(function(){a.getVersion()},a.timer),a.getVersion(),window.VISIBLE=!0,document.addEventListener("visibilitychange",function(){window.VISIBLE=!window.VISIBLE}),$("#offlinePlaceholder button").on("click",function(){a.getVersion()}),window.setTimeout(function(){window.frontendConfig.isCluster===!0&&($(".health-state").css("cursor","pointer"),$(".health-state").on("click",function(){window.App.navigate("#nodes",{trigger:!0})}))},1e3)},template:templateEngine.createTemplate("footerView.ejs"),showServerStatus:function(a){window.App.isCluster?this.renderClusterState(a):a===!0?($("#healthStatus").removeClass("negative"),$("#healthStatus").addClass("positive"),$(".health-state").html("GOOD"),$(".health-icon").html(''),$("#offlinePlaceholder").hide()):($("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),$(".health-state").html("UNKNOWN"),$(".health-icon").html(''),$("#offlinePlaceholder").show(),this.reconnectAnimation(0))},reconnectAnimation:function(a){var b=this;0===a&&(b.lap=a,$("#offlineSeconds").text(b.timer/1e3),clearTimeout(b.timerFunction)),b.lap0?($("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),1===c?$(".health-state").html(c+" NODE ERROR"):$(".health-state").html(c+" NODES ERROR"),$(".health-icon").html('')):($("#healthStatus").removeClass("negative"),$("#healthStatus").addClass("positive"),$(".health-state").html("NODES OK"),$(".health-icon").html(''))};$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,async:!0,success:function(a){b(a)}})}else $("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),$(".health-state").html(window.location.host+" OFFLINE"),$(".health-icon").html(''),$("#offlinePlaceholder").show(),this.reconnectAnimation(0)},showShortcutModal:function(){window.arangoHelper.hotkeysFunctions.showHotkeysModal()},getVersion:function(){var a=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/version"),contentType:"application/json",processData:!1,async:!0,success:function(b){a.showServerStatus(!0),a.isOffline===!0&&(a.isOffline=!1,a.isOfflineCounter=0,a.firstLogin?a.firstLogin=!1:window.setTimeout(function(){a.showServerStatus(!0)},1e3),a.system.name=b.server,a.system.version=b.version,a.render())},error:function(b){401===b.status?(a.showServerStatus(!0),window.App.navigate("login",{trigger:!0})):(a.isOffline=!0,a.isOfflineCounter++,a.isOfflineCounter>=1&&a.showServerStatus(!1))}}),a.system.hasOwnProperty("database")||$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/database/current"),contentType:"application/json",processData:!1,async:!0,success:function(b){var c=b.result.name;a.system.database=c;var d=window.setInterval(function(){var b=$("#databaseNavi");b&&(window.clearTimeout(d),d=null,a.render())},50)}})},renderVersion:function(){this.system.hasOwnProperty("database")&&this.system.hasOwnProperty("name")&&$(this.el).html(this.template.render({name:this.system.name,version:this.system.version,database:this.system.database}))},render:function(){return this.system.version||this.getVersion(),$(this.el).html(this.template.render({name:this.system.name,version:this.system.version})),this}})}(),function(){"use strict";window.FoxxActiveView=Backbone.View.extend({tagName:"div",className:"tile pure-u-1-1 pure-u-sm-1-2 pure-u-md-1-3 pure-u-lg-1-4 pure-u-xl-1-6",template:templateEngine.createTemplate("foxxActiveView.ejs"),_show:!0,events:{click:"openAppDetailView"},openAppDetailView:function(){window.App.navigate("service/"+encodeURIComponent(this.model.get("mount")),{trigger:!0})},toggle:function(a,b){switch(a){case"devel":this.model.isDevelopment()&&(this._show=b);break;case"production":this.model.isDevelopment()||this.model.isSystem()||(this._show=b);break;case"system":this.model.isSystem()&&(this._show=b)}this._show?$(this.el).show():$(this.el).hide()},render:function(){return this.model.fetchThumbnail(function(){$(this.el).html(this.template.render({model:this.model}));var a=function(){this.model.needsConfiguration()&&($(this.el).find(".warning-icons").length>0?$(this.el).find(".warning-icons").append(''):$(this.el).find("img").after(''))}.bind(this),b=function(){this.model.hasUnconfiguredDependencies()&&($(this.el).find(".warning-icons").length>0?$(this.el).find(".warning-icons").append(''):$(this.el).find("img").after(''))}.bind(this);this.model.getConfiguration(a),this.model.getDependencies(b)}.bind(this)),$(this.el)}})}(),function(){"use strict";var a={ERROR_SERVICE_DOWNLOAD_FAILED:{code:1752,message:"service download failed"}},b=templateEngine.createTemplate("applicationListView.ejs"),c=function(a){this.collection=a.collection},d=function(b){var c=this;if(b.error===!1)this.collection.fetch({success:function(){window.modalView.hide(),c.reload(),console.log(b),arangoHelper.arangoNotification("Services","Service "+b.name+" installed.")}});else{var d=b;switch(b.hasOwnProperty("responseJSON")&&(d=b.responseJSON),d.errorNum){case a.ERROR_SERVICE_DOWNLOAD_FAILED.code:arangoHelper.arangoError("Services","Unable to download application from the given repository.");break;default:arangoHelper.arangoError("Services",d.errorNum+". "+d.errorMessage)}}},e=function(){window.modalView.modalBindValidation({id:"new-app-mount",validateInput:function(){return[{rule:Joi.string().regex(/^(\/(APP[^\/]+|(?!APP)[a-zA-Z0-9_\-%]+))+$/i),msg:"May not contain /APP"},{rule:Joi.string().regex(/^(\/[a-zA-Z0-9_\-%]+)+$/),msg:"Can only contain [a-zA-Z0-9_-%]"},{rule:Joi.string().regex(/^\/([^_]|_open\/)/),msg:"Mountpoints with _ are reserved for internal use"},{rule:Joi.string().regex(/[^\/]$/),msg:"May not end with /"},{rule:Joi.string().regex(/^\//),msg:"Has to start with /"},{rule:Joi.string().required().min(2),msg:"Has to be non-empty"}]}})},f=function(){window.modalView.modalBindValidation({id:"repository",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+$/),msg:"No valid Github account and repository."}]}})},g=function(){window.modalView.modalBindValidation({id:"new-app-author",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-name",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z\-_][a-zA-Z0-9\-_]*$/),msg:"Can only contain a to z, A to Z, 0-9, '-' and '_'."}]}}),window.modalView.modalBindValidation({id:"new-app-description",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-license",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9 \.,;\-]+$/),msg:"Has to be non empty."}]}}),window.modalView.modalTestAll()},h=function(a){window.modalView.clearValidators();var b=$("#modalButton1");switch(this._upgrade||e(),a){case"newApp":b.html("Generate"),b.prop("disabled",!1),g();break;case"appstore":b.html("Install"),b.prop("disabled",!0);break;case"github":f(),b.html("Install"),b.prop("disabled",!1);break;case"zip":b.html("Install"),b.prop("disabled",!1)}b.prop("disabled")||window.modalView.modalTestAll()||b.prop("disabled",!0)},i=function(a){var b=$(a.currentTarget).attr("href").substr(1);h.call(this,b)},j=function(a){if(h.call(this,"appstore"),window.modalView.modalTestAll()){var b,c;this._upgrade?(b=this.mount,c=$("#new-app-teardown").prop("checked")):b=window.arangoHelper.escapeHtml($("#new-app-mount").val());var e=$(a.currentTarget).attr("appId"),f=$(a.currentTarget).attr("appVersion");void 0!==c?this.collection.installFromStore({name:e,version:f},b,d.bind(this),c):this.collection.installFromStore({name:e,version:f},b,d.bind(this)),window.modalView.hide(),arangoHelper.arangoNotification("Services","Installing "+e+".")}},k=function(a,b){if(void 0===b?b=this._uploadData:this._uploadData=b,b&&window.modalView.modalTestAll()){var c,e;this._upgrade?(c=this.mount,e=$("#new-app-teardown").prop("checked")):c=window.arangoHelper.escapeHtml($("#new-app-mount").val()),void 0!==e?this.collection.installFromZip(b.filename,c,d.bind(this),e):this.collection.installFromZip(b.filename,c,d.bind(this))}},l=function(){if(window.modalView.modalTestAll()){var a,b,c,e;this._upgrade?(c=this.mount,e=$("#new-app-teardown").prop("checked")):c=window.arangoHelper.escapeHtml($("#new-app-mount").val()),a=window.arangoHelper.escapeHtml($("#repository").val()),b=window.arangoHelper.escapeHtml($("#tag").val()),""===b&&(b="master");var f={url:window.arangoHelper.escapeHtml($("#repository").val()),version:window.arangoHelper.escapeHtml($("#tag").val())};try{Joi.assert(a,Joi.string().regex(/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+$/))}catch(g){return}void 0!==e?this.collection.installFromGithub(f,c,d.bind(this),e):this.collection.installFromGithub(f,c,d.bind(this))}},m=function(){if(window.modalView.modalTestAll()){var a,b;this._upgrade?(a=this.mount,b=$("#new-app-teardown").prop("checked")):a=window.arangoHelper.escapeHtml($("#new-app-mount").val());var c={name:window.arangoHelper.escapeHtml($("#new-app-name").val()),documentCollections:_.map($("#new-app-document-collections").select2("data"),function(a){return window.arangoHelper.escapeHtml(a.text)}),edgeCollections:_.map($("#new-app-edge-collections").select2("data"),function(a){return window.arangoHelper.escapeHtml(a.text)}),author:window.arangoHelper.escapeHtml($("#new-app-author").val()),license:window.arangoHelper.escapeHtml($("#new-app-license").val()),description:window.arangoHelper.escapeHtml($("#new-app-description").val())};void 0!==b?this.collection.generate(c,a,d.bind(this),b):this.collection.generate(c,a,d.bind(this))}},n=function(){var a=$(".modal-body .tab-pane.active").attr("id");switch(a){case"newApp":m.apply(this);break;case"github":l.apply(this);break;case"zip":k.apply(this)}},o=function(a,c){var d=[],e={"click #infoTab a":i.bind(a),"click .install-app":j.bind(a)};d.push(window.modalView.createSuccessButton("Generate",n.bind(a))),window.modalView.show("modalApplicationMount.ejs","Install Service",d,c,void 0,void 0,e),$("#new-app-document-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"}),$("#new-app-edge-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"});var f=function(){var a=$("#modalButton1");a.prop("disabled")||window.modalView.modalTestAll()?a.prop("disabled",!1):a.prop("disabled",!0)};$(".select2-search-field input").focusout(function(){f(),window.setTimeout(function(){$(".select2-drop").is(":visible")&&($("#select2-search-field input").is(":focus")||($("#s2id_new-app-document-collections").select2("close"),$("#s2id_new-app-edge-collections").select2("close"),f()))},200)}),$(".select2-search-field input").focusin(function(){if($(".select2-drop").is(":visible")){var a=$("#modalButton1");a.prop("disabled",!0)}}),$("#upload-foxx-zip").uploadFile({url:arangoHelper.databaseUrl("/_api/upload?multipart=true"),allowedTypes:"zip",multiple:!1,onSuccess:k.bind(a)}),$.get("foxxes/fishbowl",function(a){var c=$("#appstore-content");c.html(""),_.each(_.sortBy(a,"name"),function(a){c.append(b.render(a))})}).fail(function(){var a=$("#appstore-content");a.append("
Store is not available. ArangoDB is not able to connect to github.com
")})};c.prototype.install=function(a){this.reload=a,this._upgrade=!1,this._uploadData=void 0,delete this.mount,o(this,!1),window.modalView.clearValidators(),e(),g()},c.prototype.upgrade=function(a,b){this.reload=b,this._upgrade=!0,this._uploadData=void 0,this.mount=a,o(this,!0),window.modalView.clearValidators(),g()},window.FoxxInstallView=c}(),function(){"use strict";window.GraphManagementView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("graphManagementView.ejs"),edgeDefintionTemplate:templateEngine.createTemplate("edgeDefinitionTable.ejs"),eCollList:[],removedECollList:[],dropdownVisible:!1,initialize:function(a){this.options=a},events:{"click #deleteGraph":"deleteGraph","click .icon_arangodb_settings2.editGraph":"editGraph","click #createGraph":"addNewGraph","keyup #graphManagementSearchInput":"search","click #graphManagementSearchSubmit":"search","click .tile-graph":"redirectToGraphViewer","click #gv2":"redirectToGraphViewer2","click #graphManagementToggle":"toggleGraphDropdown","click .css-label":"checkBoxes","change #graphSortDesc":"sorting"},toggleTab:function(a){var b=a.currentTarget.id;b=b.replace("tab-",""),$("#tab-content-create-graph .tab-pane").removeClass("active"),$("#tab-content-create-graph #"+b).addClass("active"),"exampleGraphs"===b?$("#modal-dialog .modal-footer .button-success").css("display","none"):$("#modal-dialog .modal-footer .button-success").css("display","initial")},redirectToGraphViewer:function(a){var b=$(a.currentTarget).attr("id");b=b.substr(0,b.length-5),window.location=window.location+"/"+encodeURIComponent(b)},redirectToGraphViewer2:function(a){a.preventDefault();var b=$(a.currentTarget).parent().parent().attr("id");b=b.substr(0,b.length-5),console.log(b),window.App.navigate("graph2/"+encodeURIComponent(b),{trigger:!0})},loadGraphViewer:function(a,b){var c=function(b){if(b)arangoHelper.arangoError("","");else{var c=this.collection.get(a).get("edgeDefinitions");if(!c||0===c.length)return;var d={type:"gharial",graphName:a,baseUrl:arangoHelper.databaseUrl("/")},e=$("#content").width()-75;$("#content").html("");var f=arangoHelper.calculateCenterDivHeight();this.ui=new GraphViewerUI($("#content")[0],d,e,$(".centralRow").height()-135,{nodeShaper:{label:"_key",color:{type:"attribute",key:"_key"}}},!0),$(".contentDiv").height(f)}}.bind(this);b?this.collection.fetch({cache:!1,success:function(){c()}}):c()},handleResize:function(a){this.width&&this.width===a||(this.width=a,this.ui&&this.ui.changeWidth(a))},addNewGraph:function(a){a.preventDefault(),this.createEditGraphModal()},deleteGraph:function(){var a=this,b=$("#editGraphName")[0].value;if($("#dropGraphCollections").is(":checked")){var c=function(c){c?(a.collection.remove(a.collection.get(b)),a.updateGraphManagementView(),window.modalView.hide()):(window.modalView.hide(),arangoHelper.arangoError("Graph","Could not delete Graph."))};this.collection.dropAndDeleteGraph(b,c)}else this.collection.get(b).destroy({success:function(){a.updateGraphManagementView(),window.modalView.hide()},error:function(a,b){var c=JSON.parse(b.responseText),d=c.errorMessage;arangoHelper.arangoError(d),window.modalView.hide()}})},checkBoxes:function(a){var b=a.currentTarget.id;$("#"+b).click()},toggleGraphDropdown:function(){$("#graphSortDesc").attr("checked",this.collection.sortOptions.desc),$("#graphManagementToggle").toggleClass("activated"),$("#graphManagementDropdown2").slideToggle(200)},sorting:function(){$("#graphSortDesc").is(":checked")?this.collection.setSortingDesc(!0):this.collection.setSortingDesc(!1),$("#graphManagementDropdown").is(":visible")?this.dropdownVisible=!0:this.dropdownVisible=!1,this.render()},createExampleGraphs:function(a){var b=$(a.currentTarget).attr("graph-id"),c=this;$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_admin/aardvark/graph-examples/create/"+encodeURIComponent(b)),success:function(){window.modalView.hide(),c.updateGraphManagementView(),arangoHelper.arangoNotification("Example Graphs","Graph: "+b+" created.")},error:function(a){if(window.modalView.hide(),a.responseText)try{var c=JSON.parse(a.responseText);arangoHelper.arangoError("Example Graphs",c.errorMessage)}catch(d){arangoHelper.arangoError("Example Graphs","Could not create example graph: "+b)}else arangoHelper.arangoError("Example Graphs","Could not create example graph: "+b)}})},render:function(a,b){var c=this;return this.collection.fetch({cache:!1,success:function(){c.collection.sort(),$(c.el).html(c.template.render({graphs:c.collection,searchString:""})),c.dropdownVisible===!0&&($("#graphManagementDropdown2").show(),$("#graphSortDesc").attr("checked",c.collection.sortOptions.desc),$("#graphManagementToggle").toggleClass("activated"),$("#graphManagementDropdown").show()),c.events["click .tableRow"]=c.showHideDefinition.bind(c),c.events['change tr[id*="newEdgeDefinitions"]']=c.setFromAndTo.bind(c),c.events["click .graphViewer-icon-button"]=c.addRemoveDefinition.bind(c),c.events["click #graphTab a"]=c.toggleTab.bind(c),c.events["click .createExampleGraphs"]=c.createExampleGraphs.bind(c),c.events["focusout .select2-search-field input"]=function(a){$(".select2-drop").is(":visible")&&($("#select2-search-field input").is(":focus")||window.setTimeout(function(){$(a.currentTarget).parent().parent().parent().select2("close")},200))},arangoHelper.setCheckboxStatus("#graphManagementDropdown")}}),a&&this.loadGraphViewer(a,b),this},setFromAndTo:function(a){a.stopPropagation();var b,c=this.calculateEdgeDefinitionMap();if(a.added){if(-1===this.eCollList.indexOf(a.added.id)&&-1!==this.removedECollList.indexOf(a.added.id))return b=a.currentTarget.id.split("row_newEdgeDefinitions")[1],$('input[id*="newEdgeDefinitions'+b+'"]').select2("val",null),void $('input[id*="newEdgeDefinitions'+b+'"]').attr("placeholder","The collection "+a.added.id+" is already used.");this.removedECollList.push(a.added.id),this.eCollList.splice(this.eCollList.indexOf(a.added.id),1)}else this.eCollList.push(a.removed.id),this.removedECollList.splice(this.removedECollList.indexOf(a.removed.id),1);c[a.val]?(b=a.currentTarget.id.split("row_newEdgeDefinitions")[1],$("#s2id_fromCollections"+b).select2("val",c[a.val].from),$("#fromCollections"+b).attr("disabled",!0),$("#s2id_toCollections"+b).select2("val",c[a.val].to),$("#toCollections"+b).attr("disabled",!0)):(b=a.currentTarget.id.split("row_newEdgeDefinitions")[1],$("#s2id_fromCollections"+b).select2("val",null),$("#fromCollections"+b).attr("disabled",!1),$("#s2id_toCollections"+b).select2("val",null),$("#toCollections"+b).attr("disabled",!1))},editGraph:function(a){a.stopPropagation(),this.collection.fetch({cache:!1}),this.graphToEdit=this.evaluateGraphName($(a.currentTarget).attr("id"),"_settings");var b=this.collection.findWhere({_key:this.graphToEdit});this.createEditGraphModal(b)},saveEditedGraph:function(){var a,b,c,d,e,f=$("#editGraphName")[0].value,g=_.pluck($("#newVertexCollections").select2("data"),"text"),h=[],i={};if(e=$("[id^=s2id_newEdgeDefinitions]").toArray(),e.forEach(function(e){if(d=$(e).attr("id"),d=d.replace("s2id_newEdgeDefinitions",""),a=_.pluck($("#s2id_newEdgeDefinitions"+d).select2("data"),"text")[0],a&&""!==a&&(b=_.pluck($("#s2id_fromCollections"+d).select2("data"),"text"),c=_.pluck($("#s2id_toCollections"+d).select2("data"),"text"),0!==b.length&&0!==c.length)){var f={collection:a,from:b,to:c};h.push(f),i[a]=f}}),0===h.length)return $("#s2id_newEdgeDefinitions0 .select2-choices").css("border-color","red"),$("#s2id_newEdgeDefinitions0").parent().parent().next().find(".select2-choices").css("border-color","red"),void $("#s2id_newEdgeDefinitions0").parent().parent().next().next().find(".select2-choices").css("border-color","red");var j=this.collection.findWhere({_key:f}),k=j.get("edgeDefinitions"),l=j.get("orphanCollections"),m=[];l.forEach(function(a){-1===g.indexOf(a)&&j.deleteVertexCollection(a)}),g.forEach(function(a){-1===l.indexOf(a)&&j.addVertexCollection(a)});var n=[],o=[],p=[];k.forEach(function(a){var b=a.collection;m.push(b);var c=i[b];void 0===c?p.push(b):JSON.stringify(c)!==JSON.stringify(a)&&o.push(b)}),h.forEach(function(a){var b=a.collection;-1===m.indexOf(b)&&n.push(b)}),n.forEach(function(a){j.addEdgeDefinition(i[a])}),o.forEach(function(a){j.modifyEdgeDefinition(i[a])}),p.forEach(function(a){j.deleteEdgeDefinition(a)}),this.updateGraphManagementView(),window.modalView.hide()},evaluateGraphName:function(a,b){var c=a.lastIndexOf(b);return a.substring(0,c)},search:function(){var a,b,c,d;a=$("#graphManagementSearchInput"),b=$("#graphManagementSearchInput").val(),d=this.collection.filter(function(a){return-1!==a.get("_key").indexOf(b)}),$(this.el).html(this.template.render({graphs:d,searchString:b})),a=$("#graphManagementSearchInput"),c=a.val().length,a.focus(),a[0].setSelectionRange(c,c)},updateGraphManagementView:function(){var a=this;this.collection.fetch({cache:!1,success:function(){a.render()}})},createNewGraph:function(){var a,b,c,d,e,f=$("#createNewGraphName").val(),g=_.pluck($("#newVertexCollections").select2("data"),"text"),h=[],i=this;return f?this.collection.findWhere({_key:f})?(arangoHelper.arangoError("The graph '"+f+"' already exists."),0):(e=$("[id^=s2id_newEdgeDefinitions]").toArray(),e.forEach(function(e){d=$(e).attr("id"),d=d.replace("s2id_newEdgeDefinitions",""),a=_.pluck($("#s2id_newEdgeDefinitions"+d).select2("data"),"text")[0],a&&""!==a&&(b=_.pluck($("#s2id_fromCollections"+d).select2("data"),"text"),c=_.pluck($("#s2id_toCollections"+d).select2("data"),"text"),1!==b&&1!==c&&h.push({collection:a,from:b,to:c}))}),0===h.length?($("#s2id_newEdgeDefinitions0 .select2-choices").css("border-color","red"),$("#s2id_newEdgeDefinitions0").parent().parent().next().find(".select2-choices").css("border-color","red"),void $("#s2id_newEdgeDefinitions0").parent().parent().next().next().find(".select2-choices").css("border-color","red")):void this.collection.create({name:f,edgeDefinitions:h,orphanCollections:g},{success:function(){i.updateGraphManagementView(),window.modalView.hide()},error:function(a,b){var c=JSON.parse(b.responseText),d=c.errorMessage;d=d.replace("<",""),d=d.replace(">",""),arangoHelper.arangoError(d)}})):(arangoHelper.arangoError("A name for the graph has to be provided."),0)},createEditGraphModal:function(a){var b,c=[],d=[],e=[],f=this.options.collectionCollection.models,g=this,h="",i=[{collection:"",from:"",to:""}],j="",k=function(a,b){return a=a.toLowerCase(),b=b.toLowerCase(),b>a?-1:a>b?1:0};if(this.eCollList=[],this.removedECollList=[],f.forEach(function(a){a.get("isSystem")||("edge"===a.get("type")?g.eCollList.push(a.id):d.push(a.id))}),window.modalView.enableHotKeys=!1,this.counter=0,a?(b="Edit Graph",h=a.get("_key"),i=a.get("edgeDefinitions"),i&&0!==i.length||(i=[{collection:"",from:"",to:""}]),j=a.get("orphanCollections"),e.push(window.modalView.createReadOnlyEntry("editGraphName","Name",h,"The name to identify the graph. Has to be unique")),c.push(window.modalView.createDeleteButton("Delete",this.deleteGraph.bind(this))),c.push(window.modalView.createSuccessButton("Save",this.saveEditedGraph.bind(this)))):(b="Create Graph",e.push(window.modalView.createTextEntry("createNewGraphName","Name","","The name to identify the graph. Has to be unique.","graphName",!0)),c.push(window.modalView.createSuccessButton("Create",this.createNewGraph.bind(this)))),i.forEach(function(a){0===g.counter?(a.collection&&(g.removedECollList.push(a.collection),g.eCollList.splice(g.eCollList.indexOf(a.collection),1)),e.push(window.modalView.createSelect2Entry("newEdgeDefinitions"+g.counter,"Edge definitions",a.collection,"An edge definition defines a relation of the graph","Edge definitions",!0,!1,!0,1,g.eCollList.sort(k)))):e.push(window.modalView.createSelect2Entry("newEdgeDefinitions"+g.counter,"Edge definitions",a.collection,"An edge definition defines a relation of the graph","Edge definitions",!1,!0,!1,1,g.eCollList.sort(k))),e.push(window.modalView.createSelect2Entry("fromCollections"+g.counter,"fromCollections",a.from,"The collections that contain the start vertices of the relation.","fromCollections",!0,!1,!1,10,d.sort(k))),e.push(window.modalView.createSelect2Entry("toCollections"+g.counter,"toCollections",a.to,"The collections that contain the end vertices of the relation.","toCollections",!0,!1,!1,10,d.sort(k))),g.counter++}),e.push(window.modalView.createSelect2Entry("newVertexCollections","Vertex collections",j,"Collections that are part of a graph but not used in an edge definition","Vertex Collections",!1,!1,!1,10,d.sort(k))),window.modalView.show("modalGraphTable.ejs",b,c,e,void 0,void 0,this.events),a){$(".modal-body table").css("border-collapse","separate");var l;for($(".modal-body .spacer").remove(),l=0;l<=this.counter;l++)$("#row_fromCollections"+l).show(),$("#row_toCollections"+l).show(),$("#row_newEdgeDefinitions"+l).addClass("first"),$("#row_fromCollections"+l).addClass("middle"),$("#row_toCollections"+l).addClass("last"),$("#row_toCollections"+l).after('
')}},calculateEdgeDefinitionMap:function(){var a={};return this.collection.models.forEach(function(b){b.get("edgeDefinitions").forEach(function(b){a[b.collection]={from:b.from,to:b.to}})}),a}})}(),function(){"use strict";window.GraphSettingsView=Backbone.View.extend({el:"#graphSettingsContent",remove:function(){return this.$el.empty().off(),this.stopListening(),this},general:{graph:{type:"divider",name:"Graph"},nodeStart:{type:"string",name:"Starting node",desc:"A valid node id. If empty, a random node will be chosen.",value:2},layout:{type:"select",name:"Layout algorithm",desc:"Different graph displaying algorithms. No overlap is very fast, force is slower and fruchtermann is the slowest. The calculation time strongly depends on your nodes and edges counts.",noverlap:{name:"No overlap",val:"noverlap"},force:{name:"Force",val:"force"},fruchtermann:{name:"Fruchtermann",val:"fruchtermann"}},renderer:{type:"select",name:"Renderer",desc:"Canvas enables editing, WebGL is only for displaying a graph but much faster.",canvas:{name:"Canvas",val:"canvas"},webgl:{name:"WebGL",val:"webgl"}},depth:{desc:"Search depth, starting from your start node.",type:"number",name:"Search depth",value:2}},specific:{nodes:{type:"divider",name:"Nodes"},nodeLabel:{type:"string",name:"Label",desc:"Node label. Please choose a valid and available node attribute.","default":"_key"},nodeLabelByCollection:{type:"select",name:"Label by coll?",desc:"Set label text by collection. If activated node label attribute will be ignored.",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"}},nodeLabelThreshold:{type:"range",name:"Label threshold",desc:"The minimum size a node must have on screen to see its label displayed. This does not affect hovering behavior.","default":"_key"},nodeColor:{type:"color",name:"Color",desc:"Default node color. RGB or HEX value.","default":"#2ecc71"},nodeColorAttribute:{type:"string",name:"Colorize attr",desc:"If an attribute is given, nodes will then be colorized by the attribute. This setting ignores default node color if set."},nodeColorByCollection:{type:"select",name:"Colorize by coll?",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should nodes be colorized by their collection? If enabled, node color and node color attribute will be ignored."},nodeSize:{type:"string",name:"Sizing attribute",desc:"Default node size. Numeric value > 0."},edges:{type:"divider",name:"Edges"},edgeLabel:{type:"string",name:"Label",desc:"Default edge label."},edgeLabelByCollection:{type:"select",name:"Label by coll?",desc:"Set label text by collection. If activated edge label attribute will be ignored.",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"}},edgeLabelThreshold:{type:"range",name:"Label threshold",desc:"The minimum size an edge must have on screen to see its label displayed. This does not affect hovering behavior.","default":"_key"},edgeColor:{type:"color",name:"Color",desc:"Default edge color. RGB or HEX value.","default":"#cccccc"},edgeColorAttribute:{type:"string",name:"Colorize attr",desc:"If an attribute is given, edges will then be colorized by the attribute. This setting ignores default edge color if set."},edgeColorByCollection:{type:"select",name:"Colorize by coll?",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should edges be colorized by their collection? If enabled, edge color and edge color attribute will be ignored."
-},edgeEditable:{type:"select",name:"Editable",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should edges be editable?"},edgeType:{type:"select",name:"Type",desc:"The type of the edge",line:{name:"Line",val:"line"},arrow:{name:"Arrow",val:"arrow"},curve:{name:"Curve",val:"curve"},dotted:{name:"Dotted",val:"dotted"},dashed:{name:"Dashed",val:"dashed"},tapered:{name:"Tapered",val:"tapered"}}},template:templateEngine.createTemplate("graphSettingsView.ejs"),initialize:function(a){this.name=a.name,this.userConfig=a.userConfig,this.saveCallback=a.saveCallback},events:{"click #saveGraphSettings":"saveGraphSettings","click #restoreGraphSettings":"setDefaults","keyup #graphSettingsView input":"checkEnterKey","keyup #graphSettingsView select":"checkEnterKey",'change input[type="range"]':"saveGraphSettings",'change input[type="color"]':"checkColor","change select":"saveGraphSettings","focus #graphSettingsView input":"lastFocus","focus #graphSettingsView select":"lastFocus"},lastFocus:function(a){this.lastFocussed=a.currentTarget.id},checkEnterKey:function(a){13===a.keyCode&&this.saveGraphSettings()},getGraphSettings:function(a){var b=this,c=window.App.currentDB.toJSON().name+"_"+this.name;this.userConfig.fetch({success:function(d){b.graphConfig=d.toJSON().graphs[c],a&&b.continueRender()}})},checkColor:function(){this.saveGraphSettings(null,!0)},saveGraphSettings:function(a,b,c,d){var e=this,f=window.App.currentDB.toJSON().name+"_"+this.name,g={};if(d)g[f]=d;else{var h,i={};$("#graphSettingsView select").each(function(a,b){h=b.id,i[h.substr(2,b.id.length)]=$(b).val()}),$("#graphSettingsView input").each(function(a,b){h=b.id,i[h.substr(2,b.id.length)]=$(b).val()}),g[f]=i}c&&(g[f].nodeStart=c);var j=function(){window.App.graphViewer2?""!==b&&void 0!==b?window.App.graphViewer2.updateColors():window.App.graphViewer2.render(e.lastFocussed):arangoHelper.arangoNotification("Graph "+this.name,"Configuration saved.")}.bind(this);this.userConfig.setItem("graphs",g,j)},setDefaults:function(){var a={layout:"force",renderer:"canvas",depth:"2",nodeColor:"#2ecc71",nodeColorAttribute:"",nodeColorByCollection:"false",nodeLabelThreshold:10,edgeColor:"#cccccc",edgeColorAttribute:"",edgeColorByCollection:"false",edgeLabelThreshold:10,nodeLabel:"_key",edgeLabel:"",edgeType:"line",nodeSize:"",edgeEditable:"false",nodeLabelByCollection:"false",edgeLabelByCollection:"false",nodeStart:""};this.saveGraphSettings(null,null,null,a),this.render(),window.App.graphViewer2.render(this.lastFocussed)},toggle:function(){$(this.el).is(":visible")?this.hide():this.show()},show:function(){$(this.el).show("slide",{direction:"right"},250)},hide:function(){$(this.el).hide("slide",{direction:"right"},250)},render:function(){this.getGraphSettings(!0)},continueRender:function(){$(this.el).html(this.template.render({general:this.general,specific:this.specific})),arangoHelper.fixTooltips(".gv-tooltips","top"),this.graphConfig?(_.each(this.graphConfig,function(a,b){$("#g_"+b).val(a)}),$("#g_nodeLabelThreshold_label").text(this.graphConfig.nodeLabelThreshold),$("#g_edgeLabelThreshold_label").text(this.graphConfig.edgeLabelThreshold)):this.setDefaults()}})}(),function(){"use strict";window.GraphViewer2=Backbone.View.extend({el:"#content",remove:function(){return this.$el.empty().off(),this.stopListening(),this},template:templateEngine.createTemplate("graphViewer2.ejs"),initialize:function(a){var b=this;a.id&&(this.setElement(a.id),this.graphData=a.data,this.aqlMode=!0),this.name=a.name,this.userConfig=a.userConfig,this.documentStore=a.documentStore,this.initSigma(),void 0!==this.name&&this.collection.fetch({cache:!1,success:function(c){b.model=b.collection.findWhere({_key:a.name}).toJSON()}})},colors:{hotaru:["#364C4A","#497C7F","#92C5C0","#858168","#CCBCA5"],random1:["#292F36","#4ECDC4","#F7FFF7","#DD6363","#FFE66D"]},aqlMode:!1,events:{"click #downloadPNG":"downloadSVG","click #reloadGraph":"reloadGraph","click #settingsMenu":"toggleSettings","click #noGraphToggle":"toggleSettings","click #toggleForce":"toggleLayout","click #selectNodes":"toggleLasso"},cursorX:0,cursorY:0,layouting:!1,model:null,viewStates:{captureMode:!1},graphConfig:null,graphSettings:null,initSigma:function(){try{sigma.classes.graph.addMethod("neighbors",function(a){var b,c={},d=this.allNeighborsIndex[a]||{};for(b in d)c[b]=this.nodesIndex[b];return c}),sigma.classes.graph.addMethod("getNodeEdges",function(a){var b=this.edges(),c=[];return _.each(b,function(b){b.source!==a&&b.target!==a||c.push(b.id)}),c})}catch(a){}},downloadSVG:function(){var a=this;this.currentGraph.toSVG({download:!0,filename:a.name+".svg",size:1e3})},resize:function(){$("#graph-container").width($(".centralContent").width()),$("#graph-container").height($(".centralRow").height()-150)},toggleSettings:function(){this.graphSettingsView.toggle()},render:function(a){this.$el.html(this.template.render({})),$("#subNavigationBar .breadcrumb").html("Graph: "+this.name),this.resize(),this.fetchGraph(a)},renderAQL:function(a){this.$el.html(this.template.render({})),this.$el.find(".headerBar").remove();var b=$(".centralRow").height()-250;this.$el.find("#graph-container").css("height",b),this.graphData.modified=this.parseData(this.graphData.original,this.graphData.graphInfo),this.renderGraph(this.graphData.modified)},parseData:function(a,b){var c={},d={},e={nodes:[],edges:[],settings:{}};return"object"===b?(_.each(a,function(a){a.edges&&a.vertices&&(_.each(a.edges,function(a){d[a._id]={id:a._id,source:a._from,label:a._key,color:"#cccccc",target:a._to}}),_.each(a.vertices,function(a){c[a._id]={id:a._id,label:a._key,size:.3,color:"#2ecc71",x:Math.random(),y:Math.random()}}))}),_.each(c,function(a){e.nodes.push(a)}),_.each(d,function(a){e.edges.push(a)})):"array"===b&&(_.each(a,function(a){c[a._from]=null,c[a._to]=null,e.edges.push({id:a._id,source:a._from,label:a._key,color:"#cccccc",target:a._to})}),_.each(c,function(a,b){e.nodes.push({id:b,label:b,size:.3,color:"#2ecc71",x:Math.random(),y:Math.random()})})),e},rerender:function(){this.fetchGraph()},fetchGraph:function(a){var b=this;$(this.el).append('
Fetching graph data. Please wait ... If it`s taking too much time to draw the graph, please go to: '+window.location.href+"/settings and adjust your settings.It is possible that the graph is too big to be handled by the browser.
')},fillBindParamTable:function(a){_.each(a,function(a,b){_.each($("#arangoBindParamTable input"),function(c){$(c).attr("name")===b&&$(c).val(a)})})},initAce:function(){var a=this;this.aqlEditor=ace.edit("aqlEditor"),this.aqlEditor.getSession().setMode("ace/mode/aql"),this.aqlEditor.setFontSize("10pt"),this.aqlEditor.setShowPrintMargin(!1),this.bindParamAceEditor=ace.edit("bindParamAceEditor"),this.bindParamAceEditor.getSession().setMode("ace/mode/json"),this.bindParamAceEditor.setFontSize("10pt"),this.bindParamAceEditor.setShowPrintMargin(!1),this.bindParamAceEditor.getSession().on("change",function(){try{a.bindParamTableObj=JSON.parse(a.bindParamAceEditor.getValue()),a.allowParamToggle=!0,a.setCachedQuery(a.aqlEditor.getValue(),JSON.stringify(a.bindParamTableObj))}catch(b){""===a.bindParamAceEditor.getValue()?(_.each(a.bindParamTableObj,function(b,c){a.bindParamTableObj[c]=""}),a.allowParamToggle=!0):a.allowParamToggle=!1}}),this.aqlEditor.getSession().on("change",function(){a.checkForNewBindParams(),a.renderBindParamTable(),a.initDone&&a.setCachedQuery(a.aqlEditor.getValue(),JSON.stringify(a.bindParamTableObj)),a.bindParamAceEditor.setValue(JSON.stringify(a.bindParamTableObj,null," "),1),$("#aqlEditor .ace_text-input").focus(),a.resize()}),this.aqlEditor.commands.addCommand({name:"togglecomment",bindKey:{win:"Ctrl-Shift-C",linux:"Ctrl-Shift-C",mac:"Command-Shift-C"},exec:function(a){a.toggleCommentLines()},multiSelectAction:"forEach"}),this.aqlEditor.commands.addCommand({name:"executeQuery",bindKey:{win:"Ctrl-Return",mac:"Command-Return",linux:"Ctrl-Return"},exec:function(){a.executeQuery()}}),this.aqlEditor.commands.addCommand({name:"saveQuery",bindKey:{win:"Ctrl-Shift-S",mac:"Command-Shift-S",linux:"Ctrl-Shift-S"},exec:function(){a.addAQL()}}),this.aqlEditor.commands.addCommand({name:"explainQuery",bindKey:{win:"Ctrl-Shift-Return",mac:"Command-Shift-Return",linux:"Ctrl-Shift-Return"},exec:function(){a.explainQuery()}}),this.aqlEditor.commands.addCommand({name:"togglecomment",bindKey:{win:"Ctrl-Shift-C",linux:"Ctrl-Shift-C",mac:"Command-Shift-C"},exec:function(a){a.toggleCommentLines()},multiSelectAction:"forEach"}),this.aqlEditor.commands.addCommand({name:"showSpotlight",bindKey:{win:"Ctrl-Space",mac:"Ctrl-Space",linux:"Ctrl-Space"},exec:function(){a.showSpotlight()}}),this.queryPreview=ace.edit("queryPreview"),this.queryPreview.getSession().setMode("ace/mode/aql"),this.queryPreview.setReadOnly(!0),this.queryPreview.setFontSize("13px"),$("#aqlEditor .ace_text-input").focus()},updateQueryTable:function(){function a(a,b){var c;return c=a.nameb.name?1:0}var b=this;this.updateLocalQueries(),this.myQueriesTableDesc.rows=this.customQueries,_.each(this.myQueriesTableDesc.rows,function(a){a.secondRow='',a.hasOwnProperty("parameter")&&delete a.parameter,delete a.value}),this.myQueriesTableDesc.rows.sort(a),_.each(this.queries,function(a){a.hasOwnProperty("parameter")&&delete a.parameter,b.myQueriesTableDesc.rows.push({name:a.name,thirdRow:''})}),this.myQueriesTableDesc.unescaped=[!1,!0,!0],this.$(this.myQueriesId).html(this.table.render({content:this.myQueriesTableDesc}))},listenKey:function(a){13===a.keyCode&&"Update"===$("#modalButton1").html()&&this.saveAQL(),this.checkSaveName()},addAQL:function(){this.refreshAQL(!0),this.createCustomQueryModal(),setTimeout(function(){$("#new-query-name").focus()},500)},createCustomQueryModal:function(){var a=[],b=[];b.push(window.modalView.createTextEntry("new-query-name","Name","",void 0,void 0,!1,[{rule:Joi.string().required(),msg:"No query name given."}])),a.push(window.modalView.createSuccessButton("Save",this.saveAQL.bind(this))),window.modalView.show("modalTable.ejs","Save Query",a,b,void 0,void 0,{"keyup #new-query-name":this.listenKey.bind(this)})},checkSaveName:function(){var a=$("#new-query-name").val();if("Insert Query"===a)return void $("#new-query-name").val("");var b=this.customQueries.some(function(b){return b.name===a});b?($("#modalButton1").removeClass("button-success"),$("#modalButton1").addClass("button-warning"),$("#modalButton1").text("Update")):($("#modalButton1").removeClass("button-warning"),$("#modalButton1").addClass("button-success"),$("#modalButton1").text("Save"))},saveAQL:function(a){a&&a.stopPropagation(),this.refreshAQL();var b=$("#new-query-name").val(),c=this.bindParamTableObj;if(!$("#new-query-name").hasClass("invalid-input")&&""!==b.trim()){var d=this.aqlEditor.getValue(),e=!1;if(_.each(this.customQueries,function(a){return a.name===b?(a.value=d,void(e=!0)):void 0}),e===!0)this.collection.findWhere({name:b}).set("value",d);else{if(""!==c&&void 0!==c||(c="{}"),"string"==typeof c)try{c=JSON.parse(c)}catch(f){arangoHelper.arangoError("Query","Could not parse bind parameter")}this.collection.add({name:b,parameter:c,value:d})}var g=function(a){if(a)arangoHelper.arangoError("Query","Could not save query");else{var b=this;this.collection.fetch({success:function(){b.updateLocalQueries()}})}}.bind(this);this.collection.saveCollectionQueries(g),window.modalView.hide()}},verifyQueryAndParams:function(){var a=!1;0===this.aqlEditor.getValue().length&&(arangoHelper.arangoError("Query","Your query is empty"),a=!0);var b=[];return _.each(this.bindParamTableObj,function(c,d){""===c&&(a=!0,b.push(d))}),b.length>0&&arangoHelper.arangoError("Bind Parameter",JSON.stringify(b)+" not defined."),a},executeQuery:function(){if(!this.verifyQueryAndParams()){this.$(this.outputDiv).prepend(this.outputTemplate.render({counter:this.outputCounter,type:"Query"})),$("#outputEditorWrapper"+this.outputCounter).hide(),$("#outputEditorWrapper"+this.outputCounter).show("fast");var a=this.outputCounter,b=ace.edit("outputEditor"+a),c=ace.edit("sentQueryEditor"+a),d=ace.edit("sentBindParamEditor"+a);c.getSession().setMode("ace/mode/aql"),c.setOption("vScrollBarAlwaysVisible",!0),c.setFontSize("13px"),c.setReadOnly(!0),this.setEditorAutoHeight(c),b.setFontSize("13px"),b.getSession().setMode("ace/mode/json"),b.setReadOnly(!0),b.setOption("vScrollBarAlwaysVisible",!0),b.setShowPrintMargin(!1),this.setEditorAutoHeight(b),d.setValue(JSON.stringify(this.bindParamTableObj),1),d.setOption("vScrollBarAlwaysVisible",!0),d.getSession().setMode("ace/mode/json"),d.setReadOnly(!0),this.setEditorAutoHeight(d),this.fillResult(b,c,a),this.outputCounter++}},readQueryData:function(){var a=$("#querySize"),b={query:this.aqlEditor.getValue(),id:"currentFrontendQuery"};return"all"===a.val()?b.batchSize=1e6:b.batchSize=parseInt(a.val(),10),Object.keys(this.bindParamTableObj).length>0&&(b.bindVars=this.bindParamTableObj),JSON.stringify(b)},fillResult:function(a,b,c){var d=this,e=this.readQueryData();e&&(b.setValue(d.aqlEditor.getValue(),1),$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_api/cursor"),headers:{"x-arango-async":"store"},data:e,contentType:"application/json",processData:!1,success:function(b,e,f){f.getResponseHeader("x-arango-async-id")&&d.queryCallbackFunction(f.getResponseHeader("x-arango-async-id"),a,c),$.noty.clearQueue(),$.noty.closeAll(),d.handleResult(c)},error:function(a){try{var b=JSON.parse(a.responseText);arangoHelper.arangoError("["+b.errorNum+"]",b.errorMessage)}catch(e){arangoHelper.arangoError("Query error","ERROR")}d.handleResult(c)}}))},handleResult:function(){var a=this;window.progressView.hide(),$("#removeResults").show(),window.setTimeout(function(){a.aqlEditor.focus()},300),$(".centralRow").animate({scrollTop:$("#queryContent").height()},"fast")},setEditorAutoHeight:function(a){var b=$(".centralRow").height(),c=(b-250)/17;a.setOptions({maxLines:c,minLines:10})},deselect:function(a){var b=a.getSelection(),c=b.lead.row,d=b.lead.column;b.setSelectionRange({start:{row:c,column:d},end:{row:c,column:d}}),a.focus()},queryCallbackFunction:function(a,b,c){var d=this,e=function(a,b){$.ajax({url:arangoHelper.databaseUrl("/_api/job/"+encodeURIComponent(a)+"/cancel"),type:"PUT",success:function(){window.clearTimeout(d.checkQueryTimer),$("#outputEditorWrapper"+b).remove(),arangoHelper.arangoNotification("Query","Query canceled.")}})};$("#outputEditorWrapper"+c+" #cancelCurrentQuery").bind("click",function(){e(a,c)}),$("#outputEditorWrapper"+c+" #copy2aqlEditor").bind("click",function(){$("#toggleQueries1").is(":visible")||d.toggleQueries();var a=ace.edit("sentQueryEditor"+c).getValue(),b=JSON.parse(ace.edit("sentBindParamEditor"+c).getValue());d.aqlEditor.setValue(a,1),d.deselect(d.aqlEditor),Object.keys(b).length>0&&(d.bindParamTableObj=b,d.setCachedQuery(d.aqlEditor.getValue(),JSON.stringify(d.bindParamTableObj)),$("#bindParamEditor").is(":visible")?d.renderBindParamTable():(d.bindParamAceEditor.setValue(JSON.stringify(b),1),d.deselect(d.bindParamAceEditor))),$(".centralRow").animate({scrollTop:0},"fast"),d.resize()}),this.execPending=!1;var f=function(a){var c="";a.extra&&a.extra.warnings&&a.extra.warnings.length>0&&(c+="Warnings:\r\n\r\n",a.extra.warnings.forEach(function(a){c+="["+a.code+"], '"+a.message+"'\r\n"})),""!==c&&(c+="\r\nResult:\r\n\r\n"),b.setValue(c+JSON.stringify(a.result,void 0,2),1),b.getSession().setScrollTop(0)},g=function(a){f(a),window.progressView.hide();var e=d.analyseQuery(a.result);if(console.log("Using "+e.defaultType+" as data format."),"table"===e.defaultType){$("#outputEditorWrapper"+c+" .arangoToolbarTop").after(''),$("#outputTable"+c).show(),d.renderOutputTable(e,c);var g=$(".centralRow").height()-250;$(".outputEditorWrapper .tableWrapper").css("max-height",g),$("#outputEditor"+c).hide()}else"graph"===e.defaultType&&($("#outputEditorWrapper"+c+" .arangoToolbarTop").after(''),$("#outputGraph"+c).show(),d.renderOutputGraph(e,c),$("#outputEditor"+c).hide());$("#"+e.defaultType+"-switch").addClass("active").css("display","inline");var h=function(a,b,d){d||(d=""),$("#outputEditorWrapper"+c+" .arangoToolbarTop .pull-left").append(''+a+"")};$("#outputEditorWrapper"+c+" .pull-left #spinner").remove();var i="-";a&&a.extra&&a.extra.stats&&(i=a.extra.stats.executionTime.toFixed(3)+" s"),h(a.result.length+" elements","fa-calculator"),h(i,"fa-clock-o"),a.extra&&a.extra.stats&&(a.extra.stats.writesExecuted>0||a.extra.stats.writesIgnored>0)&&(h(a.extra.stats.writesExecuted+" writes","fa-check-circle positive"),0===a.extra.stats.writesIgnored?h(a.extra.stats.writesIgnored+" writes ignored","fa-check-circle positive","additional"):h(a.extra.stats.writesIgnored+" writes ignored","fa-exclamation-circle warning","additional")),$("#outputEditorWrapper"+c+" .switchAce").show(),$("#outputEditorWrapper"+c+" .fa-close").show(),$("#outputEditor"+c).css("opacity","1"),$("#outputEditorWrapper"+c+" #downloadQueryResult").show(),$("#outputEditorWrapper"+c+" #copy2aqlEditor").show(),$("#outputEditorWrapper"+c+" #cancelCurrentQuery").remove(),d.setEditorAutoHeight(b),d.deselect(b),a.id&&$.ajax({url:"/_api/cursor/"+encodeURIComponent(a.id),type:"DELETE"})},h=function(){$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_api/job/"+encodeURIComponent(a)),contentType:"application/json",processData:!1,success:function(a,b,c){201===c.status?g(a):204===c.status&&(d.checkQueryTimer=window.setTimeout(function(){h()},500))},error:function(a){var b;try{if("Gone"===a.statusText)return arangoHelper.arangoNotification("Query","Query execution aborted."),void d.removeOutputEditor(c);b=JSON.parse(a.responseText),arangoHelper.arangoError("Query",b.errorMessage),
-b.errorMessage&&(null!==b.errorMessage.match(/\d+:\d+/g)?d.markPositionError(b.errorMessage.match(/'.*'/g)[0],b.errorMessage.match(/\d+:\d+/g)[0]):d.markPositionError(b.errorMessage.match(/\(\w+\)/g)[0]),d.removeOutputEditor(c))}catch(e){if(d.removeOutputEditor(c),409===b.code)return;400!==b.code&&404!==b.code&&arangoHelper.arangoNotification("Query","Successfully aborted.")}window.progressView.hide()}})};h()},analyseQuery:function(a){var b={defaultType:null,original:a,modified:null},c=!1;if(a[0])if(a[0].vertices&&a[0].edges){var d=0,e=0;_.each(a,function(a){a.edges&&(e+=a.edges.length,_.each(a.edges,function(a){a._from&&a._to&&d++}))});var f=d/e*100;f>=95&&(c=!0,b.defaultType="graph",b.graphInfo="object")}else{var g=0,h=a.length;_.each(a,function(a){a._from&&a._to&&g++});var i=g/h*100;i>=95&&(c=!0,b.defaultType="graph",b.graphInfo="array")}if(!c){var j,k=0,l=!0,m={};if(a.length<=1&&(l=!1),l){_.each(a,function(a){j=_.keys(a).length,j>k&&(k=j),_.each(a,function(a,b){m[b]?m[b]=m[b]+1:m[b]=1})});var n;_.each(m,function(b,c){n=b/a.length*100,l!==!1&&95>=n&&(l=!1)})}l&&(c=!0,b.defaultType="table")}return c||(b.defaultType="json"),b},markPositionError:function(a,b){var c;b&&(c=b.split(":")[0],a=a.substr(1,a.length-2));var d=this.aqlEditor.find(a);!d&&b&&(this.aqlEditor.selection.moveCursorToPosition({row:c,column:0}),this.aqlEditor.selection.selectLine()),window.setTimeout(function(){$(".ace_start").first().css("background","rgba(255, 129, 129, 0.7)")},100)},refreshAQL:function(){var a=this,b=function(b){b?arangoHelper.arangoError("Query","Could not reload Queries"):(a.updateLocalQueries(),a.updateQueryTable())},c=function(){a.getSystemQueries(b)};this.getAQL(c)},getSystemQueries:function(a){var b=this;$.ajax({type:"GET",cache:!1,url:"js/arango/aqltemplates.json",contentType:"application/json",processData:!1,success:function(c){a&&a(!1),b.queries=c},error:function(){a&&a(!0),arangoHelper.arangoNotification("Query","Error while loading system templates")}})},updateLocalQueries:function(){var a=this;this.customQueries=[],this.collection.each(function(b){a.customQueries.push({name:b.get("name"),value:b.get("value"),parameter:b.get("parameter")})})},renderOutputTable:function(a,b){var c={id:"outputTableData"+b,titles:[],rows:[]},d=!0,e=[];_.each(a.original,function(a){d===!0&&(c.titles=Object.keys(a),d=!1),_.each(a,function(a){"object"==typeof a&&(a=JSON.stringify(a)),e.push(a)}),c.rows.push(e),e=[]}),$("#outputTable"+b).append(this.table.render({content:c}))},renderOutputGraph:function(a,b){this.graphViewer2=new window.GraphViewer2({name:void 0,documentStore:window.App.arangoDocumentStore,collection:new window.GraphCollection,userConfig:window.App.userConfig,id:"#outputGraph"+b,data:a}),this.graphViewer2.renderAQL()},getAQL:function(a){var b=this;this.collection.fetch({success:function(){var c=localStorage.getItem("customQueries");if(c){var d=JSON.parse(c);_.each(d,function(a){b.collection.add({value:a.value,name:a.name})});var e=function(a){a?arangoHelper.arangoError("Custom Queries","Could not import old local storage queries"):localStorage.removeItem("customQueries")};b.collection.saveCollectionQueries(e)}b.updateLocalQueries(),a&&a()}})}})}(),function(){"use strict";window.ScaleView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("scaleView.ejs"),interval:1e4,knownServers:[],events:{"click #addCoord":"addCoord","click #removeCoord":"removeCoord","click #addDBs":"addDBs","click #removeDBs":"removeDBs"},setCoordSize:function(a){var b=this,c={numberOfCoordinators:a};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(c),success:function(){b.updateTable(c)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},setDBsSize:function(a){var b=this,c={numberOfDBServers:a};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(c),success:function(){b.updateTable(c)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},addCoord:function(){this.setCoordSize(this.readNumberFromID("#plannedCoords",!0))},removeCoord:function(){this.setCoordSize(this.readNumberFromID("#plannedCoords",!1,!0))},addDBs:function(){this.setDBsSize(this.readNumberFromID("#plannedDBs",!0))},removeDBs:function(){this.setDBsSize(this.readNumberFromID("#plannedDBs",!1,!0))},readNumberFromID:function(a,b,c){var d=$(a).html(),e=!1;try{e=JSON.parse(d)}catch(f){}return b&&e++,c&&1!==e&&e--,e},initialize:function(a){var b=this;clearInterval(this.intervalFunction),window.App.isCluster&&(this.dbServers=a.dbServers,this.coordinators=a.coordinators,this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#sNodes"===window.location.hash&&b.coordinators.fetch({success:function(){b.dbServers.fetch({success:function(){b.continueRender(!0)}})}})},this.interval))},render:function(){var a=this,b=function(){var b=function(){a.continueRender()};this.waitForDBServers(b)}.bind(this);this.initDoneCoords?b():this.waitForCoordinators(b),window.arangoHelper.buildNodesSubNav("scale")},continueRender:function(a){var b,c,d=this;b=this.coordinators.toJSON(),c=this.dbServers.toJSON(),this.$el.html(this.template.render({runningCoords:b.length,runningDBs:c.length,plannedCoords:void 0,plannedDBs:void 0,initialized:a})),$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",processData:!1,success:function(a){d.updateTable(a)}})},updateTable:function(a){var b='scaling in progress ',c='no scaling process active';a.numberOfCoordinators&&($("#plannedCoords").html(a.numberOfCoordinators),this.coordinators.toJSON().length===a.numberOfCoordinators?$("#statusCoords").html(c):$("#statusCoords").html(b)),a.numberOfDBServers&&($("#plannedDBs").html(a.numberOfDBServers),this.dbServers.toJSON().length===a.numberOfDBServers?$("#statusDBs").html(c):$("#statusDBs").html(b))},waitForDBServers:function(a){var b=this;0===this.dbServers.length?window.setInterval(function(){b.waitForDBServers(a)},300):a()},waitForCoordinators:function(a){var b=this;window.setTimeout(function(){0===b.coordinators.length?b.waitForCoordinators(a):(b.initDoneCoords=!0,a())},200)},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.SettingsView=Backbone.View.extend({el:"#content",initialize:function(a){this.collectionName=a.collectionName,this.model=this.collection},events:{},render:function(){this.breadcrumb(),window.arangoHelper.buildCollectionSubNav(this.collectionName,"Settings"),this.renderSettings()},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},unloadCollection:function(){var a=function(a){a?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be unloaded."):void 0===a?(this.model.set("status","unloading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","unloaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" unloaded.")}.bind(this);this.model.unloadCollection(a),window.modalView.hide()},loadCollection:function(){var a=function(a){a?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be loaded."):void 0===a?(this.model.set("status","loading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","loaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" loaded.")}.bind(this);this.model.loadCollection(a),window.modalView.hide()},truncateCollection:function(){this.model.truncateCollection(),window.modalView.hide()},deleteCollection:function(){this.model.destroy({error:function(){arangoHelper.arangoError("Could not delete collection.")},success:function(){window.App.navigate("#collections",{trigger:!0})}})},saveModifiedCollection:function(){var a=function(a,b){if(a)arangoHelper.arangoError("Error","Could not get coordinator info");else{var c;c=b?this.model.get("name"):$("#change-collection-name").val();var d=this.model.get("status");if("loaded"===d){var e;try{e=JSON.parse(1024*$("#change-collection-size").val()*1024)}catch(f){return arangoHelper.arangoError("Please enter a valid number"),0}var g;try{if(g=JSON.parse($("#change-index-buckets").val()),1>g||parseInt(g,10)!==Math.pow(2,Math.log2(g)))throw new Error("invalid indexBuckets value")}catch(f){return arangoHelper.arangoError("Please enter a valid number of index buckets"),0}var h=function(a){a?arangoHelper.arangoError("Collection error: "+a.responseText):(arangoHelper.arangoNotification("Collection: Successfully changed."),window.App.navigate("#cSettings/"+c,{trigger:!0}))},i=function(a){if(a)arangoHelper.arangoError("Collection error: "+a.responseText);else{var b=$("#change-collection-sync").val();this.model.changeCollection(b,e,g,h)}}.bind(this);frontendConfig.isCluster===!1?this.model.renameCollection(c,i):i()}else if("unloaded"===d)if(this.model.get("name")!==c){var j=function(a,b){a?arangoHelper.arangoError("Collection"+b.responseText):(arangoHelper.arangoNotification("CollectionSuccessfully changed."),window.App.navigate("#cSettings/"+c,{trigger:!0}))};frontendConfig.isCluster===!1?this.model.renameCollection(c,j):j()}else window.modalView.hide()}}.bind(this);window.isCoordinator(a)},renderSettings:function(){var a=function(a,b){if(a)arangoHelper.arangoError("Error","Could not get coordinator info");else{var c=!1;"loaded"===this.model.get("status")&&(c=!0);var d=[],e=[];b||e.push(window.modalView.createTextEntry("change-collection-name","Name",this.model.get("name"),!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}]));var f=function(){e.push(window.modalView.createReadOnlyEntry("change-collection-id","ID",this.model.get("id"),"")),e.push(window.modalView.createReadOnlyEntry("change-collection-type","Type",this.model.get("type"),"")),e.push(window.modalView.createReadOnlyEntry("change-collection-status","Status",this.model.get("status"),"")),d.push(window.modalView.createDeleteButton("Delete",this.deleteCollection.bind(this))),d.push(window.modalView.createDeleteButton("Truncate",this.truncateCollection.bind(this))),c?d.push(window.modalView.createNotificationButton("Unload",this.unloadCollection.bind(this))):d.push(window.modalView.createNotificationButton("Load",this.loadCollection.bind(this))),d.push(window.modalView.createSuccessButton("Save",this.saveModifiedCollection.bind(this)));var a=["General","Indices"],b=["modalTable.ejs","indicesView.ejs"];window.modalView.show(b,"Modify Collection",d,e,null,null,this.events,null,a,"content"),$($("#infoTab").children()[1]).remove()}.bind(this);if(c){var g=function(a,b){if(a)arangoHelper.arangoError("Collection","Could not fetch properties");else{var c=b.journalSize/1048576,d=b.indexBuckets,g=b.waitForSync;e.push(window.modalView.createTextEntry("change-collection-size","Journal size",c,"The maximal size of a journal or datafile (in MB). Must be at least 1.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),e.push(window.modalView.createTextEntry("change-index-buckets","Index buckets",d,"The number of index buckets for this collection. Must be at least 1 and a power of 2.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[1-9][0-9]*$/),msg:"Must be a number greater than 1 and a power of 2."}])),e.push(window.modalView.createSelectEntry("change-collection-sync","Wait for sync",g,"Synchronize to disk before returning from a create or update of a document.",[{value:!1,label:"No"},{value:!0,label:"Yes"}]))}f()};this.model.getProperties(g)}else f()}}.bind(this);window.isCoordinator(a)}})}(),function(){"use strict";window.ShardsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("shardsView.ejs"),interval:1e4,knownServers:[],events:{"click #shardsContent .shardLeader span":"moveShard","click #shardsContent .shardFollowers span":"moveShardFollowers","click #rebalanceShards":"rebalanceShards"},initialize:function(a){var b=this;b.dbServers=a.dbServers,clearInterval(this.intervalFunction),window.App.isCluster&&(this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#shards"===window.location.hash&&b.render(!1)},this.interval))},render:function(a){var b=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/shardDistribution"),contentType:"application/json",processData:!1,async:!0,success:function(a){var c,d=!1;b.shardDistribution=a.results,_.each(a.results,function(a,b){c=b.substring(0,1),"_"!==c&&"error"!==b&&"code"!==b&&(d=!0)}),d?b.continueRender(a.results):arangoHelper.renderEmpty("No collections and no shards available")},error:function(a){0!==a.readyState&&arangoHelper.arangoError("Cluster","Could not fetch sharding information.")}}),a!==!1&&arangoHelper.buildNodesSubNav("Shards")},moveShardFollowers:function(a){var b=$(a.currentTarget).html();this.moveShard(a,b)},moveShard:function(a,b){var c,d,e,f,g=this,h=window.App.currentDB.get("name");d=$(a.currentTarget).parent().parent().attr("collection"),e=$(a.currentTarget).parent().parent().attr("shard"),b?(f=$(a.currentTarget).parent().parent().attr("leader"),c=b):c=$(a.currentTarget).parent().parent().attr("leader");var i=[],j=[],k={},l=[];return g.dbServers[0].each(function(a){a.get("name")!==c&&(k[a.get("name")]={value:a.get("name"),label:a.get("name")})}),_.each(g.shardDistribution[d].Plan[e].followers,function(a){delete k[a]}),b&&delete k[f],_.each(k,function(a){l.push(a)}),l=l.reverse(),0===l.length?void arangoHelper.arangoMessage("Shards","No database server for moving the shard is available."):(j.push(window.modalView.createSelectEntry("toDBServer","Destination",void 0,"Please select the target databse server. The selected database server will be the new leader of the shard.",l)),i.push(window.modalView.createSuccessButton("Move",this.confirmMoveShards.bind(this,h,d,e,c))),void window.modalView.show("modalTable.ejs","Move shard: "+e,i,j))},confirmMoveShards:function(a,b,c,d){var e=this,f=$("#toDBServer").val(),g={database:a,collection:b,shard:c,fromServer:d,toServer:f};$.ajax({type:"POST",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/moveShard"),contentType:"application/json",processData:!1,data:JSON.stringify(g),async:!0,success:function(a){a===!0&&(window.setTimeout(function(){e.render(!1)},1500),arangoHelper.arangoNotification("Shard "+c+" will be moved to "+f+"."))},error:function(){arangoHelper.arangoNotification("Shard "+c+" could not be moved to "+f+".")}}),window.modalView.hide()},rebalanceShards:function(){var a=this;$.ajax({type:"POST",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/rebalanceShards"),contentType:"application/json",processData:!1,data:JSON.stringify({}),async:!0,success:function(b){b===!0&&(window.setTimeout(function(){a.render(!1)},1500),arangoHelper.arangoNotification("Started rebalance process."))},error:function(){arangoHelper.arangoNotification("Could not start rebalance process.")}}),window.modalView.hide()},continueRender:function(a){delete a.code,delete a.error,this.$el.html(this.template.render({collections:a}))},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.ShowClusterView=Backbone.View.extend({detailEl:"#modalPlaceholder",el:"#content",defaultFrame:12e5,template:templateEngine.createTemplate("showCluster.ejs"),modal:templateEngine.createTemplate("waitModal.ejs"),detailTemplate:templateEngine.createTemplate("detailView.ejs"),events:{"change #selectDB":"updateCollections","change #selectCol":"updateShards","click .dbserver.success":"dashboard","click .coordinator.success":"dashboard"},replaceSVGs:function(){$(".svgToReplace").each(function(){var a=$(this),b=a.attr("id"),c=a.attr("src");$.get(c,function(c){var d=$(c).find("svg");d.attr("id",b).attr("class","icon").removeAttr("xmlns:a"),a.replaceWith(d)},"xml")})},updateServerTime:function(){this.serverTime=(new Date).getTime()},setShowAll:function(){this.graphShowAll=!0},resetShowAll:function(){this.graphShowAll=!1,this.renderLineChart()},initialize:function(a){this.options=a,this.interval=1e4,this.isUpdating=!1,this.timer=null,this.knownServers=[],this.graph=void 0,this.graphShowAll=!1,this.updateServerTime(),this.dygraphConfig=this.options.dygraphConfig,this.dbservers=new window.ClusterServers([],{interval:this.interval}),this.coordinators=new window.ClusterCoordinators([],{interval:this.interval}),this.documentStore=new window.ArangoDocuments,this.statisticsDescription=new window.StatisticsDescription,this.statisticsDescription.fetch({async:!1}),this.dbs=new window.ClusterDatabases([],{interval:this.interval}),this.cols=new window.ClusterCollections,this.shards=new window.ClusterShards,this.startUpdating()},listByAddress:function(a){var b={},c=this;this.dbservers.byAddress(b,function(b){c.coordinators.byAddress(b,a)})},updateCollections:function(){var a=this,b=$("#selectCol"),c=$("#selectDB").find(":selected").attr("id");if(c){var d=b.find(":selected").attr("id");b.html(""),this.cols.getList(c,function(c){_.each(_.pluck(c,"name"),function(a){b.append('")});var e=$("#"+d,b);1===e.length&&e.prop("selected",!0),a.updateShards()})}},updateShards:function(){var a=$("#selectDB").find(":selected").attr("id"),b=$("#selectCol").find(":selected").attr("id");this.shards.getList(a,b,function(a){$(".shardCounter").html("0"),_.each(a,function(a){$("#"+a.server+"Shards").html(a.shards.length)})})},updateServerStatus:function(a){var b=this,c=function(a,b,c){var d,e,f=c;f=f.replace(/\./g,"-"),f=f.replace(/\:/g,"_"),e=$("#id"+f),e.length<1||(d=e.attr("class").split(/\s+/)[1],e.attr("class",a+" "+d+" "+b),"coordinator"===a&&("success"===b?$(".button-gui",e.closest(".tile")).toggleClass("button-gui-disabled",!1):$(".button-gui",e.closest(".tile")).toggleClass("button-gui-disabled",!0)))};this.coordinators.getStatuses(c.bind(this,"coordinator"),function(){b.dbservers.getStatuses(c.bind(b,"dbserver")),a()})},updateDBDetailList:function(){var a=this,b=$("#selectDB"),c=b.find(":selected").attr("id");b.html(""),this.dbs.getList(function(d){_.each(_.pluck(d,"name"),function(a){b.append('")});var e=$("#"+c,b);1===e.length&&e.prop("selected",!0),a.updateCollections()})},rerender:function(){var a=this;this.updateServerStatus(function(){a.getServerStatistics(function(){a.updateServerTime(),a.data=a.generatePieData(),a.renderPieChart(a.data),a.renderLineChart(),a.updateDBDetailList()})})},render:function(){this.knownServers=[],delete this.hist;var a=this;this.listByAddress(function(b){1===Object.keys(b).length?a.type="testPlan":a.type="other",a.updateDBDetailList(),a.dbs.getList(function(c){$(a.el).html(a.template.render({dbs:_.pluck(c,"name"),byAddress:b,type:a.type})),$(a.el).append(a.modal.render({})),a.replaceSVGs(),a.getServerStatistics(function(){a.data=a.generatePieData(),a.renderPieChart(a.data),a.renderLineChart(),a.updateDBDetailList(),a.startUpdating()})})})},generatePieData:function(){var a=[],b=this;return this.data.forEach(function(c){a.push({key:c.get("name"),value:c.get("system").virtualSize,time:b.serverTime})}),a},addStatisticsItem:function(a,b,c,d){var e=this;e.hasOwnProperty("hist")||(e.hist={}),e.hist.hasOwnProperty(a)||(e.hist[a]=[]);var f=e.hist[a],g=f.length;if(0===g)f.push({time:b,snap:d,requests:c,requestsPerSecond:0});else{var h=f[g-1].time,i=f[g-1].requests;if(c>i){var j=b-h,k=0;j>0&&(k=(c-i)/j),f.push({time:b,snap:d,requests:c,requestsPerSecond:k})}}},getServerStatistics:function(a){var b=this,c=Math.round(b.serverTime/1e3);this.data=void 0;var d=new window.ClusterStatisticsCollection,e=this.coordinators.first();this.dbservers.forEach(function(a){if("ok"===a.get("status")){-1===b.knownServers.indexOf(a.id)&&b.knownServers.push(a.id);var c=new window.Statistics({name:a.id});c.url=e.get("protocol")+"://"+e.get("address")+"/_admin/clusterStatistics?DBserver="+a.get("name"),d.add(c)}}),this.coordinators.forEach(function(a){if("ok"===a.get("status")){-1===b.knownServers.indexOf(a.id)&&b.knownServers.push(a.id);var c=new window.Statistics({name:a.id});c.url=a.get("protocol")+"://"+a.get("address")+"/_admin/statistics",d.add(c)}});var f=d.size();this.data=[];var g=function(d){f--;var e=d.get("time"),g=d.get("name"),h=d.get("http").requestsTotal;b.addStatisticsItem(g,e,h,c),b.data.push(d),0===f&&a()},h=function(){f--,0===f&&a()};d.fetch(g,h)},renderPieChart:function(a){var b=$("#clusterGraphs svg").width(),c=$("#clusterGraphs svg").height(),d=Math.min(b,c)/2,e=this.dygraphConfig.colors,f=d3.svg.arc().outerRadius(d-20).innerRadius(0),g=d3.layout.pie().sort(function(a){return a.value}).value(function(a){return a.value});d3.select("#clusterGraphs").select("svg").remove();var h=d3.select("#clusterGraphs").append("svg").attr("class","clusterChart").append("g").attr("transform","translate("+b/2+","+(c/2-10)+")"),i=d3.svg.arc().outerRadius(d-2).innerRadius(d-2),j=h.selectAll(".arc").data(g(a)).enter().append("g").attr("class","slice");j.append("path").attr("d",f).style("fill",function(a,b){return e[b%e.length]}).style("stroke",function(a,b){return e[b%e.length]}),j.append("text").attr("transform",function(a){return"translate("+f.centroid(a)+")"}).style("text-anchor","middle").text(function(a){var b=a.data.value/1024/1024/1024;return b.toFixed(2)}),j.append("text").attr("transform",function(a){return"translate("+i.centroid(a)+")"}).style("text-anchor","middle").text(function(a){return a.data.key})},renderLineChart:function(){var a,b,c,d,e,f,g=this,h=1200,i=[],j=[],k=Math.round((new Date).getTime()/1e3)-h,l=g.knownServers,m=function(){return null};for(c=0;cf||(j.hasOwnProperty(f)?a=j[f]:(e=new Date(1e3*f),a=j[f]=[e].concat(l.map(m))),a[c+1]=b[d].requestsPerSecond);i=[],Object.keys(j).sort().forEach(function(a){i.push(j[a])});var n=this.dygraphConfig.getDefaultConfig("clusterRequestsPerSecond");n.labelsDiv=$("#lineGraphLegend")[0],n.labels=["datetime"].concat(l),g.graph=new Dygraph(document.getElementById("lineGraph"),i,n)},stopUpdating:function(){window.clearTimeout(this.timer),delete this.graph,this.isUpdating=!1},startUpdating:function(){if(!this.isUpdating){this.isUpdating=!0;var a=this;this.timer=window.setInterval(function(){a.rerender()},this.interval)}},dashboard:function(a){this.stopUpdating();var b,c,d=$(a.currentTarget),e={},f=d.attr("id");f=f.replace(/\-/g,"."),f=f.replace(/\_/g,":"),f=f.substr(2),e.raw=f,e.isDBServer=d.hasClass("dbserver"),e.isDBServer?(b=this.dbservers.findWhere({address:e.raw}),c=this.coordinators.findWhere({status:"ok"}),e.endpoint=c.get("protocol")+"://"+c.get("address")):(b=this.coordinators.findWhere({address:e.raw}),e.endpoint=b.get("protocol")+"://"+b.get("address")),e.target=encodeURIComponent(b.get("name")),window.App.serverToShow=e,window.App.dashboard()},getCurrentSize:function(a){"#"!==a.substr(0,1)&&(a="#"+a);var b,c;return $(a).attr("style",""),b=$(a).height(),c=$(a).width(),{height:b,width:c}},resize:function(){var a;this.graph&&(a=this.getCurrentSize(this.graph.maindiv_.id),this.graph.resize(a.width,a.height))}})}(),function(){"use strict";window.SpotlightView=Backbone.View.extend({template:templateEngine.createTemplate("spotlightView.ejs"),el:"#spotlightPlaceholder",displayLimit:8,typeahead:null,callbackSuccess:null,callbackCancel:null,collections:{system:[],doc:[],edge:[]},events:{"focusout #spotlight .tt-input":"hide","keyup #spotlight .typeahead":"listenKey"},aqlKeywordsArray:[],aqlBuiltinFunctionsArray:[],aqlKeywords:"for|return|filter|sort|limit|let|collect|asc|desc|in|into|insert|update|remove|replace|upsert|options|with|and|or|not|distinct|graph|outbound|inbound|any|all|none|aggregate|like|count|shortest_path",hide:function(){this.typeahead=$("#spotlight .typeahead").typeahead("destroy"),$(this.el).hide()},listenKey:function(a){if(27===a.keyCode)this.callbackSuccess&&this.callbackCancel(),this.hide();else if(13===a.keyCode&&this.callbackSuccess){var b=$(this.typeahead).val();this.callbackSuccess(b),this.hide()}},substringMatcher:function(a){return function(b,c){var d,e;d=[],e=new RegExp(b,"i"),_.each(a,function(a){e.test(a)&&d.push(a)}),c(d)}},updateDatasets:function(){var a=this;this.collections={system:[],doc:[],edge:[]},window.App.arangoCollectionsStore.each(function(b){b.get("isSystem")?a.collections.system.push(b.get("name")):"document"===b.get("type")?a.collections.doc.push(b.get("name")):a.collections.edge.push(b.get("name"))})},stringToArray:function(){var a=this;_.each(this.aqlKeywords.split("|"),function(b){a.aqlKeywordsArray.push(b.toUpperCase())}),a.aqlKeywordsArray.push(!0),a.aqlKeywordsArray.push(!1),a.aqlKeywordsArray.push(null)},fetchKeywords:function(a){var b=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/aql-builtin"),contentType:"application/json",success:function(c){b.stringToArray(),b.updateDatasets(),_.each(c.functions,function(a){b.aqlBuiltinFunctionsArray.push(a.name)}),a&&a()},error:function(){a&&a(),arangoHelper.arangoError("AQL","Could not fetch AQL function definition.")}})},show:function(a,b,c){var d=this;this.callbackSuccess=a,this.callbackCancel=b;var e=function(){var a=function(a,b,c){var d='
"),$("#subNavigationBar .breadcrumb").html(a)},openApp:function(){var a=function(a,b){a?arangoHelper.arangoError("DB","Could not get current database"):window.open(this.appUrl(b),this.model.get("title")).focus()}.bind(this);arangoHelper.currentDatabase(a)},deleteApp:function(){var a=[window.modalView.createDeleteButton("Delete",function(){var a={teardown:$("#app_delete_run_teardown").is(":checked")};this.model.destroy(a,function(a,b){a||b.error!==!1||(window.modalView.hide(),window.App.navigate("services",{trigger:!0}))})}.bind(this))],b=[window.modalView.createCheckboxEntry("app_delete_run_teardown","Run teardown?",!0,"Should this app's teardown script be executed before removing the app?",!0)];window.modalView.show("modalTable.ejs",'Delete Foxx App mounted at "'+this.model.get("mount")+'"',a,b,void 0,"
Are you sure? There is no way back...
",!0)},appUrl:function(a){return arangoHelper.databaseUrl(this.model.get("mount"),a)},applyConfig:function(){var a={};_.each(this.model.get("config"),function(b,c){var d=$("#app_config_"+c),e=d.val();if("boolean"===b.type||"bool"===b.type)return void(a[c]=d.is(":checked"));if(""===e&&b.hasOwnProperty("default"))return a[c]=b["default"],void("json"===b.type&&(a[c]=JSON.stringify(b["default"])));if("number"===b.type)a[c]=parseFloat(e);else if("integer"===b.type||"int"===b.type)a[c]=parseInt(e,10);else{if("json"!==b.type)return void(a[c]=window.arangoHelper.escapeHtml(e));a[c]=e&&JSON.stringify(JSON.parse(e))}}),this.model.setConfiguration(a,function(){this.updateConfig(),arangoHelper.arangoNotification(this.model.get("name"),"Settings applied.")}.bind(this))},showConfigDialog:function(){if(_.isEmpty(this.model.get("config")))return void $("#settings .buttons").html($("#hidden_buttons").html());var a=_.map(this.model.get("config"),function(a,b){var c=void 0===a["default"]?"":String(a["default"]),d=void 0===a.current?"":String(a.current),e="createTextEntry",f=!1,g=[];return"boolean"===a.type||"bool"===a.type?(e="createCheckboxEntry",a["default"]=a["default"]||!1,c=a["default"]||!1,d=a.current||!1):"json"===a.type?(e="createBlobEntry",c=void 0===a["default"]?"":JSON.stringify(a["default"]),d=void 0===a.current?"":a.current,g.push({rule:function(a){return a&&JSON.parse(a)},msg:"Must be well-formed JSON or empty."})):"integer"===a.type||"int"===a.type?g.push({rule:Joi.number().integer().optional().allow(""),msg:"Has to be an integer."}):"number"===a.type?g.push({rule:Joi.number().optional().allow(""),msg:"Has to be a number."}):("password"===a.type&&(e="createPasswordEntry"),g.push({rule:Joi.string().optional().allow(""),msg:"Has to be a string."})),void 0===a["default"]&&a.required!==!1&&(f=!0,g.unshift({rule:Joi.any().required(),msg:"This field is required."})),window.modalView[e]("app_config_"+b,b,d,a.description,c,f,g)}),b=[window.modalView.createSuccessButton("Apply",this.applyConfig.bind(this))];window.modalView.show("modalTable.ejs","Configuration",b,a,null,null,null,null,null,"settings"),$(".modal-footer").prepend($("#hidden_buttons").html())},applyDeps:function(){var a={};_.each(this.model.get("deps"),function(b,c){var d=$("#app_deps_"+c);a[c]=window.arangoHelper.escapeHtml(d.val())}),this.model.setDependencies(a,function(){window.modalView.hide(),this.updateDeps()}.bind(this))},showDepsDialog:function(){if(!_.isEmpty(this.model.get("deps"))){var a=_.map(this.model.get("deps"),function(a,b){var c=void 0===a.current?"":String(a.current),d="",e=a.definition.name;"*"!==a.definition.version&&(e+="@"+a.definition.version);var f=[{rule:Joi.string().optional().allow(""),msg:"Has to be a string."}];return a.definition.required&&f.push({rule:Joi.string().required(),msg:"This value is required."}),window.modalView.createTextEntry("app_deps_"+b,a.title,c,e,d,a.definition.required,f)}),b=[window.modalView.createSuccessButton("Apply",this.applyDeps.bind(this))];window.modalView.show("modalTable.ejs","Dependencies",b,a)}},showDropdown:function(){_.isEmpty(this.model.get("scripts"))||$("#scripts_dropdown").show(200)},hideDropdown:function(){$("#scripts_dropdown").hide()}})}(),function(){"use strict";window.ApplicationsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("applicationsView.ejs"),events:{"click #addApp":"createInstallModal","click #foxxToggle":"slideToggle","click #checkDevel":"toggleDevel","click #checkProduction":"toggleProduction","click #checkSystem":"toggleSystem"},fixCheckboxes:function(){this._showDevel?$("#checkDevel").attr("checked","checked"):$("#checkDevel").removeAttr("checked"),this._showSystem?$("#checkSystem").attr("checked","checked"):$("#checkSystem").removeAttr("checked"),this._showProd?$("#checkProduction").attr("checked","checked"):$("#checkProduction").removeAttr("checked"),$("#checkDevel").next().removeClass("fa fa-check-square-o fa-square-o").addClass("fa"),$("#checkSystem").next().removeClass("fa fa-check-square-o fa-square-o").addClass("fa"),$("#checkProduction").next().removeClass("fa fa-check-square-o fa-square-o").addClass("fa"),arangoHelper.setCheckboxStatus("#foxxDropdown")},toggleDevel:function(){var a=this;this._showDevel=!this._showDevel,_.each(this._installedSubViews,function(b){b.toggle("devel",a._showDevel)}),this.fixCheckboxes()},toggleProduction:function(){var a=this;this._showProd=!this._showProd,_.each(this._installedSubViews,function(b){b.toggle("production",a._showProd)}),this.fixCheckboxes()},toggleSystem:function(){this._showSystem=!this._showSystem;var a=this;_.each(this._installedSubViews,function(b){b.toggle("system",a._showSystem)}),this.fixCheckboxes()},reload:function(){var a=this;_.each(this._installedSubViews,function(a){a.undelegateEvents()}),this.collection.fetch({success:function(){a.createSubViews(),a.render()}})},createSubViews:function(){var a=this;this._installedSubViews={},a.collection.each(function(b){var c=new window.FoxxActiveView({model:b,appsView:a});a._installedSubViews[b.get("mount")]=c})},initialize:function(){this._installedSubViews={},this._showDevel=!0,this._showProd=!0,this._showSystem=!1},slideToggle:function(){$("#foxxToggle").toggleClass("activated"),$("#foxxDropdownOut").slideToggle(200)},createInstallModal:function(a){a.preventDefault(),window.foxxInstallView.install(this.reload.bind(this))},render:function(){this.collection.sort(),$(this.el).html(this.template.render({})),_.each(this._installedSubViews,function(a){$("#installedList").append(a.render())}),this.delegateEvents(),$("#checkDevel").attr("checked",this._showDevel),$("#checkProduction").attr("checked",this._showProd),$("#checkSystem").attr("checked",this._showSystem),arangoHelper.setCheckboxStatus("#foxxDropdown");var a=this;return _.each(this._installedSubViews,function(b){b.toggle("devel",a._showDevel),b.toggle("system",a._showSystem)}),arangoHelper.fixTooltips("icon_arangodb","left"),this}})}(),function(){"use strict";window.ClusterView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("clusterView.ejs"),events:{},statsEnabled:!1,historyInit:!1,initDone:!1,interval:5e3,maxValues:100,knownServers:[],chartData:{},charts:{},nvcharts:[],startHistory:{},startHistoryAccumulated:{},initialize:function(a){var b=this;window.App.isCluster&&(this.dbServers=a.dbServers,this.coordinators=a.coordinators,this.updateServerTime(),window.setInterval(function(){if("#cluster"===window.location.hash||""===window.location.hash||"#"===window.location.hash){var a=function(a){b.rerenderValues(a),b.rerenderGraphs(a)};b.getCoordStatHistory(a)}},this.interval))},render:function(){this.$el.html(this.template.render({})),this.initDone||(void 0!==this.coordinators.first()?this.getServerStatistics():this.waitForCoordinators(),this.initDone=!0),this.initGraphs()},waitForCoordinators:function(){var a=this;window.setTimeout(function(){a.coordinators?a.getServerStatistics():a.waitForCoordinators()},500)},updateServerTime:function(){this.serverTime=(new Date).getTime()},getServerStatistics:function(){var a=this;this.data=void 0;var b=this.coordinators.first();this.statCollectCoord=new window.ClusterStatisticsCollection([],{host:b.get("address")}),this.statCollectDBS=new window.ClusterStatisticsCollection([],{host:b.get("address")});var c=[];_.each(this.dbServers,function(a){a.each(function(a){c.push(a)})}),_.each(c,function(c){if("ok"===c.get("status")){-1===a.knownServers.indexOf(c.id)&&a.knownServers.push(c.id);var d=new window.Statistics({name:c.id});d.url=b.get("protocol")+"://"+b.get("address")+"/_admin/clusterStatistics?DBserver="+c.get("name"),a.statCollectDBS.add(d)}}),this.coordinators.forEach(function(b){if("ok"===b.get("status")){-1===a.knownServers.indexOf(b.id)&&a.knownServers.push(b.id);var c=new window.Statistics({name:b.id});c.url=b.get("protocol")+"://"+b.get("address")+"/_admin/statistics",a.statCollectCoord.add(c)}});var d=function(b){a.rerenderValues(b),a.rerenderGraphs(b)};a.getCoordStatHistory(d),a.renderNodes()},rerenderValues:function(a){var b=this;b.renderNodes(),this.renderValue("#clusterConnections",Math.round(a.clientConnectionsCurrent)),this.renderValue("#clusterConnectionsAvg",Math.round(a.clientConnections15M));var c=a.physicalMemory,d=a.residentSizeCurrent;this.renderValue("#clusterRam",[d,c])},renderValue:function(a,b,c,d){if("number"==typeof b)$(a).html(b);else if($.isArray(b)){var e=b[0],f=b[1],g=1/(f/e)*100;g>90?c=!0:g>70&&90>g&&(d=!0),$(a).html(g.toFixed(1)+" %")}else"string"==typeof b&&$(a).html(b);c?($(a).addClass("negative"),$(a).removeClass("warning"),$(a).removeClass("positive")):d?($(a).addClass("warning"),$(a).removeClass("positive"),$(a).removeClass("negative")):($(a).addClass("positive"),$(a).removeClass("negative"),$(a).removeClass("warning"))},renderNodes:function(){var a=this,b=function(a){var b=0,c=0,d=0,e=0;_.each(a,function(a){"Coordinator"===a.Role?(b++,"GOOD"!==a.Status&&c++):"DBServer"===a.Role&&(d++,"GOOD"!==a.Status&&e++)}),c>0?this.renderValue("#clusterCoordinators",b-c+"/"+b,!0):this.renderValue("#clusterCoordinators",b),e>0?this.renderValue("#clusterDBServers",d-e+"/"+d,!0):this.renderValue("#clusterDBServers",d)}.bind(this);$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,async:!0,success:function(a){b(a.Health)},error:function(){a.renderValue("#clusterCoordinators","N/A",!0),a.renderValue("#clusterDBServers","N/A",!0)}})},initValues:function(){var a=["#clusterNodes","#clusterRam","#clusterConnections","#clusterConnectionsAvg"];_.each(a,function(a){$(a).html('')})},graphData:{data:{sent:[],received:[]},http:[],average:[]},checkArraySizes:function(){var a=this;_.each(a.chartsOptions,function(b,c){_.each(b.options,function(b,d){b.values.length>a.maxValues-1&&a.chartsOptions[c].options[d].values.shift()})})},formatDataForGraph:function(a){var b=this;b.historyInit?(b.checkArraySizes(),b.chartsOptions[0].options[0].values.push({x:a.times[a.times.length-1],y:a.bytesSentPerSecond[a.bytesSentPerSecond.length-1]}),b.chartsOptions[0].options[1].values.push({x:a.times[a.times.length-1],y:a.bytesReceivedPerSecond[a.bytesReceivedPerSecond.length-1]}),b.chartsOptions[1].options[0].values.push({x:a.times[a.times.length-1],y:b.calcTotalHttp(a.http,a.bytesSentPerSecond.length-1)}),b.chartsOptions[2].options[0].values.push({x:a.times[a.times.length-1],y:a.avgRequestTime[a.bytesSentPerSecond.length-1]/b.coordinators.length})):(_.each(a.times,function(c,d){b.chartsOptions[0].options[0].values.push({x:c,y:a.bytesSentPerSecond[d]}),b.chartsOptions[0].options[1].values.push({x:c,y:a.bytesReceivedPerSecond[d]}),b.chartsOptions[1].options[0].values.push({x:c,y:b.calcTotalHttp(a.http,d)}),b.chartsOptions[2].options[0].values.push({x:c,y:a.avgRequestTime[d]/b.coordinators.length})}),b.historyInit=!0)},chartsOptions:[{id:"#clusterData",type:"bytes",count:2,options:[{area:!0,values:[],key:"Bytes out",color:"rgb(23,190,207)",strokeWidth:2,fillOpacity:.1},{area:!0,values:[],key:"Bytes in",color:"rgb(188, 189, 34)",strokeWidth:2,fillOpacity:.1}]},{id:"#clusterHttp",type:"bytes",options:[{area:!0,values:[],key:"Bytes",color:"rgb(0, 166, 90)",fillOpacity:.1}]},{id:"#clusterAverage",data:[],type:"seconds",options:[{area:!0,values:[],key:"Seconds",color:"rgb(243, 156, 18)",fillOpacity:.1}]}],initGraphs:function(){var a=this,b="No data...";_.each(a.chartsOptions,function(c){nv.addGraph(function(){a.charts[c.id]=nv.models.stackedAreaChart().options({useInteractiveGuideline:!0,showControls:!1,noData:b,duration:0}),a.charts[c.id].xAxis.axisLabel("").tickFormat(function(a){var b=new Date(1e3*a);return(b.getHours()<10?"0":"")+b.getHours()+":"+(b.getMinutes()<10?"0":"")+b.getMinutes()+":"+(b.getSeconds()<10?"0":"")+b.getSeconds()}).staggerLabels(!1),a.charts[c.id].yAxis.axisLabel("").tickFormat(function(a){var b;return"bytes"===c.type?null===a?"N/A":(b=parseFloat(d3.format(".2f")(a)),prettyBytes(b)):"seconds"===c.type?null===a?"N/A":b=parseFloat(d3.format(".3f")(a)):void 0});var d,e=a.returnGraphOptions(c.id);return e.length>0?_.each(e,function(a,b){c.options[b].values=a}):c.options[0].values=[],d=c.options,a.chartData[c.id]=d3.select(c.id).append("svg").datum(d).transition().duration(300).call(a.charts[c.id]).each("start",function(){window.setTimeout(function(){d3.selectAll(c.id+" *").each(function(){this.__transition__&&(this.__transition__.duration=0)})},0)}),nv.utils.windowResize(a.charts[c.id].update),a.nvcharts.push(a.charts[c.id]),a.charts[c.id]})})},returnGraphOptions:function(a){var b=[];return b="#clusterData"===a?[this.chartsOptions[0].options[0].values,this.chartsOptions[0].options[1].values]:"#clusterHttp"===a?[this.chartsOptions[1].options[0].values]:"#clusterAverage"===a?[this.chartsOptions[2].options[0].values]:[]},rerenderGraphs:function(a){if(this.statsEnabled){var b,c,d=this;this.formatDataForGraph(a),_.each(d.chartsOptions,function(a){c=d.returnGraphOptions(a.id),c.length>0?_.each(c,function(b,c){a.options[c].values=b}):a.options[0].values=[],b=a.options,b[0].values.length>0&&d.historyInit&&d.charts[a.id]&&d.charts[a.id].update()})}},calcTotalHttp:function(a,b){var c=0;return _.each(a,function(a){c+=a[b]}),c},getCoordStatHistory:function(a){$.ajax({url:"statistics/coordshort",json:!0}).success(function(b){this.statsEnabled=b.enabled,a(b.data)}.bind(this))}})}(),function(){"use strict";window.CollectionListItemView=Backbone.View.extend({tagName:"div",className:"tile pure-u-1-1 pure-u-sm-1-2 pure-u-md-1-3 pure-u-lg-1-4 pure-u-xl-1-6",template:templateEngine.createTemplate("collectionsItemView.ejs"),initialize:function(a){this.collectionsView=a.collectionsView},events:{"click .iconSet.icon_arangodb_settings2":"createEditPropertiesModal","click .pull-left":"noop","click .icon_arangodb_settings2":"editProperties","click .spanInfo":"showProperties",click:"selectCollection"},render:function(){return this.model.get("locked")?($(this.el).addClass("locked"),$(this.el).addClass(this.model.get("lockType"))):$(this.el).removeClass("locked"),"loading"!==this.model.get("status")&&"unloading"!==this.model.get("status")||$(this.el).addClass("locked"),$(this.el).html(this.template.render({model:this.model})),$(this.el).attr("id","collection_"+this.model.get("name")),this},editProperties:function(a){return this.model.get("locked")?0:(a.stopPropagation(),void this.createEditPropertiesModal())},showProperties:function(a){return this.model.get("locked")?0:(a.stopPropagation(),void this.createInfoModal())},selectCollection:function(a){return $(a.target).hasClass("disabled")?0:this.model.get("locked")?0:"loading"===this.model.get("status")?0:void("unloaded"===this.model.get("status")?this.loadCollection():window.App.navigate("collection/"+encodeURIComponent(this.model.get("name"))+"/documents/1",{trigger:!0}))},noop:function(a){a.stopPropagation()},unloadCollection:function(){var a=function(a){a?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be unloaded."):void 0===a?(this.model.set("status","unloading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","unloaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" unloaded.")}.bind(this);this.model.unloadCollection(a),window.modalView.hide()},loadCollection:function(){var a=function(a){a?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be loaded."):void 0===a?(this.model.set("status","loading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","loaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" loaded.")}.bind(this);this.model.loadCollection(a),window.modalView.hide()},truncateCollection:function(){this.model.truncateCollection(),window.modalView.hide()},deleteCollection:function(){this.model.destroy({error:function(){arangoHelper.arangoError("Could not delete collection.")},success:function(){window.modalView.hide()}}),this.collectionsView.render()},saveModifiedCollection:function(){var a=function(a,b){if(a)arangoHelper.arangoError("Error","Could not get coordinator info");else{var c;c=b?this.model.get("name"):$("#change-collection-name").val();var d=this.model.get("status");if("loaded"===d){var e;try{e=JSON.parse(1024*$("#change-collection-size").val()*1024)}catch(f){return arangoHelper.arangoError("Please enter a valid number"),0}var g;try{if(g=JSON.parse($("#change-index-buckets").val()),1>g||parseInt(g,10)!==Math.pow(2,Math.log2(g)))throw new Error("invalid indexBuckets value")}catch(f){return arangoHelper.arangoError("Please enter a valid number of index buckets"),0}var h=function(a){a?arangoHelper.arangoError("Collection error: "+a.responseText):(this.collectionsView.render(),window.modalView.hide())}.bind(this),i=function(a){if(a)arangoHelper.arangoError("Collection error: "+a.responseText);else{var b=$("#change-collection-sync").val();this.model.changeCollection(b,e,g,h)}}.bind(this);frontendConfig.isCluster===!1?this.model.renameCollection(c,i):i()}else if("unloaded"===d)if(this.model.get("name")!==c){var j=function(a,b){a?arangoHelper.arangoError("Collection error: "+b.responseText):(this.collectionsView.render(),window.modalView.hide())}.bind(this);frontendConfig.isCluster===!1?this.model.renameCollection(c,j):j()}else window.modalView.hide()}}.bind(this);window.isCoordinator(a)},createEditPropertiesModal:function(){var a=function(a,b){if(a)arangoHelper.arangoError("Error","Could not get coordinator info");else{var c=!1;"loaded"===this.model.get("status")&&(c=!0);var d=[],e=[];b||e.push(window.modalView.createTextEntry("change-collection-name","Name",this.model.get("name"),!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}]));var f=function(){e.push(window.modalView.createReadOnlyEntry("change-collection-id","ID",this.model.get("id"),"")),e.push(window.modalView.createReadOnlyEntry("change-collection-type","Type",this.model.get("type"),"")),e.push(window.modalView.createReadOnlyEntry("change-collection-status","Status",this.model.get("status"),"")),d.push(window.modalView.createDeleteButton("Delete",this.deleteCollection.bind(this))),d.push(window.modalView.createDeleteButton("Truncate",this.truncateCollection.bind(this))),c?d.push(window.modalView.createNotificationButton("Unload",this.unloadCollection.bind(this))):d.push(window.modalView.createNotificationButton("Load",this.loadCollection.bind(this))),d.push(window.modalView.createSuccessButton("Save",this.saveModifiedCollection.bind(this)));var a=["General","Indices"],b=["modalTable.ejs","indicesView.ejs"];window.modalView.show(b,"Modify Collection",d,e,null,null,this.events,null,a),
+"loaded"===this.model.get("status")?this.getIndex():$($("#infoTab").children()[1]).remove()}.bind(this);if(c){var g=function(a,b){if(a)arangoHelper.arangoError("Collection","Could not fetch properties");else{var c=b.journalSize/1048576,d=b.indexBuckets,g=b.waitForSync;e.push(window.modalView.createTextEntry("change-collection-size","Journal size",c,"The maximal size of a journal or datafile (in MB). Must be at least 1.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),e.push(window.modalView.createTextEntry("change-index-buckets","Index buckets",d,"The number of index buckets for this collection. Must be at least 1 and a power of 2.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[1-9][0-9]*$/),msg:"Must be a number greater than 1 and a power of 2."}])),e.push(window.modalView.createSelectEntry("change-collection-sync","Wait for sync",g,"Synchronize to disk before returning from a create or update of a document.",[{value:!1,label:"No"},{value:!0,label:"Yes"}]))}f()};this.model.getProperties(g)}else f()}}.bind(this);window.isCoordinator(a)},bindIndexEvents:function(){this.unbindIndexEvents();var a=this;$("#indexEditView #addIndex").bind("click",function(){a.toggleNewIndexView(),$("#cancelIndex").unbind("click"),$("#cancelIndex").bind("click",function(){a.toggleNewIndexView()}),$("#createIndex").unbind("click"),$("#createIndex").bind("click",function(){a.createIndex()})}),$("#newIndexType").bind("change",function(){a.selectIndexType()}),$(".deleteIndex").bind("click",function(b){a.prepDeleteIndex(b)}),$("#infoTab a").bind("click",function(a){if($("#indexDeleteModal").remove(),"Indices"!==$(a.currentTarget).html()||$(a.currentTarget).parent().hasClass("active")||($("#newIndexView").hide(),$("#indexEditView").show(),$("#modal-dialog .modal-footer .button-danger").hide(),$("#modal-dialog .modal-footer .button-success").hide(),$("#modal-dialog .modal-footer .button-notification").hide()),"General"===$(a.currentTarget).html()&&!$(a.currentTarget).parent().hasClass("active")){$("#modal-dialog .modal-footer .button-danger").show(),$("#modal-dialog .modal-footer .button-success").show(),$("#modal-dialog .modal-footer .button-notification").show();var b=$(".index-button-bar2")[0];$("#cancelIndex").is(":visible")&&($("#cancelIndex").detach().appendTo(b),$("#createIndex").detach().appendTo(b))}})},unbindIndexEvents:function(){$("#indexEditView #addIndex").unbind("click"),$("#newIndexType").unbind("change"),$("#infoTab a").unbind("click"),$(".deleteIndex").unbind("click")},createInfoModal:function(){var a=function(a,b,c){if(a)arangoHelper.arangoError("Figures","Could not get revision.");else{var d=[],e={figures:c,revision:b,model:this.model};window.modalView.show("modalCollectionInfo.ejs","Collection: "+this.model.get("name"),d,e)}}.bind(this),b=function(b,c){if(b)arangoHelper.arangoError("Figures","Could not get figures.");else{var d=c;this.model.getRevision(a,d)}}.bind(this);this.model.getFigures(b)},resetIndexForms:function(){$("#indexHeader input").val("").prop("checked",!1),$("#newIndexType").val("Geo").prop("selected",!0),this.selectIndexType()},createIndex:function(){var a,b,c,d=this,e=$("#newIndexType").val(),f={};switch(e){case"Geo":a=$("#newGeoFields").val();var g=d.checkboxToValue("#newGeoJson"),h=d.checkboxToValue("#newGeoConstraint"),i=d.checkboxToValue("#newGeoIgnoreNull");f={type:"geo",fields:d.stringToArray(a),geoJson:g,constraint:h,ignoreNull:i};break;case"Hash":a=$("#newHashFields").val(),b=d.checkboxToValue("#newHashUnique"),c=d.checkboxToValue("#newHashSparse"),f={type:"hash",fields:d.stringToArray(a),unique:b,sparse:c};break;case"Fulltext":a=$("#newFulltextFields").val();var j=parseInt($("#newFulltextMinLength").val(),10)||0;f={type:"fulltext",fields:d.stringToArray(a),minLength:j};break;case"Skiplist":a=$("#newSkiplistFields").val(),b=d.checkboxToValue("#newSkiplistUnique"),c=d.checkboxToValue("#newSkiplistSparse"),f={type:"skiplist",fields:d.stringToArray(a),unique:b,sparse:c}}var k=function(a,b){if(a)if(b){var c=JSON.parse(b.responseText);arangoHelper.arangoError("Document error",c.errorMessage)}else arangoHelper.arangoError("Document error","Could not create index.");d.refreshCollectionsView()};window.modalView.hide(),d.model.createIndex(f,k)},lastTarget:null,prepDeleteIndex:function(a){var b=this;this.lastTarget=a,this.lastId=$(this.lastTarget.currentTarget).parent().parent().first().children().first().text(),$("#modal-dialog .modal-footer").after('
")})}this.bindIndexEvents()},toggleNewIndexView:function(){var a=$(".index-button-bar2")[0];$("#indexEditView").is(":visible")?($("#indexEditView").hide(),$("#newIndexView").show(),$("#cancelIndex").detach().appendTo("#modal-dialog .modal-footer"),$("#createIndex").detach().appendTo("#modal-dialog .modal-footer")):($("#indexEditView").show(),$("#newIndexView").hide(),$("#cancelIndex").detach().appendTo(a),$("#createIndex").detach().appendTo(a)),arangoHelper.fixTooltips(".icon_arangodb, .arangoicon","right"),this.resetIndexForms()},stringToArray:function(a){var b=[];return a.split(",").forEach(function(a){a=a.replace(/(^\s+|\s+$)/g,""),""!==a&&b.push(a)}),b},checkboxToValue:function(a){return $(a).prop("checked")}})}(),function(){"use strict";window.CollectionsView=Backbone.View.extend({el:"#content",el2:"#collectionsThumbnailsIn",searchTimeout:null,refreshRate:1e4,template:templateEngine.createTemplate("collectionsView.ejs"),refetchCollections:function(){var a=this;this.collection.fetch({cache:!1,success:function(){a.checkLockedCollections()}})},checkLockedCollections:function(){var a=function(a,b){var c=this;a?console.log("Could not check locked collections"):(this.collection.each(function(a){a.set("locked",!1)}),_.each(b,function(a){var b=c.collection.findWhere({id:a.collection});b.set("locked",!0),b.set("lockType",a.type),b.set("desc",a.desc)}),this.collection.each(function(a){a.get("locked")||($("#collection_"+a.get("name")).find(".corneredBadge").removeClass("loaded unloaded"),$("#collection_"+a.get("name")+" .corneredBadge").text(a.get("status")),$("#collection_"+a.get("name")+" .corneredBadge").addClass(a.get("status"))),a.get("locked")||"loading"===a.get("status")?($("#collection_"+a.get("name")).addClass("locked"),a.get("locked")?($("#collection_"+a.get("name")).find(".corneredBadge").removeClass("loaded unloaded"),$("#collection_"+a.get("name")).find(".corneredBadge").addClass("inProgress"),$("#collection_"+a.get("name")+" .corneredBadge").text(a.get("desc"))):$("#collection_"+a.get("name")+" .corneredBadge").text(a.get("status"))):($("#collection_"+a.get("name")).removeClass("locked"),$("#collection_"+a.get("name")+" .corneredBadge").text(a.get("status")),$("#collection_"+a.get("name")+" .corneredBadge").hasClass("inProgress")&&($("#collection_"+a.get("name")+" .corneredBadge").text(a.get("status")),$("#collection_"+a.get("name")+" .corneredBadge").removeClass("inProgress"),$("#collection_"+a.get("name")+" .corneredBadge").addClass("loaded")),"unloaded"===a.get("status")&&$("#collection_"+a.get("name")+" .icon_arangodb_info").addClass("disabled"))}))}.bind(this);window.arangoHelper.syncAndReturnUninishedAardvarkJobs("index",a)},initialize:function(){var a=this;window.setInterval(function(){"#collections"===window.location.hash&&window.VISIBLE&&a.refetchCollections()},a.refreshRate)},render:function(){this.checkLockedCollections();var a=!1;$("#collectionsDropdown").is(":visible")&&(a=!0),$(this.el).html(this.template.render({})),this.setFilterValues(),a===!0&&$("#collectionsDropdown2").show();var b=this.collection.searchOptions;this.collection.getFiltered(b).forEach(function(a){$("#collectionsThumbnailsIn",this.el).append(new window.CollectionListItemView({model:a,collectionsView:this}).render().el)},this),"none"===$("#collectionsDropdown2").css("display")?$("#collectionsToggle").removeClass("activated"):$("#collectionsToggle").addClass("activated");var c;arangoHelper.setCheckboxStatus("#collectionsDropdown");try{c=b.searchPhrase.length}catch(d){}return $("#searchInput").val(b.searchPhrase),$("#searchInput").focus(),$("#searchInput")[0].setSelectionRange(c,c),arangoHelper.fixTooltips(".icon_arangodb, .arangoicon","left"),this},events:{"click #createCollection":"createCollection","keydown #searchInput":"restrictToSearchPhraseKey","change #searchInput":"restrictToSearchPhrase","click #searchSubmit":"restrictToSearchPhrase","click .checkSystemCollections":"checkSystem","click #checkLoaded":"checkLoaded","click #checkUnloaded":"checkUnloaded","click #checkDocument":"checkDocument","click #checkEdge":"checkEdge","click #sortName":"sortName","click #sortType":"sortType","click #sortOrder":"sortOrder","click #collectionsToggle":"toggleView","click .css-label":"checkBoxes"},updateCollectionsView:function(){var a=this;this.collection.fetch({cache:!1,success:function(){a.render()}})},toggleView:function(){$("#collectionsToggle").toggleClass("activated"),$("#collectionsDropdown2").slideToggle(200)},checkBoxes:function(a){var b=a.currentTarget.id;$("#"+b).click()},checkSystem:function(){var a=this.collection.searchOptions,b=a.includeSystem;a.includeSystem=$(".checkSystemCollections").is(":checked")===!0,b!==a.includeSystem&&this.render()},checkEdge:function(){var a=this.collection.searchOptions,b=a.includeEdge;a.includeEdge=$("#checkEdge").is(":checked")===!0,b!==a.includeEdge&&this.render()},checkDocument:function(){var a=this.collection.searchOptions,b=a.includeDocument;a.includeDocument=$("#checkDocument").is(":checked")===!0,b!==a.includeDocument&&this.render()},checkLoaded:function(){var a=this.collection.searchOptions,b=a.includeLoaded;a.includeLoaded=$("#checkLoaded").is(":checked")===!0,b!==a.includeLoaded&&this.render()},checkUnloaded:function(){var a=this.collection.searchOptions,b=a.includeUnloaded;a.includeUnloaded=$("#checkUnloaded").is(":checked")===!0,b!==a.includeUnloaded&&this.render()},sortName:function(){var a=this.collection.searchOptions,b=a.sortBy;a.sortBy=$("#sortName").is(":checked")===!0?"name":"type",b!==a.sortBy&&this.render()},sortType:function(){var a=this.collection.searchOptions,b=a.sortBy;a.sortBy=$("#sortType").is(":checked")===!0?"type":"name",b!==a.sortBy&&this.render()},sortOrder:function(){var a=this.collection.searchOptions,b=a.sortOrder;a.sortOrder=$("#sortOrder").is(":checked")===!0?-1:1,b!==a.sortOrder&&this.render()},setFilterValues:function(){var a=this.collection.searchOptions;$("#checkLoaded").attr("checked",a.includeLoaded),$("#checkUnloaded").attr("checked",a.includeUnloaded),$(".checkSystemCollections").attr("checked",a.includeSystem),$("#checkEdge").attr("checked",a.includeEdge),$("#checkDocument").attr("checked",a.includeDocument),$("#sortName").attr("checked","type"!==a.sortBy),$("#sortType").attr("checked","type"===a.sortBy),$("#sortOrder").attr("checked",1!==a.sortOrder)},search:function(){var a=this.collection.searchOptions,b=$("#searchInput").val();b!==a.searchPhrase&&(a.searchPhrase=b,this.render())},resetSearch:function(){this.searchTimeout&&(clearTimeout(this.searchTimeout),this.searchTimeout=null);var a=this.collection.searchOptions;a.searchPhrase=null},restrictToSearchPhraseKey:function(){var a=this;this.resetSearch(),a.searchTimeout=setTimeout(function(){a.search()},200)},restrictToSearchPhrase:function(){this.resetSearch(),this.search()},createCollection:function(a){a.preventDefault(),this.createNewCollectionModal()},submitCreateCollection:function(){var a=function(a,b){if(a)arangoHelper.arangoError("DB","Could not check coordinator state");else{var c=$("#new-collection-name").val(),d=$("#new-collection-size").val(),e=$("#new-replication-factor").val(),f=$("#new-collection-type").val(),g=$("#new-collection-sync").val(),h=1,i=[];if(""===e&&(e=1),b){if(h=$("#new-collection-shards").val(),""===h&&(h=1),h=parseInt(h,10),1>h)return arangoHelper.arangoError("Number of shards has to be an integer value greater or equal 1"),0;i=_.pluck($("#new-collection-shardBy").select2("data"),"text"),0===i.length&&i.push("_key")}if("_"===c.substr(0,1))return arangoHelper.arangoError('No "_" allowed as first character!'),0;var j=!1,k="true"===g;if(d>0)try{d=1024*JSON.parse(d)*1024}catch(l){return arangoHelper.arangoError("Please enter a valid number"),0}if(""===c)return arangoHelper.arangoError("No collection name entered!"),0;var m=function(a,b){if(a)try{b=JSON.parse(b.responseText),arangoHelper.arangoError("Error",b.errorMessage)}catch(c){}else this.updateCollectionsView();window.modalView.hide()}.bind(this);this.collection.newCollection({collName:c,wfs:k,isSystem:j,collSize:d,replicationFactor:e,collType:f,shards:h,shardBy:i},m)}}.bind(this);window.isCoordinator(a)},createNewCollectionModal:function(){var a=function(a,b){if(a)arangoHelper.arangoError("DB","Could not check coordinator state");else{var c=[],d=[],e={},f=[];d.push(window.modalView.createTextEntry("new-collection-name","Name","",!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only symbols, "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])),d.push(window.modalView.createSelectEntry("new-collection-type","Type","","The type of the collection to create.",[{value:2,label:"Document"},{value:3,label:"Edge"}])),b&&(d.push(window.modalView.createTextEntry("new-collection-shards","Shards","","The number of shards to create. You cannot change this afterwards. Recommended: DBServers squared","",!0)),d.push(window.modalView.createSelect2Entry("new-collection-shardBy","shardBy","","The keys used to distribute documents on shards. Type the key and press return to add it.","_key",!1))),c.push(window.modalView.createSuccessButton("Save",this.submitCreateCollection.bind(this))),f.push(window.modalView.createTextEntry("new-collection-size","Journal size","","The maximal size of a journal or datafile (in MB). Must be at least 1.","",!1,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),window.App.isCluster&&f.push(window.modalView.createTextEntry("new-replication-factor","Replication factor","","Numeric value. Must be at least 1. Description: TODO","",!1,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),f.push(window.modalView.createSelectEntry("new-collection-sync","Wait for sync","","Synchronize to disk before returning from a create or update of a document.",[{value:!1,label:"No"},{value:!0,label:"Yes"}])),e.header="Advanced",e.content=f,window.modalView.show("modalTable.ejs","New Collection",c,d,e),$("#s2id_new-collection-shardBy .select2-search-field input").on("focusout",function(a){$(".select2-drop").is(":visible")&&($("#select2-search-field input").is(":focus")||window.setTimeout(function(){$(a.currentTarget).parent().parent().parent().select2("close")},200))})}}.bind(this);window.isCoordinator(a)}})}(),function(){"use strict";function a(a,b){return void 0!==a&&null!==a||(a=0),a.toFixed(b)}window.DashboardView=Backbone.View.extend({el:"#content",interval:1e4,defaultTimeFrame:12e5,defaultDetailFrame:1728e5,history:{},graphs:{},events:{"click .subViewNavbar .subMenuEntry":"toggleViews"},tendencies:{asyncPerSecondCurrent:["asyncPerSecondCurrent","asyncPerSecondPercentChange"],syncPerSecondCurrent:["syncPerSecondCurrent","syncPerSecondPercentChange"],clientConnectionsCurrent:["clientConnectionsCurrent","clientConnectionsPercentChange"],clientConnectionsAverage:["clientConnections15M","clientConnections15MPercentChange"],numberOfThreadsCurrent:["numberOfThreadsCurrent","numberOfThreadsPercentChange"],numberOfThreadsAverage:["numberOfThreads15M","numberOfThreads15MPercentChange"],virtualSizeCurrent:["virtualSizeCurrent","virtualSizePercentChange"],virtualSizeAverage:["virtualSize15M","virtualSize15MPercentChange"]},barCharts:{totalTimeDistribution:["queueTimeDistributionPercent","requestTimeDistributionPercent"],dataTransferDistribution:["bytesSentDistributionPercent","bytesReceivedDistributionPercent"]},barChartsElementNames:{queueTimeDistributionPercent:"Queue",requestTimeDistributionPercent:"Computation",bytesSentDistributionPercent:"Bytes sent",bytesReceivedDistributionPercent:"Bytes received"},getDetailFigure:function(a){var b=$(a.currentTarget).attr("id").replace(/ChartButton/g,"");return b},showDetail:function(a){var b,c=this,d=this.getDetailFigure(a);b=this.dygraphConfig.getDetailChartConfig(d),this.getHistoryStatistics(d),this.detailGraphFigure=d,window.modalView.hideFooter=!0,window.modalView.hide(),window.modalView.show("modalGraph.ejs",b.header,void 0,void 0,void 0,void 0,this.events),window.modalView.hideFooter=!1,$("#modal-dialog").on("hidden",function(){c.hidden()}),$("#modal-dialog").toggleClass("modal-chart-detail",!0),b.height=.7*$(window).height(),b.width=$(".modal-inner-detail").width(),b.labelsDiv=$(b.labelsDiv)[0],this.detailGraph=new Dygraph(document.getElementById("lineChartDetail"),this.history[this.server][d],b)},hidden:function(){this.detailGraph.destroy(),delete this.detailGraph,delete this.detailGraphFigure},getCurrentSize:function(a){"#"!==a.substr(0,1)&&(a="#"+a);var b,c;return $(a).attr("style",""),b=$(a).height(),c=$(a).width(),{height:b,width:c}},prepareDygraphs:function(){var a,b=this;this.dygraphConfig.getDashBoardFigures().forEach(function(c){a=b.dygraphConfig.getDefaultConfig(c);var d=b.getCurrentSize(a.div);a.height=d.height,a.width=d.width,b.graphs[c]=new Dygraph(document.getElementById(a.div),b.history[b.server][c]||[],a)})},initialize:function(a){this.options=a,this.dygraphConfig=a.dygraphConfig,this.d3NotInitialized=!0,this.events["click .dashboard-sub-bar-menu-sign"]=this.showDetail.bind(this),this.events["mousedown .dygraph-rangesel-zoomhandle"]=this.stopUpdating.bind(this),this.events["mouseup .dygraph-rangesel-zoomhandle"]=this.startUpdating.bind(this),this.serverInfo=a.serverToShow,this.serverInfo?this.server=this.serverInfo.target:this.server="-local-",this.history[this.server]={}},toggleViews:function(a){var b=a.currentTarget.id.split("-")[0],c=this,d=["replication","requests","system"];_.each(d,function(a){b!==a?$("#"+a).hide():($("#"+a).show(),c.resize(),$(window).resize())}),$(".subMenuEntries").children().removeClass("active"),$("#"+b+"-statistics").addClass("active"),window.setTimeout(function(){c.resize(),$(window).resize()},200)},updateCharts:function(){var a=this;return this.detailGraph?void this.updateLineChart(this.detailGraphFigure,!0):(this.prepareD3Charts(this.isUpdating),this.prepareResidentSize(this.isUpdating),this.updateTendencies(),void Object.keys(this.graphs).forEach(function(b){a.updateLineChart(b,!1)}))},updateTendencies:function(){var a=this,b=this.tendencies,c="";Object.keys(b).forEach(function(b){var d="",e=0;a.history.hasOwnProperty(a.server)&&a.history[a.server].hasOwnProperty(b)&&(e=a.history[a.server][b][1]),0>e?c="#d05448":(c="#77DB99",d="+"),a.history.hasOwnProperty(a.server)&&a.history[a.server].hasOwnProperty(b)?$("#"+b).html(a.history[a.server][b][0]+' '+d+e+"%"):$("#"+b).html('
")}.bind(this);if("_system"!==frontendConfig.db)return void c();var d=function(d,e){d||(e?this.getStatistics(b,a):c())}.bind(this);void 0===window.App.currentDB.get("name")?window.setTimeout(function(){return"_system"!==window.App.currentDB.get("name")?void c():void this.options.database.hasSystemAccess(d)}.bind(this),300):this.options.database.hasSystemAccess(d)}})}(),function(){"use strict";window.DatabaseView=Backbone.View.extend({users:null,el:"#content",template:templateEngine.createTemplate("databaseView.ejs"),dropdownVisible:!1,currentDB:"",events:{"click #createDatabase":"createDatabase","click #submitCreateDatabase":"submitCreateDatabase","click .editDatabase":"editDatabase","click #userManagementView .icon":"editDatabase","click #selectDatabase":"updateDatabase","click #submitDeleteDatabase":"submitDeleteDatabase","click .contentRowInactive a":"changeDatabase","keyup #databaseSearchInput":"search","click #databaseSearchSubmit":"search","click #databaseToggle":"toggleSettingsDropdown","click .css-label":"checkBoxes","click #dbSortDesc":"sorting"},sorting:function(){$("#dbSortDesc").is(":checked")?this.collection.setSortingDesc(!0):this.collection.setSortingDesc(!1),$("#databaseDropdown").is(":visible")?this.dropdownVisible=!0:this.dropdownVisible=!1,this.render()},initialize:function(){this.collection.fetch({async:!0,cache:!1})},checkBoxes:function(a){var b=a.currentTarget.id;$("#"+b).click()},render:function(){var a=function(a,b){a?arangoHelper.arangoError("DB","Could not get current db properties"):(this.currentDB=b,this.collection.sort(),$(this.el).html(this.template.render({collection:this.collection,searchString:"",currentDB:this.currentDB})),this.dropdownVisible===!0&&($("#dbSortDesc").attr("checked",this.collection.sortOptions.desc),$("#databaseToggle").toggleClass("activated"),$("#databaseDropdown2").show()),arangoHelper.setCheckboxStatus("#databaseDropdown"),this.replaceSVGs())}.bind(this);return this.collection.getCurrentDatabase(a),this},toggleSettingsDropdown:function(){$("#dbSortDesc").attr("checked",this.collection.sortOptions.desc),$("#databaseToggle").toggleClass("activated"),$("#databaseDropdown2").slideToggle(200)},selectedDatabase:function(){return $("#selectDatabases").val()},handleError:function(a,b,c){return 409===a?void arangoHelper.arangoError("DB","Database "+c+" already exists."):400===a?void arangoHelper.arangoError("DB","Invalid Parameters"):403===a?void arangoHelper.arangoError("DB","Insufficent rights. Execute this from _system database"):void 0},validateDatabaseInfo:function(a,b){return""===b?(arangoHelper.arangoError("DB","You have to define an owner for the new database"),!1):""===a?(arangoHelper.arangoError("DB","You have to define a name for the new database"),!1):0===a.indexOf("_")?(arangoHelper.arangoError("DB ","Databasename should not start with _"),!1):a.match(/^[a-zA-Z][a-zA-Z0-9_\-]*$/)?!0:(arangoHelper.arangoError("DB","Databasename may only contain numbers, letters, _ and -"),!1)},createDatabase:function(a){a.preventDefault(),this.createAddDatabaseModal()},switchDatabase:function(a){if(!$(a.target).parent().hasClass("iconSet")){var b=$(a.currentTarget).find("h5").text();if(""!==b){var c=this.collection.createDatabaseURL(b);window.location.replace(c)}}},submitCreateDatabase:function(){var a=this,b=$("#newDatabaseName").val(),c=$("#newUser").val(),d={name:b};this.collection.create(d,{error:function(c,d){a.handleError(d.status,d.statusText,b)},success:function(d){"root"!==c&&$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(c)+"/database/"+encodeURIComponent(b)),contentType:"application/json",data:JSON.stringify({grant:"rw"})}),$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_api/user/root/database/"+encodeURIComponent(b)),contentType:"application/json",data:JSON.stringify({grant:"rw"})}),"#databases"===window.location.hash&&a.updateDatabases(),arangoHelper.arangoNotification("Database "+d.get("name")+" created.")}}),arangoHelper.arangoNotification("Database creation in progress."),window.modalView.hide()},submitDeleteDatabase:function(a){var b=this.collection.where({name:a});b[0].destroy({wait:!0,url:arangoHelper.databaseUrl("/_api/database/"+a)}),this.updateDatabases(),window.App.naviView.dbSelectionView.render($("#dbSelect")),window.modalView.hide()},changeDatabase:function(a){var b=$(a.currentTarget).attr("id"),c=this.collection.createDatabaseURL(b);window.location.replace(c)},updateDatabases:function(){var a=this;this.collection.fetch({cache:!1,success:function(){a.render(),window.App.handleSelectDatabase()}})},editDatabase:function(a){var b=this.evaluateDatabaseName($(a.currentTarget).attr("id"),"_edit-database"),c=!0;b===this.currentDB&&(c=!1),this.createEditDatabaseModal(b,c)},search:function(){var a,b,c,d;a=$("#databaseSearchInput"),b=$("#databaseSearchInput").val(),d=this.collection.filter(function(a){return-1!==a.get("name").indexOf(b)}),$(this.el).html(this.template.render({collection:d,searchString:b,currentDB:this.currentDB})),this.replaceSVGs(),a=$("#databaseSearchInput"),c=a.val().length,a.focus(),a[0].setSelectionRange(c,c)},replaceSVGs:function(){$(".svgToReplace").each(function(){var a=$(this),b=a.attr("id"),c=a.attr("src");$.get(c,function(c){var d=$(c).find("svg");d.attr("id",b).attr("class","tile-icon-svg").removeAttr("xmlns:a"),a.replaceWith(d)},"xml")})},evaluateDatabaseName:function(a,b){var c=a.lastIndexOf(b);return a.substring(0,c)},createEditDatabaseModal:function(a,b){var c=[],d=[];d.push(window.modalView.createReadOnlyEntry("id_name","Name",a,"")),b?c.push(window.modalView.createDeleteButton("Delete",this.submitDeleteDatabase.bind(this,a))):c.push(window.modalView.createDisabledButton("Delete")),window.modalView.show("modalTable.ejs","Delete database",c,d)},createAddDatabaseModal:function(){var a=[],b=[];b.push(window.modalView.createTextEntry("newDatabaseName","Name","",!1,"Database Name",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Database name must start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No database name given."}]));var c=[];window.App.userCollection.each(function(a){c.push({value:a.get("user"),label:a.get("user")})}),b.push(window.modalView.createSelectEntry("newUser","Username",null!==this.users?this.users.whoAmI():"root","Please define the owner of this database. This will be the only user having initial access to this database if authentication is turned on. Please note that if you specify a username different to your account you will not be able to access the database with your account after having creating it. Specifying a username is mandatory even with authentication turned off. If there is a failure you will be informed.",c)),a.push(window.modalView.createSuccessButton("Create",this.submitCreateDatabase.bind(this))),window.modalView.show("modalTable.ejs","Create Database",a,b),$("#useDefaultPassword").change(function(){"true"===$("#useDefaultPassword").val()?$("#row_newPassword").hide():$("#row_newPassword").show()}),$("#row_newPassword").hide()}})}(),function(){"use strict";window.DBSelectionView=Backbone.View.extend({template:templateEngine.createTemplate("dbSelectionView.ejs"),events:{"click .dbSelectionLink":"changeDatabase"},initialize:function(a){this.current=a.current},changeDatabase:function(a){var b=$(a.currentTarget).closest(".dbSelectionLink.tab").attr("id"),c=this.collection.createDatabaseURL(b);window.location.replace(c)},render:function(a){var b=function(b,c){b?arangoHelper.arangoError("DB","Could not fetch databases"):(this.$el=a,this.$el.html(this.template.render({list:c,current:this.current.get("name")})),this.delegateEvents())}.bind(this);return this.collection.getDatabasesForUser(b),this.el}})}(),function(){"use strict";window.DocumentsView=window.PaginationView.extend({filters:{0:!0},filterId:0,paginationDiv:"#documentsToolbarF",idPrefix:"documents",addDocumentSwitch:!0,activeFilter:!1,lastCollectionName:void 0,restoredFilters:[],editMode:!1,allowUpload:!1,el:"#content",table:"#documentsTableID",template:templateEngine.createTemplate("documentsView.ejs"),collectionContext:{prev:null,next:null},editButtons:["#deleteSelected","#moveSelected"],initialize:function(a){this.documentStore=a.documentStore,this.collectionsStore=a.collectionsStore,this.tableView=new window.TableView({el:this.table,collection:this.collection}),this.tableView.setRowClick(this.clicked.bind(this)),this.tableView.setRemoveClick(this.remove.bind(this))},resize:function(){$("#docPureTable").height($(".centralRow").height()-210),$("#docPureTable .pure-table-body").css("max-height",$("#docPureTable").height()-47)},setCollectionId:function(a,b){this.collection.setCollection(a),this.collection.setPage(b),this.page=b;var c=function(b,c){b?arangoHelper.arangoError("Error","Could not get collection properties."):(this.type=c,this.collection.getDocuments(this.getDocsCallback.bind(this)),this.collectionModel=this.collectionsStore.get(a))}.bind(this);arangoHelper.collectionApiType(a,null,c)},getDocsCallback:function(a){$("#documents_last").css("visibility","hidden"),$("#documents_first").css("visibility","hidden"),a?(window.progressView.hide(),arangoHelper.arangoError("Document error","Could not fetch requested documents.")):a&&void 0===a||(window.progressView.hide(),this.drawTable(),this.renderPaginationElements())},events:{"click #collectionPrev":"prevCollection","click #collectionNext":"nextCollection","click #filterCollection":"filterCollection","click #markDocuments":"editDocuments","click #importCollection":"importCollection","click #exportCollection":"exportCollection","click #filterSend":"sendFilter","click #addFilterItem":"addFilterItem","click .removeFilterItem":"removeFilterItem","click #deleteSelected":"deleteSelectedDocs","click #moveSelected":"moveSelectedDocs","click #addDocumentButton":"addDocumentModal","click #documents_first":"firstDocuments","click #documents_last":"lastDocuments","click #documents_prev":"prevDocuments","click #documents_next":"nextDocuments","click #confirmDeleteBtn":"confirmDelete","click .key":"nop",keyup:"returnPressedHandler","keydown .queryline input":"filterValueKeydown","click #importModal":"showImportModal","click #resetView":"resetView","click #confirmDocImport":"startUpload","click #exportDocuments":"startDownload","change #documentSize":"setPagesize","change #docsSort":"setSorting"},showSpinner:function(){$("#uploadIndicator").show()},hideSpinner:function(){$("#uploadIndicator").hide()},showImportModal:function(){$("#docImportModal").modal("show")},hideImportModal:function(){$("#docImportModal").modal("hide")},setPagesize:function(){var a=$("#documentSize").find(":selected").val();this.collection.setPagesize(a),this.collection.getDocuments(this.getDocsCallback.bind(this))},setSorting:function(){var a=$("#docsSort").val();""!==a&&void 0!==a&&null!==a||(a="_key"),this.collection.setSort(a)},returnPressedHandler:function(a){13===a.keyCode&&$(a.target).is($("#docsSort"))&&this.collection.getDocuments(this.getDocsCallback.bind(this)),13===a.keyCode&&$("#confirmDeleteBtn").attr("disabled")===!1&&this.confirmDelete()},nop:function(a){a.stopPropagation()},resetView:function(){var a=function(a){a&&arangoHelper.arangoError("Document","Could not fetch documents count")};$("input").val(""),$("select").val("=="),this.removeAllFilterItems(),$("#documentSize").val(this.collection.getPageSize()),$("#documents_last").css("visibility","visible"),$("#documents_first").css("visibility","visible"),this.addDocumentSwitch=!0,this.collection.resetFilter(),this.collection.loadTotal(a),this.restoredFilters=[],this.allowUpload=!1,this.files=void 0,this.file=void 0,$("#confirmDocImport").attr("disabled",!0),this.markFilterToggle(),this.collection.getDocuments(this.getDocsCallback.bind(this))},startDownload:function(){var a=this.collection.buildDownloadDocumentQuery();if(""!==a||void 0!==a||null!==a){var b="query/result/download/"+btoa(JSON.stringify(a));arangoHelper.download(b)}else arangoHelper.arangoError("Document error","could not download documents")},startUpload:function(){var a=function(a,b){a?(arangoHelper.arangoError("Upload",b),this.hideSpinner()):(this.hideSpinner(),this.hideImportModal(),this.resetView())}.bind(this);this.allowUpload===!0&&(this.showSpinner(),this.collection.uploadDocuments(this.file,a))},uploadSetup:function(){var a=this;$("#importDocuments").change(function(b){a.files=b.target.files||b.dataTransfer.files,a.file=a.files[0],$("#confirmDocImport").attr("disabled",!1),a.allowUpload=!0})},buildCollectionLink:function(a){return"collection/"+encodeURIComponent(a.get("name"))+"/documents/1"},markFilterToggle:function(){this.restoredFilters.length>0?$("#filterCollection").addClass("activated"):$("#filterCollection").removeClass("activated")},editDocuments:function(){$("#importCollection").removeClass("activated"),$("#exportCollection").removeClass("activated"),this.markFilterToggle(),$("#markDocuments").toggleClass("activated"),this.changeEditMode(),$("#filterHeader").hide(),$("#importHeader").hide(),$("#editHeader").slideToggle(200),$("#exportHeader").hide()},filterCollection:function(){$("#importCollection").removeClass("activated"),$("#exportCollection").removeClass("activated"),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),this.markFilterToggle(),this.activeFilter=!0,$("#importHeader").hide(),$("#editHeader").hide(),$("#exportHeader").hide(),$("#filterHeader").slideToggle(200);var a;for(a in this.filters)if(this.filters.hasOwnProperty(a))return void $("#attribute_name"+a).focus()},exportCollection:function(){$("#importCollection").removeClass("activated"),$("#filterHeader").removeClass("activated"),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),$("#exportCollection").toggleClass("activated"),this.markFilterToggle(),$("#exportHeader").slideToggle(200),$("#importHeader").hide(),$("#filterHeader").hide(),$("#editHeader").hide()},importCollection:function(){this.markFilterToggle(),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),$("#importCollection").toggleClass("activated"),$("#exportCollection").removeClass("activated"),$("#importHeader").slideToggle(200),$("#filterHeader").hide(),$("#editHeader").hide(),$("#exportHeader").hide()},changeEditMode:function(a){a===!1||this.editMode===!0?($("#docPureTable .pure-table-body .pure-table-row").css("cursor","default"),$(".deleteButton").fadeIn(),$(".addButton").fadeIn(),$(".selected-row").removeClass("selected-row"),this.editMode=!1,this.tableView.setRowClick(this.clicked.bind(this))):($("#docPureTable .pure-table-body .pure-table-row").css("cursor","copy"),$(".deleteButton").fadeOut(),$(".addButton").fadeOut(),$(".selectedCount").text(0),this.editMode=!0,this.tableView.setRowClick(this.editModeClick.bind(this)))},getFilterContent:function(){var a,b,c=[];for(a in this.filters)if(this.filters.hasOwnProperty(a)){b=$("#attribute_value"+a).val();try{b=JSON.parse(b)}catch(d){b=String(b)}""!==$("#attribute_name"+a).val()&&c.push({attribute:$("#attribute_name"+a).val(),operator:$("#operator"+a).val(),value:b})}return c},sendFilter:function(){this.restoredFilters=this.getFilterContent();var a=this;this.collection.resetFilter(),this.addDocumentSwitch=!1,_.each(this.restoredFilters,function(b){void 0!==b.operator&&a.collection.addFilter(b.attribute,b.operator,b.value)}),this.collection.setToFirst(),this.collection.getDocuments(this.getDocsCallback.bind(this)),this.markFilterToggle()},restoreFilter:function(){var a=this,b=0;this.filterId=0,$("#docsSort").val(this.collection.getSort()),_.each(this.restoredFilters,function(c){0!==b&&a.addFilterItem(),void 0!==c.operator&&($("#attribute_name"+b).val(c.attribute),$("#operator"+b).val(c.operator),$("#attribute_value"+b).val(c.value)),b++,a.collection.addFilter(c.attribute,c.operator,c.value)})},addFilterItem:function(){var a=++this.filterId;$("#filterHeader").append('
'),this.filters[a]=!0,this.checkFilterState()},filterValueKeydown:function(a){13===a.keyCode&&this.sendFilter()},checkFilterState:function(){var a=$("#filterHeader .queryline").length;if(1===a)$("#filterHeader .removeFilterItem").remove();else if(0===$("#filterHeader .queryline").first().find(".removeFilterItem").length){var b=$("#filterHeader .queryline").first().children().first().attr("id"),c=b.substr(14,b.length);$("#filterHeader .queryline").first().find(".add-filter-item").after(' ')}0===$("#filterHeader .queryline").first().find(".add-filter-item").length&&$("#filterHeader .queryline").first().find(".filterValue").after('')},removeFilterItem:function(a){var b=a.currentTarget,c=b.id.replace(/^removeFilter/,"");delete this.filters[c],delete this.restoredFilters[c],$(b.parentElement).remove(),this.checkFilterState()},removeAllFilterItems:function(){var a,b=$("#filterHeader").children().length;for(a=1;b>=a;a++)$("#removeFilter"+a).parent().remove();this.filters={0:!0},this.filterId=0},addDocumentModal:function(){var a=window.location.hash.split("/")[1],b=[],c=[],d=function(a,d){a?arangoHelper.arangoError("Error","Could not fetch collection type"):"edge"===d?(c.push(window.modalView.createTextEntry("new-edge-from-attr","_from","","document _id: document handle of the linked vertex (incoming relation)",void 0,!1,[{rule:Joi.string().required(),msg:"No _from attribute given."}])),c.push(window.modalView.createTextEntry("new-edge-to","_to","","document _id: document handle of the linked vertex (outgoing relation)",void 0,!1,[{rule:Joi.string().required(),msg:"No _to attribute given."}])),c.push(window.modalView.createTextEntry("new-edge-key-attr","_key",void 0,"the edges unique key(optional attribute, leave empty for autogenerated key","is optional: leave empty for autogenerated key",!1,[{rule:Joi.string().allow("").optional(),msg:""}])),b.push(window.modalView.createSuccessButton("Create",this.addEdge.bind(this))),window.modalView.show("modalTable.ejs","Create edge",b,c)):(c.push(window.modalView.createTextEntry("new-document-key-attr","_key",void 0,"the documents unique key(optional attribute, leave empty for autogenerated key","is optional: leave empty for autogenerated key",!1,[{rule:Joi.string().allow("").optional(),msg:""}])),b.push(window.modalView.createSuccessButton("Create",this.addDocument.bind(this))),window.modalView.show("modalTable.ejs","Create document",b,c))}.bind(this);arangoHelper.collectionApiType(a,!0,d)},addEdge:function(){var a,b=window.location.hash.split("/")[1],c=$(".modal-body #new-edge-from-attr").last().val(),d=$(".modal-body #new-edge-to").last().val(),e=$(".modal-body #new-edge-key-attr").last().val(),f=function(b,c){if(b)arangoHelper.arangoError("Error","Could not create edge");else{window.modalView.hide(),c=c._id.split("/");try{a="collection/"+c[0]+"/"+c[1],decodeURI(a)}catch(d){a="collection/"+c[0]+"/"+encodeURIComponent(c[1])}window.location.hash=a}};""!==e||void 0!==e?this.documentStore.createTypeEdge(b,c,d,e,f):this.documentStore.createTypeEdge(b,c,d,null,f)},addDocument:function(){var a,b=window.location.hash.split("/")[1],c=$(".modal-body #new-document-key-attr").last().val(),d=function(b,c){if(b)arangoHelper.arangoError("Error","Could not create document");else{window.modalView.hide(),c=c.split("/");try{a="collection/"+c[0]+"/"+c[1],decodeURI(a)}catch(d){a="collection/"+c[0]+"/"+encodeURIComponent(c[1])}window.location.hash=a}};""!==c||void 0!==c?this.documentStore.createTypeDocument(b,c,d):this.documentStore.createTypeDocument(b,null,d)},moveSelectedDocs:function(){var a=[],b=[],c=this.getSelectedDocs();0!==c.length&&(b.push(window.modalView.createTextEntry("move-documents-to","Move to","",!1,"collection-name",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}])),a.push(window.modalView.createSuccessButton("Move",this.confirmMoveSelectedDocs.bind(this))),window.modalView.show("modalTable.ejs","Move documents",a,b))},confirmMoveSelectedDocs:function(){var a=this.getSelectedDocs(),b=this,c=$(".modal-body").last().find("#move-documents-to").val(),d=function(){this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide()}.bind(this);_.each(a,function(a){b.collection.moveDocument(a,b.collection.collectionID,c,d)})},deleteSelectedDocs:function(){var a=[],b=[],c=this.getSelectedDocs();0!==c.length&&(b.push(window.modalView.createReadOnlyEntry(void 0,c.length+" documents selected","Do you want to delete all selected documents?",void 0,void 0,!1,void 0)),a.push(window.modalView.createDeleteButton("Delete",this.confirmDeleteSelectedDocs.bind(this))),window.modalView.show("modalTable.ejs","Delete documents",a,b))},confirmDeleteSelectedDocs:function(){var a=this.getSelectedDocs(),b=[],c=this;_.each(a,function(a){if("document"===c.type){var d=function(a){a?(b.push(!1),arangoHelper.arangoError("Document error","Could not delete document.")):(b.push(!0),c.collection.setTotalMinusOne(),c.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(c);c.documentStore.deleteDocument(c.collection.collectionID,a,d)}else if("edge"===c.type){var e=function(a){a?(b.push(!1),arangoHelper.arangoError("Edge error","Could not delete edge")):(c.collection.setTotalMinusOne(),b.push(!0),c.collection.getDocuments(this.getDocsCallback.bind(this)),$("#markDocuments").click(),window.modalView.hide())}.bind(c);c.documentStore.deleteEdge(c.collection.collectionID,a,e)}})},getSelectedDocs:function(){var a=[];return _.each($("#docPureTable .pure-table-body .pure-table-row"),function(b){$(b).hasClass("selected-row")&&a.push($($(b).children()[1]).find(".key").text())}),a},remove:function(a){this.docid=$(a.currentTarget).parent().parent().prev().find(".key").text(),$("#confirmDeleteBtn").attr("disabled",!1),$("#docDeleteModal").modal("show")},confirmDelete:function(){$("#confirmDeleteBtn").attr("disabled",!0);var a=window.location.hash.split("/"),b=a[3];"source"!==b&&this.reallyDelete()},reallyDelete:function(){if("document"===this.type){var a=function(a){a?arangoHelper.arangoError("Error","Could not delete document"):(this.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#docDeleteModal").modal("hide"))}.bind(this);this.documentStore.deleteDocument(this.collection.collectionID,this.docid,a)}else if("edge"===this.type){var b=function(a){a?arangoHelper.arangoError("Edge error","Could not delete edge"):(this.collection.setTotalMinusOne(),this.collection.getDocuments(this.getDocsCallback.bind(this)),$("#docDeleteModal").modal("hide"))}.bind(this);this.documentStore.deleteEdge(this.collection.collectionID,this.docid,b)}},editModeClick:function(a){var b=$(a.currentTarget);b.hasClass("selected-row")?b.removeClass("selected-row"):b.addClass("selected-row");var c=this.getSelectedDocs();$(".selectedCount").text(c.length),_.each(this.editButtons,function(a){c.length>0?($(a).prop("disabled",!1),$(a).removeClass("button-neutral"),$(a).removeClass("disabled"),"#moveSelected"===a?$(a).addClass("button-success"):$(a).addClass("button-danger")):($(a).prop("disabled",!0),$(a).addClass("disabled"),$(a).addClass("button-neutral"),"#moveSelected"===a?$(a).removeClass("button-success"):$(a).removeClass("button-danger"))})},clicked:function(a){var b,c=a.currentTarget,d=$(c).attr("id").substr(4);try{b="collection/"+this.collection.collectionID+"/"+d,decodeURI(d)}catch(e){b="collection/"+this.collection.collectionID+"/"+encodeURIComponent(d)}window.location.hash=b},drawTable:function(){this.tableView.setElement($("#docPureTable")).render(),arangoHelper.fixTooltips(".icon_arangodb, .arangoicon","top"),$(".prettify").snippet("javascript",{style:"nedit",menu:!1,startText:!1,transparent:!0,showNum:!1}),this.resize()},checkCollectionState:function(){this.lastCollectionName===this.collectionName?this.activeFilter&&(this.filterCollection(),this.restoreFilter()):void 0!==this.lastCollectionName&&(this.collection.resetFilter(),this.collection.setSort(""),this.restoredFilters=[],this.activeFilter=!1)},render:function(){return $(this.el).html(this.template.render({})),2===this.type?this.type="document":3===this.type&&(this.type="edge"),this.tableView.setElement($(this.table)).drawLoading(),this.collectionContext=this.collectionsStore.getPosition(this.collection.collectionID),this.collectionName=window.location.hash.split("/")[1],this.breadcrumb(),window.arangoHelper.buildCollectionSubNav(this.collectionName,"Content"),this.checkCollectionState(),this.lastCollectionName=this.collectionName,this.uploadSetup(),$("[data-toggle=tooltip]").tooltip(),$(".upload-info").tooltip(),arangoHelper.fixTooltips(".icon_arangodb, .arangoicon","top"),this.renderPaginationElements(),this.selectActivePagesize(),this.markFilterToggle(),this.resize(),this},rerender:function(){this.collection.getDocuments(this.getDocsCallback.bind(this)),this.resize()},selectActivePagesize:function(){$("#documentSize").val(this.collection.getPageSize())},renderPaginationElements:function(){this.renderPagination();var a=$("#totalDocuments");0===a.length&&($("#documentsToolbarFL").append(''),a=$("#totalDocuments")),"document"===this.type&&a.html(numeral(this.collection.getTotal()).format("0,0")+" doc(s)"),"edge"===this.type&&a.html(numeral(this.collection.getTotal()).format("0,0")+" edge(s)")},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)}})}(),function(){"use strict";var a=function(a){var b=a.split("/");return"collection/"+encodeURIComponent(b[0])+"/"+encodeURIComponent(b[1])};window.DocumentView=Backbone.View.extend({el:"#content",colid:0,docid:0,customView:!1,defaultMode:"tree",template:templateEngine.createTemplate("documentView.ejs"),events:{"click #saveDocumentButton":"saveDocument","click #deleteDocumentButton":"deleteDocumentModal","click #confirmDeleteDocument":"deleteDocument","click #document-from":"navigateToDocument","click #document-to":"navigateToDocument","keydown #documentEditor .ace_editor":"keyPress","keyup .jsoneditor .search input":"checkSearchBox","click .jsoneditor .modes":"storeMode","click #addDocument":"addDocument"},checkSearchBox:function(a){""===$(a.currentTarget).val()&&this.editor.expandAll()},initialize:function(){var a=localStorage.getItem("JSONEditorMode");a&&(this.defaultMode=a)},addDocument:function(){window.App.documentsView.addDocumentModal()},storeMode:function(){var a=this;$(".type-modes").on("click",function(b){var c=$(b.currentTarget).text().toLowerCase();localStorage.setItem("JSONEditorMode",c),a.defaultMode=c})},keyPress:function(a){a.ctrlKey&&13===a.keyCode?(a.preventDefault(),this.saveDocument()):a.metaKey&&13===a.keyCode&&(a.preventDefault(),this.saveDocument())},editor:0,setType:function(a){a=2===a?"document":"edge";var b=function(a,b){if(a)arangoHelper.arangoError("Error","Could not fetch data.");else{var c=b+": ";this.type=b,this.fillInfo(c),this.fillEditor()}}.bind(this);"edge"===a?this.collection.getEdge(this.colid,this.docid,b):"document"===a&&this.collection.getDocument(this.colid,this.docid,b)},deleteDocumentModal:function(){var a=[],b=[];b.push(window.modalView.createReadOnlyEntry("doc-delete-button","Confirm delete, document id is",this.type._id,void 0,void 0,!1,/[<>&'"]/)),a.push(window.modalView.createDeleteButton("Delete",this.deleteDocument.bind(this))),window.modalView.show("modalTable.ejs","Delete Document",a,b)},deleteDocument:function(){var a=function(){if(this.customView)this.customDeleteFunction();else{var a="collection/"+encodeURIComponent(this.colid)+"/documents/1";window.modalView.hide(),window.App.navigate(a,{trigger:!0})}}.bind(this);if(this.type._from&&this.type._to){var b=function(b){b?arangoHelper.arangoError("Edge error","Could not delete edge"):a()};this.collection.deleteEdge(this.colid,this.docid,b)}else{var c=function(b){b?arangoHelper.arangoError("Error","Could not delete document"):a()};this.collection.deleteDocument(this.colid,this.docid,c)}},navigateToDocument:function(a){var b=$(a.target).attr("documentLink");b&&window.App.navigate(b,{trigger:!0})},fillInfo:function(){var b=this.collection.first(),c=b.get("_id"),d=b.get("_key"),e=b.get("_rev"),f=b.get("_from"),g=b.get("_to");if($("#document-type").css("margin-left","10px"),$("#document-type").text("_id:"),$("#document-id").css("margin-left","0"),$("#document-id").text(c),$("#document-key").text(d),$("#document-rev").text(e),f&&g){var h=a(f),i=a(g);$("#document-from").text(f),$("#document-from").attr("documentLink",h),$("#document-to").text(g),$("#document-to").attr("documentLink",i)}else $(".edge-info-container").hide()},fillEditor:function(){var a=this.removeReadonlyKeys(this.collection.first().attributes);$(".disabledBread").last().text(this.collection.first().get("_key")),this.editor.set(a),$(".ace_content").attr("font-size","11pt")},jsonContentChanged:function(){this.enableSaveButton()},resize:function(){$("#documentEditor").height($(".centralRow").height()-300)},render:function(){$(this.el).html(this.template.render({})),$("#documentEditor").height($(".centralRow").height()-300),this.disableSaveButton(),this.breadcrumb();var a=this,b=document.getElementById("documentEditor"),c={change:function(){a.jsonContentChanged()},search:!0,mode:"tree",modes:["tree","code"],iconlib:"fontawesome4"};return this.editor=new JSONEditor(b,c),this.editor.setMode(this.defaultMode),this},removeReadonlyKeys:function(a){return _.omit(a,["_key","_id","_from","_to","_rev"])},saveDocument:function(){if(void 0===$("#saveDocumentButton").attr("disabled"))if("_"===this.collection.first().attributes._id.substr(0,1)){var a=[],b=[];b.push(window.modalView.createReadOnlyEntry("doc-save-system-button","Caution","You are modifying a system collection. Really continue?",void 0,void 0,!1,/[<>&'"]/)),
+a.push(window.modalView.createSuccessButton("Save",this.confirmSaveDocument.bind(this))),window.modalView.show("modalTable.ejs","Modify System Collection",a,b)}else this.confirmSaveDocument()},confirmSaveDocument:function(){window.modalView.hide();var a;try{a=this.editor.get()}catch(b){return this.errorConfirmation(b),void this.disableSaveButton()}if(a=JSON.stringify(a),this.type._from&&this.type._to){var c=function(a){a?arangoHelper.arangoError("Error","Could not save edge."):(this.successConfirmation(),this.disableSaveButton())}.bind(this);this.collection.saveEdge(this.colid,this.docid,this.type._from,this.type._to,a,c)}else{var d=function(a){a?arangoHelper.arangoError("Error","Could not save document."):(this.successConfirmation(),this.disableSaveButton())}.bind(this);this.collection.saveDocument(this.colid,this.docid,a,d)}},successConfirmation:function(){arangoHelper.arangoNotification("Document saved.")},errorConfirmation:function(a){arangoHelper.arangoError("Document editor: ",a)},enableSaveButton:function(){$("#saveDocumentButton").prop("disabled",!1),$("#saveDocumentButton").addClass("button-success"),$("#saveDocumentButton").removeClass("button-close")},disableSaveButton:function(){$("#saveDocumentButton").prop("disabled",!0),$("#saveDocumentButton").addClass("button-close"),$("#saveDocumentButton").removeClass("button-success")},breadcrumb:function(){var a=window.location.hash.split("/");$("#subNavigationBar .breadcrumb").html('Collection: '+a[1]+'Document: '+a[2])},escaped:function(a){return a.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}})}(),function(){"use strict";window.FooterView=Backbone.View.extend({el:"#footerBar",system:{},isOffline:!0,isOfflineCounter:0,firstLogin:!0,timer:15e3,lap:0,timerFunction:null,events:{"click .footer-center p":"showShortcutModal"},initialize:function(){var a=this;window.setInterval(function(){a.getVersion()},a.timer),a.getVersion(),window.VISIBLE=!0,document.addEventListener("visibilitychange",function(){window.VISIBLE=!window.VISIBLE}),$("#offlinePlaceholder button").on("click",function(){a.getVersion()}),window.setTimeout(function(){window.frontendConfig.isCluster===!0&&($(".health-state").css("cursor","pointer"),$(".health-state").on("click",function(){window.App.navigate("#nodes",{trigger:!0})}))},1e3)},template:templateEngine.createTemplate("footerView.ejs"),showServerStatus:function(a){window.App.isCluster?this.renderClusterState(a):a===!0?($("#healthStatus").removeClass("negative"),$("#healthStatus").addClass("positive"),$(".health-state").html("GOOD"),$(".health-icon").html(''),$("#offlinePlaceholder").hide()):($("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),$(".health-state").html("UNKNOWN"),$(".health-icon").html(''),$("#offlinePlaceholder").show(),this.reconnectAnimation(0))},reconnectAnimation:function(a){var b=this;0===a&&(b.lap=a,$("#offlineSeconds").text(b.timer/1e3),clearTimeout(b.timerFunction)),b.lap0?($("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),1===c?$(".health-state").html(c+" NODE ERROR"):$(".health-state").html(c+" NODES ERROR"),$(".health-icon").html('')):($("#healthStatus").removeClass("negative"),$("#healthStatus").addClass("positive"),$(".health-state").html("NODES OK"),$(".health-icon").html(''))};$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,async:!0,success:function(a){b(a)}})}else $("#healthStatus").removeClass("positive"),$("#healthStatus").addClass("negative"),$(".health-state").html(window.location.host+" OFFLINE"),$(".health-icon").html(''),$("#offlinePlaceholder").show(),this.reconnectAnimation(0)},showShortcutModal:function(){window.arangoHelper.hotkeysFunctions.showHotkeysModal()},getVersion:function(){var a=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/version"),contentType:"application/json",processData:!1,async:!0,success:function(b){a.showServerStatus(!0),a.isOffline===!0&&(a.isOffline=!1,a.isOfflineCounter=0,a.firstLogin?a.firstLogin=!1:window.setTimeout(function(){a.showServerStatus(!0)},1e3),a.system.name=b.server,a.system.version=b.version,a.render())},error:function(b){401===b.status?(a.showServerStatus(!0),window.App.navigate("login",{trigger:!0})):(a.isOffline=!0,a.isOfflineCounter++,a.isOfflineCounter>=1&&a.showServerStatus(!1))}}),a.system.hasOwnProperty("database")||$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/database/current"),contentType:"application/json",processData:!1,async:!0,success:function(b){var c=b.result.name;a.system.database=c;var d=window.setInterval(function(){var b=$("#databaseNavi");b&&(window.clearTimeout(d),d=null,a.render())},50)}})},renderVersion:function(){this.system.hasOwnProperty("database")&&this.system.hasOwnProperty("name")&&$(this.el).html(this.template.render({name:this.system.name,version:this.system.version,database:this.system.database}))},render:function(){return this.system.version||this.getVersion(),$(this.el).html(this.template.render({name:this.system.name,version:this.system.version})),this}})}(),function(){"use strict";window.FoxxActiveView=Backbone.View.extend({tagName:"div",className:"tile pure-u-1-1 pure-u-sm-1-2 pure-u-md-1-3 pure-u-lg-1-4 pure-u-xl-1-6",template:templateEngine.createTemplate("foxxActiveView.ejs"),_show:!0,events:{click:"openAppDetailView"},openAppDetailView:function(){window.App.navigate("service/"+encodeURIComponent(this.model.get("mount")),{trigger:!0})},toggle:function(a,b){switch(a){case"devel":this.model.isDevelopment()&&(this._show=b);break;case"production":this.model.isDevelopment()||this.model.isSystem()||(this._show=b);break;case"system":this.model.isSystem()&&(this._show=b)}this._show?$(this.el).show():$(this.el).hide()},render:function(){return this.model.fetchThumbnail(function(){$(this.el).html(this.template.render({model:this.model}));var a=function(){this.model.needsConfiguration()&&($(this.el).find(".warning-icons").length>0?$(this.el).find(".warning-icons").append(''):$(this.el).find("img").after(''))}.bind(this),b=function(){this.model.hasUnconfiguredDependencies()&&($(this.el).find(".warning-icons").length>0?$(this.el).find(".warning-icons").append(''):$(this.el).find("img").after(''))}.bind(this);this.model.getConfiguration(a),this.model.getDependencies(b)}.bind(this)),$(this.el)}})}(),function(){"use strict";var a={ERROR_SERVICE_DOWNLOAD_FAILED:{code:1752,message:"service download failed"}},b=templateEngine.createTemplate("applicationListView.ejs"),c=function(a){this.collection=a.collection},d=function(b){var c=this;if(b.error===!1)this.collection.fetch({success:function(){window.modalView.hide(),c.reload(),console.log(b),arangoHelper.arangoNotification("Services","Service "+b.name+" installed.")}});else{var d=b;switch(b.hasOwnProperty("responseJSON")&&(d=b.responseJSON),d.errorNum){case a.ERROR_SERVICE_DOWNLOAD_FAILED.code:arangoHelper.arangoError("Services","Unable to download application from the given repository.");break;default:arangoHelper.arangoError("Services",d.errorNum+". "+d.errorMessage)}}},e=function(){window.modalView.modalBindValidation({id:"new-app-mount",validateInput:function(){return[{rule:Joi.string().regex(/^(\/(APP[^\/]+|(?!APP)[a-zA-Z0-9_\-%]+))+$/i),msg:"May not contain /APP"},{rule:Joi.string().regex(/^(\/[a-zA-Z0-9_\-%]+)+$/),msg:"Can only contain [a-zA-Z0-9_-%]"},{rule:Joi.string().regex(/^\/([^_]|_open\/)/),msg:"Mountpoints with _ are reserved for internal use"},{rule:Joi.string().regex(/[^\/]$/),msg:"May not end with /"},{rule:Joi.string().regex(/^\//),msg:"Has to start with /"},{rule:Joi.string().required().min(2),msg:"Has to be non-empty"}]}})},f=function(){window.modalView.modalBindValidation({id:"repository",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+$/),msg:"No valid Github account and repository."}]}})},g=function(){window.modalView.modalBindValidation({id:"new-app-author",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-name",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z\-_][a-zA-Z0-9\-_]*$/),msg:"Can only contain a to z, A to Z, 0-9, '-' and '_'."}]}}),window.modalView.modalBindValidation({id:"new-app-description",validateInput:function(){return[{rule:Joi.string().required().min(1),msg:"Has to be non empty."}]}}),window.modalView.modalBindValidation({id:"new-app-license",validateInput:function(){return[{rule:Joi.string().required().regex(/^[a-zA-Z0-9 \.,;\-]+$/),msg:"Has to be non empty."}]}}),window.modalView.modalTestAll()},h=function(a){window.modalView.clearValidators();var b=$("#modalButton1");switch(this._upgrade||e(),a){case"newApp":b.html("Generate"),b.prop("disabled",!1),g();break;case"appstore":b.html("Install"),b.prop("disabled",!0);break;case"github":f(),b.html("Install"),b.prop("disabled",!1);break;case"zip":b.html("Install"),b.prop("disabled",!1)}b.prop("disabled")||window.modalView.modalTestAll()||b.prop("disabled",!0)},i=function(a){var b=$(a.currentTarget).attr("href").substr(1);h.call(this,b)},j=function(a){if(h.call(this,"appstore"),window.modalView.modalTestAll()){var b,c;this._upgrade?(b=this.mount,c=$("#new-app-teardown").prop("checked")):b=window.arangoHelper.escapeHtml($("#new-app-mount").val());var e=$(a.currentTarget).attr("appId"),f=$(a.currentTarget).attr("appVersion");void 0!==c?this.collection.installFromStore({name:e,version:f},b,d.bind(this),c):this.collection.installFromStore({name:e,version:f},b,d.bind(this)),window.modalView.hide(),arangoHelper.arangoNotification("Services","Installing "+e+".")}},k=function(a,b){if(void 0===b?b=this._uploadData:this._uploadData=b,b&&window.modalView.modalTestAll()){var c,e;this._upgrade?(c=this.mount,e=$("#new-app-teardown").prop("checked")):c=window.arangoHelper.escapeHtml($("#new-app-mount").val()),void 0!==e?this.collection.installFromZip(b.filename,c,d.bind(this),e):this.collection.installFromZip(b.filename,c,d.bind(this))}},l=function(){if(window.modalView.modalTestAll()){var a,b,c,e;this._upgrade?(c=this.mount,e=$("#new-app-teardown").prop("checked")):c=window.arangoHelper.escapeHtml($("#new-app-mount").val()),a=window.arangoHelper.escapeHtml($("#repository").val()),b=window.arangoHelper.escapeHtml($("#tag").val()),""===b&&(b="master");var f={url:window.arangoHelper.escapeHtml($("#repository").val()),version:window.arangoHelper.escapeHtml($("#tag").val())};try{Joi.assert(a,Joi.string().regex(/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+$/))}catch(g){return}void 0!==e?this.collection.installFromGithub(f,c,d.bind(this),e):this.collection.installFromGithub(f,c,d.bind(this))}},m=function(){if(window.modalView.modalTestAll()){var a,b;this._upgrade?(a=this.mount,b=$("#new-app-teardown").prop("checked")):a=window.arangoHelper.escapeHtml($("#new-app-mount").val());var c={name:window.arangoHelper.escapeHtml($("#new-app-name").val()),documentCollections:_.map($("#new-app-document-collections").select2("data"),function(a){return window.arangoHelper.escapeHtml(a.text)}),edgeCollections:_.map($("#new-app-edge-collections").select2("data"),function(a){return window.arangoHelper.escapeHtml(a.text)}),author:window.arangoHelper.escapeHtml($("#new-app-author").val()),license:window.arangoHelper.escapeHtml($("#new-app-license").val()),description:window.arangoHelper.escapeHtml($("#new-app-description").val())};void 0!==b?this.collection.generate(c,a,d.bind(this),b):this.collection.generate(c,a,d.bind(this))}},n=function(){var a=$(".modal-body .tab-pane.active").attr("id");switch(a){case"newApp":m.apply(this);break;case"github":l.apply(this);break;case"zip":k.apply(this)}},o=function(a,c){var d=[],e={"click #infoTab a":i.bind(a),"click .install-app":j.bind(a)};d.push(window.modalView.createSuccessButton("Generate",n.bind(a))),window.modalView.show("modalApplicationMount.ejs","Install Service",d,c,void 0,void 0,e),$("#new-app-document-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"}),$("#new-app-edge-collections").select2({tags:[],showSearchBox:!1,minimumResultsForSearch:-1,width:"336px"});var f=function(){var a=$("#modalButton1");a.prop("disabled")||window.modalView.modalTestAll()?a.prop("disabled",!1):a.prop("disabled",!0)};$(".select2-search-field input").focusout(function(){f(),window.setTimeout(function(){$(".select2-drop").is(":visible")&&($("#select2-search-field input").is(":focus")||($("#s2id_new-app-document-collections").select2("close"),$("#s2id_new-app-edge-collections").select2("close"),f()))},200)}),$(".select2-search-field input").focusin(function(){if($(".select2-drop").is(":visible")){var a=$("#modalButton1");a.prop("disabled",!0)}}),$("#upload-foxx-zip").uploadFile({url:arangoHelper.databaseUrl("/_api/upload?multipart=true"),allowedTypes:"zip",multiple:!1,onSuccess:k.bind(a)}),$.get("foxxes/fishbowl",function(a){var c=$("#appstore-content");c.html(""),_.each(_.sortBy(a,"name"),function(a){c.append(b.render(a))})}).fail(function(){var a=$("#appstore-content");a.append("
Store is not available. ArangoDB is not able to connect to github.com
")})};c.prototype.install=function(a){this.reload=a,this._upgrade=!1,this._uploadData=void 0,delete this.mount,o(this,!1),window.modalView.clearValidators(),e(),g()},c.prototype.upgrade=function(a,b){this.reload=b,this._upgrade=!0,this._uploadData=void 0,this.mount=a,o(this,!0),window.modalView.clearValidators(),g()},window.FoxxInstallView=c}(),function(){"use strict";window.GraphManagementView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("graphManagementView.ejs"),edgeDefintionTemplate:templateEngine.createTemplate("edgeDefinitionTable.ejs"),eCollList:[],removedECollList:[],dropdownVisible:!1,initialize:function(a){this.options=a},events:{"click #deleteGraph":"deleteGraph","click .icon_arangodb_settings2.editGraph":"editGraph","click #createGraph":"addNewGraph","keyup #graphManagementSearchInput":"search","click #graphManagementSearchSubmit":"search","click .tile-graph":"redirectToGraphViewer","click #gv2":"redirectToGraphViewer2","click #graphManagementToggle":"toggleGraphDropdown","click .css-label":"checkBoxes","change #graphSortDesc":"sorting"},toggleTab:function(a){var b=a.currentTarget.id;b=b.replace("tab-",""),$("#tab-content-create-graph .tab-pane").removeClass("active"),$("#tab-content-create-graph #"+b).addClass("active"),"exampleGraphs"===b?$("#modal-dialog .modal-footer .button-success").css("display","none"):$("#modal-dialog .modal-footer .button-success").css("display","initial")},redirectToGraphViewer:function(a){var b=$(a.currentTarget).attr("id");b=b.substr(0,b.length-5),window.location.hash=window.location.hash.substr(0,window.location.hash.length-1)+"2/"+encodeURIComponent(b)},redirectToGraphViewer2:function(a){a.preventDefault();var b=$(a.currentTarget).parent().parent().attr("id");b=b.substr(0,b.length-5),console.log(b),window.App.navigate("graph2/"+encodeURIComponent(b),{trigger:!0})},loadGraphViewer:function(a,b){var c=function(b){if(b)arangoHelper.arangoError("","");else{var c=this.collection.get(a).get("edgeDefinitions");if(!c||0===c.length)return;var d={type:"gharial",graphName:a,baseUrl:arangoHelper.databaseUrl("/")},e=$("#content").width()-75;$("#content").html("");var f=arangoHelper.calculateCenterDivHeight();this.ui=new GraphViewerUI($("#content")[0],d,e,$(".centralRow").height()-135,{nodeShaper:{label:"_key",color:{type:"attribute",key:"_key"}}},!0),$(".contentDiv").height(f)}}.bind(this);b?this.collection.fetch({cache:!1,success:function(){c()}}):c()},handleResize:function(a){this.width&&this.width===a||(this.width=a,this.ui&&this.ui.changeWidth(a))},addNewGraph:function(a){a.preventDefault(),this.createEditGraphModal()},deleteGraph:function(){var a=this,b=$("#editGraphName")[0].value;if($("#dropGraphCollections").is(":checked")){var c=function(c){c?(a.collection.remove(a.collection.get(b)),a.updateGraphManagementView(),window.modalView.hide()):(window.modalView.hide(),arangoHelper.arangoError("Graph","Could not delete Graph."))};this.collection.dropAndDeleteGraph(b,c)}else this.collection.get(b).destroy({success:function(){a.updateGraphManagementView(),window.modalView.hide()},error:function(a,b){var c=JSON.parse(b.responseText),d=c.errorMessage;arangoHelper.arangoError(d),window.modalView.hide()}})},checkBoxes:function(a){var b=a.currentTarget.id;$("#"+b).click()},toggleGraphDropdown:function(){$("#graphSortDesc").attr("checked",this.collection.sortOptions.desc),$("#graphManagementToggle").toggleClass("activated"),$("#graphManagementDropdown2").slideToggle(200)},sorting:function(){$("#graphSortDesc").is(":checked")?this.collection.setSortingDesc(!0):this.collection.setSortingDesc(!1),$("#graphManagementDropdown").is(":visible")?this.dropdownVisible=!0:this.dropdownVisible=!1,this.render()},createExampleGraphs:function(a){var b=$(a.currentTarget).attr("graph-id"),c=this;$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_admin/aardvark/graph-examples/create/"+encodeURIComponent(b)),success:function(){window.modalView.hide(),c.updateGraphManagementView(),arangoHelper.arangoNotification("Example Graphs","Graph: "+b+" created.")},error:function(a){if(window.modalView.hide(),a.responseText)try{var c=JSON.parse(a.responseText);arangoHelper.arangoError("Example Graphs",c.errorMessage)}catch(d){arangoHelper.arangoError("Example Graphs","Could not create example graph: "+b)}else arangoHelper.arangoError("Example Graphs","Could not create example graph: "+b)}})},render:function(a,b){var c=this;return this.collection.fetch({cache:!1,success:function(){c.collection.sort(),$(c.el).html(c.template.render({graphs:c.collection,searchString:""})),c.dropdownVisible===!0&&($("#graphManagementDropdown2").show(),$("#graphSortDesc").attr("checked",c.collection.sortOptions.desc),$("#graphManagementToggle").toggleClass("activated"),$("#graphManagementDropdown").show()),c.events["click .tableRow"]=c.showHideDefinition.bind(c),c.events['change tr[id*="newEdgeDefinitions"]']=c.setFromAndTo.bind(c),c.events["click .graphViewer-icon-button"]=c.addRemoveDefinition.bind(c),c.events["click #graphTab a"]=c.toggleTab.bind(c),c.events["click .createExampleGraphs"]=c.createExampleGraphs.bind(c),c.events["focusout .select2-search-field input"]=function(a){$(".select2-drop").is(":visible")&&($("#select2-search-field input").is(":focus")||window.setTimeout(function(){$(a.currentTarget).parent().parent().parent().select2("close")},200))},arangoHelper.setCheckboxStatus("#graphManagementDropdown")}}),a&&this.loadGraphViewer(a,b),this},setFromAndTo:function(a){a.stopPropagation();var b,c=this.calculateEdgeDefinitionMap();if(a.added){if(-1===this.eCollList.indexOf(a.added.id)&&-1!==this.removedECollList.indexOf(a.added.id))return b=a.currentTarget.id.split("row_newEdgeDefinitions")[1],$('input[id*="newEdgeDefinitions'+b+'"]').select2("val",null),void $('input[id*="newEdgeDefinitions'+b+'"]').attr("placeholder","The collection "+a.added.id+" is already used.");this.removedECollList.push(a.added.id),this.eCollList.splice(this.eCollList.indexOf(a.added.id),1)}else this.eCollList.push(a.removed.id),this.removedECollList.splice(this.removedECollList.indexOf(a.removed.id),1);c[a.val]?(b=a.currentTarget.id.split("row_newEdgeDefinitions")[1],$("#s2id_fromCollections"+b).select2("val",c[a.val].from),$("#fromCollections"+b).attr("disabled",!0),$("#s2id_toCollections"+b).select2("val",c[a.val].to),$("#toCollections"+b).attr("disabled",!0)):(b=a.currentTarget.id.split("row_newEdgeDefinitions")[1],$("#s2id_fromCollections"+b).select2("val",null),$("#fromCollections"+b).attr("disabled",!1),$("#s2id_toCollections"+b).select2("val",null),$("#toCollections"+b).attr("disabled",!1))},editGraph:function(a){a.stopPropagation(),this.collection.fetch({cache:!1}),this.graphToEdit=this.evaluateGraphName($(a.currentTarget).attr("id"),"_settings");var b=this.collection.findWhere({_key:this.graphToEdit});this.createEditGraphModal(b)},saveEditedGraph:function(){var a,b,c,d,e,f=$("#editGraphName")[0].value,g=_.pluck($("#newVertexCollections").select2("data"),"text"),h=[],i={};if(e=$("[id^=s2id_newEdgeDefinitions]").toArray(),e.forEach(function(e){if(d=$(e).attr("id"),d=d.replace("s2id_newEdgeDefinitions",""),a=_.pluck($("#s2id_newEdgeDefinitions"+d).select2("data"),"text")[0],a&&""!==a&&(b=_.pluck($("#s2id_fromCollections"+d).select2("data"),"text"),c=_.pluck($("#s2id_toCollections"+d).select2("data"),"text"),0!==b.length&&0!==c.length)){var f={collection:a,from:b,to:c};h.push(f),i[a]=f}}),0===h.length)return $("#s2id_newEdgeDefinitions0 .select2-choices").css("border-color","red"),$("#s2id_newEdgeDefinitions0").parent().parent().next().find(".select2-choices").css("border-color","red"),void $("#s2id_newEdgeDefinitions0").parent().parent().next().next().find(".select2-choices").css("border-color","red");var j=this.collection.findWhere({_key:f}),k=j.get("edgeDefinitions"),l=j.get("orphanCollections"),m=[];l.forEach(function(a){-1===g.indexOf(a)&&j.deleteVertexCollection(a)}),g.forEach(function(a){-1===l.indexOf(a)&&j.addVertexCollection(a)});var n=[],o=[],p=[];k.forEach(function(a){var b=a.collection;m.push(b);var c=i[b];void 0===c?p.push(b):JSON.stringify(c)!==JSON.stringify(a)&&o.push(b)}),h.forEach(function(a){var b=a.collection;-1===m.indexOf(b)&&n.push(b)}),n.forEach(function(a){j.addEdgeDefinition(i[a])}),o.forEach(function(a){j.modifyEdgeDefinition(i[a])}),p.forEach(function(a){j.deleteEdgeDefinition(a)}),this.updateGraphManagementView(),window.modalView.hide()},evaluateGraphName:function(a,b){var c=a.lastIndexOf(b);return a.substring(0,c)},search:function(){var a,b,c,d;a=$("#graphManagementSearchInput"),b=$("#graphManagementSearchInput").val(),d=this.collection.filter(function(a){return-1!==a.get("_key").indexOf(b)}),$(this.el).html(this.template.render({graphs:d,searchString:b})),a=$("#graphManagementSearchInput"),c=a.val().length,a.focus(),a[0].setSelectionRange(c,c)},updateGraphManagementView:function(){var a=this;this.collection.fetch({cache:!1,success:function(){a.render()}})},createNewGraph:function(){var a,b,c,d,e,f=$("#createNewGraphName").val(),g=_.pluck($("#newVertexCollections").select2("data"),"text"),h=[],i=this;return f?this.collection.findWhere({_key:f})?(arangoHelper.arangoError("The graph '"+f+"' already exists."),0):(e=$("[id^=s2id_newEdgeDefinitions]").toArray(),e.forEach(function(e){d=$(e).attr("id"),d=d.replace("s2id_newEdgeDefinitions",""),a=_.pluck($("#s2id_newEdgeDefinitions"+d).select2("data"),"text")[0],a&&""!==a&&(b=_.pluck($("#s2id_fromCollections"+d).select2("data"),"text"),c=_.pluck($("#s2id_toCollections"+d).select2("data"),"text"),1!==b&&1!==c&&h.push({collection:a,from:b,to:c}))}),0===h.length?($("#s2id_newEdgeDefinitions0 .select2-choices").css("border-color","red"),$("#s2id_newEdgeDefinitions0").parent().parent().next().find(".select2-choices").css("border-color","red"),void $("#s2id_newEdgeDefinitions0").parent().parent().next().next().find(".select2-choices").css("border-color","red")):void this.collection.create({name:f,edgeDefinitions:h,orphanCollections:g},{success:function(){i.updateGraphManagementView(),window.modalView.hide()},error:function(a,b){var c=JSON.parse(b.responseText),d=c.errorMessage;d=d.replace("<",""),d=d.replace(">",""),arangoHelper.arangoError(d)}})):(arangoHelper.arangoError("A name for the graph has to be provided."),0)},createEditGraphModal:function(a){var b,c=[],d=[],e=[],f=this.options.collectionCollection.models,g=this,h="",i=[{collection:"",from:"",to:""}],j="",k=function(a,b){return a=a.toLowerCase(),b=b.toLowerCase(),b>a?-1:a>b?1:0};if(this.eCollList=[],this.removedECollList=[],f.forEach(function(a){a.get("isSystem")||("edge"===a.get("type")?g.eCollList.push(a.id):d.push(a.id))}),window.modalView.enableHotKeys=!1,this.counter=0,a?(b="Edit Graph",h=a.get("_key"),i=a.get("edgeDefinitions"),i&&0!==i.length||(i=[{collection:"",from:"",to:""}]),j=a.get("orphanCollections"),e.push(window.modalView.createReadOnlyEntry("editGraphName","Name",h,"The name to identify the graph. Has to be unique")),c.push(window.modalView.createDeleteButton("Delete",this.deleteGraph.bind(this))),c.push(window.modalView.createSuccessButton("Save",this.saveEditedGraph.bind(this)))):(b="Create Graph",e.push(window.modalView.createTextEntry("createNewGraphName","Name","","The name to identify the graph. Has to be unique.","graphName",!0)),c.push(window.modalView.createSuccessButton("Create",this.createNewGraph.bind(this)))),i.forEach(function(a){0===g.counter?(a.collection&&(g.removedECollList.push(a.collection),g.eCollList.splice(g.eCollList.indexOf(a.collection),1)),e.push(window.modalView.createSelect2Entry("newEdgeDefinitions"+g.counter,"Edge definitions",a.collection,"An edge definition defines a relation of the graph","Edge definitions",!0,!1,!0,1,g.eCollList.sort(k)))):e.push(window.modalView.createSelect2Entry("newEdgeDefinitions"+g.counter,"Edge definitions",a.collection,"An edge definition defines a relation of the graph","Edge definitions",!1,!0,!1,1,g.eCollList.sort(k))),e.push(window.modalView.createSelect2Entry("fromCollections"+g.counter,"fromCollections",a.from,"The collections that contain the start vertices of the relation.","fromCollections",!0,!1,!1,10,d.sort(k))),e.push(window.modalView.createSelect2Entry("toCollections"+g.counter,"toCollections",a.to,"The collections that contain the end vertices of the relation.","toCollections",!0,!1,!1,10,d.sort(k))),g.counter++}),e.push(window.modalView.createSelect2Entry("newVertexCollections","Vertex collections",j,"Collections that are part of a graph but not used in an edge definition","Vertex Collections",!1,!1,!1,10,d.sort(k))),window.modalView.show("modalGraphTable.ejs",b,c,e,void 0,void 0,this.events),a){$(".modal-body table").css("border-collapse","separate");var l;for($(".modal-body .spacer").remove(),l=0;l<=this.counter;l++)$("#row_fromCollections"+l).show(),$("#row_toCollections"+l).show(),$("#row_newEdgeDefinitions"+l).addClass("first"),$("#row_fromCollections"+l).addClass("middle"),$("#row_toCollections"+l).addClass("last"),$("#row_toCollections"+l).after('
')}},calculateEdgeDefinitionMap:function(){var a={};return this.collection.models.forEach(function(b){b.get("edgeDefinitions").forEach(function(b){a[b.collection]={from:b.from,to:b.to}})}),a}})}(),function(){"use strict";window.GraphSettingsView=Backbone.View.extend({el:"#graphSettingsContent",remove:function(){return this.$el.empty().off(),this.stopListening(),this},general:{graph:{type:"divider",name:"Graph"},nodeStart:{type:"string",name:"Starting node",desc:"A valid node id. If empty, a random node will be chosen.",value:2},layout:{type:"select",name:"Layout algorithm",desc:"Different graph algorithms. No overlap is very fast, force is slower and fruchtermann is the slowest. The calculation time strongly depends on your nodes and edges counts.",noverlap:{name:"No overlap",val:"noverlap"},force:{name:"Force",val:"force"},fruchtermann:{name:"Fruchtermann",val:"fruchtermann"}},renderer:{type:"select",name:"Renderer",desc:"Canvas enables editing, WebGL is only for displaying a graph but much faster.",canvas:{name:"Canvas",val:"canvas"},webgl:{name:"WebGL",val:"webgl"}},depth:{desc:"Search depth, starting from your start node.",type:"number",name:"Search depth",value:2}},specific:{nodes:{type:"divider",name:"Nodes"},nodeLabel:{type:"string",name:"Label",desc:"Node label. Please choose a valid and available node attribute.","default":"_key"},nodeLabelByCollection:{type:"select",name:"Label by coll?",desc:"Set label text by collection. If activated node label attribute will be ignored.",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},nodeLabelThreshold:{type:"range",name:"Label threshold",desc:"The minimum size a node must have on screen to see its label displayed. This does not affect hovering behavior.","default":"_key"},nodeColor:{type:"color",name:"Color",desc:"Default node color. RGB or HEX value.","default":"#2ecc71"},nodeColorAttribute:{type:"string",name:"Colorize attr",desc:"If an attribute is given, nodes will then be colorized by the attribute. This setting ignores default node color if set."},nodeColorByCollection:{type:"select",name:"Colorize by coll?",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should nodes be colorized by their collection? If enabled, node color and node color attribute will be ignored."},nodeSize:{type:"string",name:"Sizing attribute",desc:"Default node size. Numeric value > 0."},edges:{type:"divider",name:"Edges"},edgeLabel:{type:"string",name:"Label",desc:"Default edge label."},edgeLabelByCollection:{type:"select",name:"Label by coll?",desc:"Set label text by collection. If activated edge label attribute will be ignored.",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},edgeLabelThreshold:{type:"range",name:"Label threshold",desc:"The minimum size an edge must have on screen to see its label displayed. This does not affect hovering behavior.","default":"_key"},edgeColor:{type:"color",name:"Color",desc:"Default edge color. RGB or HEX value.","default":"#cccccc"},edgeColorAttribute:{type:"string",name:"Colorize attr",desc:"If an attribute is given, edges will then be colorized by the attribute. This setting ignores default edge color if set."
+},edgeColorByCollection:{type:"select",name:"Colorize by coll?",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should edges be colorized by their collection? If enabled, edge color and edge color attribute will be ignored."},edgeEditable:{type:"select",name:"Editable",no:{name:"No",val:"false"},yes:{name:"Yes",val:"true"},desc:"Should edges be editable?"},edgeType:{type:"select",name:"Type",desc:"The type of the edge",line:{name:"Line",val:"line"},arrow:{name:"Arrow",val:"arrow"},curve:{name:"Curve",val:"curve"},dotted:{name:"Dotted",val:"dotted"},dashed:{name:"Dashed",val:"dashed"},tapered:{name:"Tapered",val:"tapered"}}},template:templateEngine.createTemplate("graphSettingsView.ejs"),initialize:function(a){this.name=a.name,this.userConfig=a.userConfig,this.saveCallback=a.saveCallback},events:{"click #saveGraphSettings":"saveGraphSettings","click #restoreGraphSettings":"setDefaults","keyup #graphSettingsView input":"checkEnterKey","keyup #graphSettingsView select":"checkEnterKey",'change input[type="range"]':"saveGraphSettings",'change input[type="color"]':"checkColor","change select":"saveGraphSettings","focus #graphSettingsView input":"lastFocus","focus #graphSettingsView select":"lastFocus"},lastFocus:function(a){this.lastFocussed=a.currentTarget.id},checkEnterKey:function(a){13===a.keyCode&&this.saveGraphSettings()},getGraphSettings:function(a){var b=this,c=window.App.currentDB.toJSON().name+"_"+this.name;this.userConfig.fetch({success:function(d){b.graphConfig=d.toJSON().graphs[c],a&&b.continueRender()}})},checkColor:function(){this.saveGraphSettings(null,!0)},saveGraphSettings:function(a,b,c,d){var e=this,f=window.App.currentDB.toJSON().name+"_"+this.name,g={};if(d)g[f]=d;else{var h,i={};$("#graphSettingsView select").each(function(a,b){h=b.id,i[h.substr(2,b.id.length)]=$(b).val()}),$("#graphSettingsView input").each(function(a,b){h=b.id,i[h.substr(2,b.id.length)]=$(b).val()}),g[f]=i}c&&(g[f].nodeStart=c);var j=function(){window.App.graphViewer2?""!==b&&void 0!==b?window.App.graphViewer2.updateColors():window.App.graphViewer2.render(e.lastFocussed):arangoHelper.arangoNotification("Graph "+this.name,"Configuration saved.")}.bind(this);this.userConfig.setItem("graphs",g,j)},setDefaults:function(){var a={layout:"force",renderer:"canvas",depth:"2",nodeColor:"#2ecc71",nodeColorAttribute:"",nodeColorByCollection:"false",nodeLabelThreshold:10,edgeColor:"#cccccc",edgeColorAttribute:"",edgeColorByCollection:"false",edgeLabelThreshold:10,nodeLabel:"_key",edgeLabel:"",edgeType:"line",nodeSize:"",edgeEditable:"false",nodeLabelByCollection:"true",edgeLabelByCollection:"true",nodeStart:""};this.saveGraphSettings(null,null,null,a),this.render(),window.App.graphViewer2.render(this.lastFocussed)},toggle:function(){$(this.el).is(":visible")?this.hide():this.show()},show:function(){$(this.el).show("slide",{direction:"right"},250)},hide:function(){$(this.el).hide("slide",{direction:"right"},250)},render:function(){this.getGraphSettings(!0)},continueRender:function(){$(this.el).html(this.template.render({general:this.general,specific:this.specific})),arangoHelper.fixTooltips(".gv-tooltips","top"),this.graphConfig?(_.each(this.graphConfig,function(a,b){$("#g_"+b).val(a)}),$("#g_nodeLabelThreshold_label").text(this.graphConfig.nodeLabelThreshold),$("#g_edgeLabelThreshold_label").text(this.graphConfig.edgeLabelThreshold)):this.setDefaults()}})}(),function(){"use strict";window.GraphViewer2=Backbone.View.extend({el:"#content",remove:function(){return this.$el.empty().off(),this.stopListening(),this},template:templateEngine.createTemplate("graphViewer2.ejs"),initialize:function(a){var b=this;a.id&&(this.setElement(a.id),this.graphData=a.data,this.aqlMode=!0),this.name=a.name,this.userConfig=a.userConfig,this.documentStore=a.documentStore,this.initSigma(),void 0!==this.name&&this.collection.fetch({cache:!1,success:function(c){b.model=b.collection.findWhere({_key:a.name}).toJSON()}})},colors:{hotaru:["#364C4A","#497C7F","#92C5C0","#858168","#CCBCA5"],random1:["#292F36","#4ECDC4","#F7FFF7","#DD6363","#FFE66D"]},selectedNodes:{},aqlMode:!1,events:{"click #downloadPNG":"downloadSVG","click #reloadGraph":"reloadGraph","click #settingsMenu":"toggleSettings","click #noGraphToggle":"toggleSettings","click #toggleForce":"toggleLayout","click #selectNodes":"toggleLasso"},cursorX:0,cursorY:0,layouting:!1,model:null,viewStates:{captureMode:!1},graphConfig:null,graphSettings:null,initSigma:function(){try{sigma.classes.graph.addMethod("neighbors",function(a){var b,c={},d=this.allNeighborsIndex[a]||{};for(b in d)c[b]=this.nodesIndex[b];return c}),sigma.classes.graph.addMethod("getNodeEdges",function(a){var b=this.edges(),c=[];return _.each(b,function(b){b.source!==a&&b.target!==a||c.push(b.id)}),c})}catch(a){}},downloadSVG:function(){var a=parseInt($("#graph-container").width(),10);sigma.plugins.image(this.currentGraph,this.currentGraph.renderers[0],{download:!0,size:a,background:"white",zoom:!0})},resize:function(){$("#graph-container").width($(".centralContent").width()),$("#graph-container").height($(".centralRow").height()-150)},toggleSettings:function(){this.graphSettingsView.toggle()},render:function(a){this.$el.html(this.template.render({})),$("#subNavigationBar .breadcrumb").html("Graph: "+this.name),this.resize(),this.fetchGraph(a)},renderAQL:function(a){this.$el.html(this.template.render({})),this.$el.find(".headerBar").remove();var b=$(".centralRow").height()-250;this.$el.find("#graph-container").css("height",b),this.graphData.modified=this.parseData(this.graphData.original,this.graphData.graphInfo),this.renderGraph(this.graphData.modified)},parseData:function(a,b){var c={},d={},e={nodes:[],edges:[],settings:{}};return"object"===b?(_.each(a,function(a){a.edges&&a.vertices&&(_.each(a.edges,function(a){d[a._id]={id:a._id,source:a._from,label:a._key,color:"#cccccc",target:a._to}}),_.each(a.vertices,function(a){c[a._id]={id:a._id,label:a._key,size:.3,color:"#2ecc71",x:Math.random(),y:Math.random()}}))}),_.each(c,function(a){e.nodes.push(a)}),_.each(d,function(a){e.edges.push(a)})):"array"===b&&(_.each(a,function(a){c[a._from]=null,c[a._to]=null,e.edges.push({id:a._id,source:a._from,label:a._key,color:"#cccccc",target:a._to})}),_.each(c,function(a,b){e.nodes.push({id:b,label:b,size:.3,color:"#2ecc71",x:Math.random(),y:Math.random()})})),e},rerender:function(){this.fetchGraph()},fetchGraph:function(a){var b=this;$(this.el).append('
Fetching graph data. Please wait ... If it`s taking too much time to draw the graph, please go to: '+window.location.href+"/settings and adjust your settings.It is possible that the graph is too big to be handled by the browser.
')},fillBindParamTable:function(a){_.each(a,function(a,b){_.each($("#arangoBindParamTable input"),function(c){$(c).attr("name")===b&&$(c).val(a)})})},initAce:function(){var a=this;this.aqlEditor=ace.edit("aqlEditor"),this.aqlEditor.getSession().setMode("ace/mode/aql"),this.aqlEditor.setFontSize("10pt"),this.aqlEditor.setShowPrintMargin(!1),this.bindParamAceEditor=ace.edit("bindParamAceEditor"),this.bindParamAceEditor.getSession().setMode("ace/mode/json"),this.bindParamAceEditor.setFontSize("10pt"),this.bindParamAceEditor.setShowPrintMargin(!1),this.bindParamAceEditor.getSession().on("change",function(){try{a.bindParamTableObj=JSON.parse(a.bindParamAceEditor.getValue()),a.allowParamToggle=!0,a.setCachedQuery(a.aqlEditor.getValue(),JSON.stringify(a.bindParamTableObj))}catch(b){""===a.bindParamAceEditor.getValue()?(_.each(a.bindParamTableObj,function(b,c){a.bindParamTableObj[c]=""}),a.allowParamToggle=!0):a.allowParamToggle=!1}}),this.aqlEditor.getSession().on("change",function(){a.checkForNewBindParams(),a.renderBindParamTable(),a.initDone&&a.setCachedQuery(a.aqlEditor.getValue(),JSON.stringify(a.bindParamTableObj)),a.bindParamAceEditor.setValue(JSON.stringify(a.bindParamTableObj,null," "),1),$("#aqlEditor .ace_text-input").focus(),a.resize()}),this.aqlEditor.commands.addCommand({name:"togglecomment",bindKey:{win:"Ctrl-Shift-C",linux:"Ctrl-Shift-C",mac:"Command-Shift-C"},exec:function(a){a.toggleCommentLines()},multiSelectAction:"forEach"}),this.aqlEditor.commands.addCommand({name:"executeQuery",bindKey:{win:"Ctrl-Return",mac:"Command-Return",linux:"Ctrl-Return"},exec:function(){a.executeQuery()}}),this.aqlEditor.commands.addCommand({name:"executeSelectedQuery",bindKey:{win:"Ctrl-Alt-Return",mac:"Command-Alt-Return",linux:"Ctrl-Alt-Return"},exec:function(){a.executeQuery(!0)}}),this.aqlEditor.commands.addCommand({name:"saveQuery",bindKey:{win:"Ctrl-Shift-S",mac:"Command-Shift-S",linux:"Ctrl-Shift-S"},exec:function(){a.addAQL()}}),this.aqlEditor.commands.addCommand({name:"explainQuery",bindKey:{win:"Ctrl-Shift-Return",mac:"Command-Shift-Return",linux:"Ctrl-Shift-Return"},exec:function(){a.explainQuery()}}),this.aqlEditor.commands.addCommand({name:"togglecomment",bindKey:{win:"Ctrl-Shift-C",linux:"Ctrl-Shift-C",mac:"Command-Shift-C"},exec:function(a){a.toggleCommentLines()},multiSelectAction:"forEach"}),this.aqlEditor.commands.addCommand({name:"showSpotlight",bindKey:{win:"Ctrl-Space",mac:"Ctrl-Space",linux:"Ctrl-Space"},exec:function(){a.showSpotlight()}}),this.queryPreview=ace.edit("queryPreview"),this.queryPreview.getSession().setMode("ace/mode/aql"),this.queryPreview.setReadOnly(!0),this.queryPreview.setFontSize("13px"),$("#aqlEditor .ace_text-input").focus()},updateQueryTable:function(){function a(a,b){var c;return c=a.nameb.name?1:0}var b=this;this.updateLocalQueries(),this.myQueriesTableDesc.rows=this.customQueries,_.each(this.myQueriesTableDesc.rows,function(a){a.secondRow='',a.hasOwnProperty("parameter")&&delete a.parameter,delete a.value}),this.myQueriesTableDesc.rows.sort(a),_.each(this.queries,function(a){a.hasOwnProperty("parameter")&&delete a.parameter,b.myQueriesTableDesc.rows.push({name:a.name,thirdRow:''})}),this.myQueriesTableDesc.unescaped=[!1,!0,!0],this.$(this.myQueriesId).html(this.table.render({content:this.myQueriesTableDesc}))},listenKey:function(a){13===a.keyCode&&"Update"===$("#modalButton1").html()&&this.saveAQL(),this.checkSaveName()},addAQL:function(){this.refreshAQL(!0),this.createCustomQueryModal(),setTimeout(function(){$("#new-query-name").focus()},500)},createCustomQueryModal:function(){var a=[],b=[];b.push(window.modalView.createTextEntry("new-query-name","Name","",void 0,void 0,!1,[{rule:Joi.string().required(),msg:"No query name given."}])),a.push(window.modalView.createSuccessButton("Save",this.saveAQL.bind(this))),window.modalView.show("modalTable.ejs","Save Query",a,b,void 0,void 0,{"keyup #new-query-name":this.listenKey.bind(this)})},checkSaveName:function(){var a=$("#new-query-name").val();if("Insert Query"===a)return void $("#new-query-name").val("");var b=this.customQueries.some(function(b){return b.name===a});b?($("#modalButton1").removeClass("button-success"),$("#modalButton1").addClass("button-warning"),$("#modalButton1").text("Update")):($("#modalButton1").removeClass("button-warning"),$("#modalButton1").addClass("button-success"),$("#modalButton1").text("Save"))},saveAQL:function(a){a&&a.stopPropagation(),this.refreshAQL();var b=$("#new-query-name").val(),c=this.bindParamTableObj;if(!$("#new-query-name").hasClass("invalid-input")&&""!==b.trim()){var d=this.aqlEditor.getValue(),e=!1;if(_.each(this.customQueries,function(a){return a.name===b?(a.value=d,void(e=!0)):void 0}),e===!0)this.collection.findWhere({name:b}).set("value",d);else{if(""!==c&&void 0!==c||(c="{}"),"string"==typeof c)try{c=JSON.parse(c)}catch(f){arangoHelper.arangoError("Query","Could not parse bind parameter")}this.collection.add({name:b,parameter:c,value:d})}var g=function(a){if(a)arangoHelper.arangoError("Query","Could not save query");else{var b=this;this.collection.fetch({success:function(){b.updateLocalQueries()}})}}.bind(this);this.collection.saveCollectionQueries(g),window.modalView.hide()}},verifyQueryAndParams:function(){var a=!1;0===this.aqlEditor.getValue().length&&(arangoHelper.arangoError("Query","Your query is empty"),a=!0);var b=[];return _.each(this.bindParamTableObj,function(c,d){""===c&&(a=!0,b.push(d))}),b.length>0&&arangoHelper.arangoError("Bind Parameter",JSON.stringify(b)+" not defined."),a},executeQuery:function(a){if(!this.verifyQueryAndParams()){this.$(this.outputDiv).prepend(this.outputTemplate.render({counter:this.outputCounter,type:"Query"})),$("#outputEditorWrapper"+this.outputCounter).hide(),$("#outputEditorWrapper"+this.outputCounter).show("fast");var b=this.outputCounter,c=ace.edit("outputEditor"+b),d=ace.edit("sentQueryEditor"+b),e=ace.edit("sentBindParamEditor"+b);d.getSession().setMode("ace/mode/aql"),d.setOption("vScrollBarAlwaysVisible",!0),d.setFontSize("13px"),d.setReadOnly(!0),this.setEditorAutoHeight(d),c.setFontSize("13px"),c.getSession().setMode("ace/mode/json"),c.setReadOnly(!0),c.setOption("vScrollBarAlwaysVisible",!0),c.setShowPrintMargin(!1),this.setEditorAutoHeight(c),e.setValue(JSON.stringify(this.bindParamTableObj),1),e.setOption("vScrollBarAlwaysVisible",!0),e.getSession().setMode("ace/mode/json"),e.setReadOnly(!0),this.setEditorAutoHeight(e),this.fillResult(c,d,b,a),this.outputCounter++}},readQueryData:function(a){var b=$("#querySize"),c={id:"currentFrontendQuery"};return a?c.query=this.aqlEditor.getSelectedText():c.query=this.aqlEditor.getValue(),"all"===b.val()?c.batchSize=1e6:c.batchSize=parseInt(b.val(),10),Object.keys(this.bindParamTableObj).length>0&&(c.bindVars=this.bindParamTableObj),JSON.stringify(c)},fillResult:function(a,b,c,d){var e=this,f=this.readQueryData(d);f&&(b.setValue(e.aqlEditor.getValue(),1),$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_api/cursor"),headers:{"x-arango-async":"store"},data:f,contentType:"application/json",processData:!1,success:function(b,d,f){f.getResponseHeader("x-arango-async-id")&&e.queryCallbackFunction(f.getResponseHeader("x-arango-async-id"),a,c),$.noty.clearQueue(),$.noty.closeAll(),e.handleResult(c)},error:function(a){try{var b=JSON.parse(a.responseText);arangoHelper.arangoError("["+b.errorNum+"]",b.errorMessage)}catch(d){arangoHelper.arangoError("Query error","ERROR")}e.handleResult(c)}}))},handleResult:function(){var a=this;window.progressView.hide(),$("#removeResults").show(),window.setTimeout(function(){a.aqlEditor.focus()},300),$(".centralRow").animate({scrollTop:$("#queryContent").height()},"fast")},setEditorAutoHeight:function(a){var b=$(".centralRow").height(),c=(b-250)/17;a.setOptions({maxLines:c,minLines:10})},deselect:function(a){var b=a.getSelection(),c=b.lead.row,d=b.lead.column;b.setSelectionRange({start:{row:c,column:d},end:{row:c,column:d}}),a.focus()},queryCallbackFunction:function(a,b,c){var d=this,e=function(a,b){$.ajax({url:arangoHelper.databaseUrl("/_api/job/"+encodeURIComponent(a)+"/cancel"),type:"PUT",success:function(){window.clearTimeout(d.checkQueryTimer),$("#outputEditorWrapper"+b).remove(),arangoHelper.arangoNotification("Query","Query canceled.")}})};$("#outputEditorWrapper"+c+" #cancelCurrentQuery").bind("click",function(){e(a,c)}),$("#outputEditorWrapper"+c+" #copy2aqlEditor").bind("click",function(){$("#toggleQueries1").is(":visible")||d.toggleQueries();var a=ace.edit("sentQueryEditor"+c).getValue(),b=JSON.parse(ace.edit("sentBindParamEditor"+c).getValue());d.aqlEditor.setValue(a,1),d.deselect(d.aqlEditor),Object.keys(b).length>0&&(d.bindParamTableObj=b,d.setCachedQuery(d.aqlEditor.getValue(),JSON.stringify(d.bindParamTableObj)),$("#bindParamEditor").is(":visible")?d.renderBindParamTable():(d.bindParamAceEditor.setValue(JSON.stringify(b),1),d.deselect(d.bindParamAceEditor))),$(".centralRow").animate({scrollTop:0},"fast"),d.resize()}),this.execPending=!1;var f=function(a){var c="";a.extra&&a.extra.warnings&&a.extra.warnings.length>0&&(c+="Warnings:\r\n\r\n",
+a.extra.warnings.forEach(function(a){c+="["+a.code+"], '"+a.message+"'\r\n"})),""!==c&&(c+="\r\nResult:\r\n\r\n"),b.setValue(c+JSON.stringify(a.result,void 0,2),1),b.getSession().setScrollTop(0)},g=function(a){f(a),window.progressView.hide();var e=d.analyseQuery(a.result);if(console.log("Using "+e.defaultType+" as data format."),"table"===e.defaultType){$("#outputEditorWrapper"+c+" .arangoToolbarTop").after(''),$("#outputTable"+c).show(),d.renderOutputTable(e,c);var g=$(".centralRow").height()-250;$(".outputEditorWrapper .tableWrapper").css("max-height",g),$("#outputEditor"+c).hide()}else"graph"===e.defaultType&&($("#outputEditorWrapper"+c+" .arangoToolbarTop").after(''),$("#outputGraph"+c).show(),d.renderOutputGraph(e,c),$("#outputEditor"+c).hide());$("#"+e.defaultType+"-switch").addClass("active").css("display","inline");var h=function(a,b,d){d||(d=""),$("#outputEditorWrapper"+c+" .arangoToolbarTop .pull-left").append(''+a+"")};$("#outputEditorWrapper"+c+" .pull-left #spinner").remove();var i="-";a&&a.extra&&a.extra.stats&&(i=a.extra.stats.executionTime.toFixed(3)+" s"),h(a.result.length+" elements","fa-calculator"),h(i,"fa-clock-o"),a.extra&&a.extra.stats&&(a.extra.stats.writesExecuted>0||a.extra.stats.writesIgnored>0)&&(h(a.extra.stats.writesExecuted+" writes","fa-check-circle positive"),0===a.extra.stats.writesIgnored?h(a.extra.stats.writesIgnored+" writes ignored","fa-check-circle positive","additional"):h(a.extra.stats.writesIgnored+" writes ignored","fa-exclamation-circle warning","additional")),$("#outputEditorWrapper"+c+" .switchAce").show(),$("#outputEditorWrapper"+c+" .fa-close").show(),$("#outputEditor"+c).css("opacity","1"),$("#outputEditorWrapper"+c+" #downloadQueryResult").show(),$("#outputEditorWrapper"+c+" #copy2aqlEditor").show(),$("#outputEditorWrapper"+c+" #cancelCurrentQuery").remove(),d.setEditorAutoHeight(b),d.deselect(b),a.id&&$.ajax({url:"/_api/cursor/"+encodeURIComponent(a.id),type:"DELETE"})},h=function(){$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_api/job/"+encodeURIComponent(a)),contentType:"application/json",processData:!1,success:function(a,b,c){201===c.status?g(a):204===c.status&&(d.checkQueryTimer=window.setTimeout(function(){h()},500))},error:function(a){var b;try{if("Gone"===a.statusText)return arangoHelper.arangoNotification("Query","Query execution aborted."),void d.removeOutputEditor(c);b=JSON.parse(a.responseText),arangoHelper.arangoError("Query",b.errorMessage),b.errorMessage&&(null!==b.errorMessage.match(/\d+:\d+/g)?d.markPositionError(b.errorMessage.match(/'.*'/g)[0],b.errorMessage.match(/\d+:\d+/g)[0]):d.markPositionError(b.errorMessage.match(/\(\w+\)/g)[0]),d.removeOutputEditor(c))}catch(e){if(d.removeOutputEditor(c),409===b.code)return;400!==b.code&&404!==b.code&&arangoHelper.arangoNotification("Query","Successfully aborted.")}window.progressView.hide()}})};h()},analyseQuery:function(a){var b={defaultType:null,original:a,modified:null},c=!1;if(a[0])if(a[0].vertices&&a[0].edges){var d=0,e=0;_.each(a,function(a){a.edges&&(e+=a.edges.length,_.each(a.edges,function(a){a._from&&a._to&&d++}))});var f=d/e*100;f>=95&&(c=!0,b.defaultType="graph",b.graphInfo="object")}else{var g=0,h=a.length;_.each(a,function(a){a._from&&a._to&&g++});var i=g/h*100;i>=95&&(c=!0,b.defaultType="graph",b.graphInfo="array")}if(!c){var j,k=0,l=!0,m={};if(a.length<=1&&(l=!1),l){_.each(a,function(a){j=_.keys(a).length,j>k&&(k=j),_.each(a,function(a,b){m[b]?m[b]=m[b]+1:m[b]=1})});var n;_.each(m,function(b,c){n=b/a.length*100,l!==!1&&95>=n&&(l=!1)})}l&&(c=!0,b.defaultType="table")}return c||(b.defaultType="json"),b},markPositionError:function(a,b){var c;b&&(c=b.split(":")[0],a=a.substr(1,a.length-2));var d=this.aqlEditor.find(a);!d&&b&&(this.aqlEditor.selection.moveCursorToPosition({row:c,column:0}),this.aqlEditor.selection.selectLine()),window.setTimeout(function(){$(".ace_start").first().css("background","rgba(255, 129, 129, 0.7)")},100)},refreshAQL:function(){var a=this,b=function(b){b?arangoHelper.arangoError("Query","Could not reload Queries"):(a.updateLocalQueries(),a.updateQueryTable())},c=function(){a.getSystemQueries(b)};this.getAQL(c)},getSystemQueries:function(a){var b=this;$.ajax({type:"GET",cache:!1,url:"js/arango/aqltemplates.json",contentType:"application/json",processData:!1,success:function(c){a&&a(!1),b.queries=c},error:function(){a&&a(!0),arangoHelper.arangoNotification("Query","Error while loading system templates")}})},updateLocalQueries:function(){var a=this;this.customQueries=[],this.collection.each(function(b){a.customQueries.push({name:b.get("name"),value:b.get("value"),parameter:b.get("parameter")})})},renderOutputTable:function(a,b){var c={id:"outputTableData"+b,titles:[],rows:[]},d=!0,e=[];_.each(a.original,function(a){d===!0&&(c.titles=Object.keys(a),d=!1),_.each(a,function(a){"object"==typeof a&&(a=JSON.stringify(a)),e.push(a)}),c.rows.push(e),e=[]}),$("#outputTable"+b).append(this.table.render({content:c}))},renderOutputGraph:function(a,b){this.graphViewer2=new window.GraphViewer2({name:void 0,documentStore:window.App.arangoDocumentStore,collection:new window.GraphCollection,userConfig:window.App.userConfig,id:"#outputGraph"+b,data:a}),this.graphViewer2.renderAQL()},getAQL:function(a){var b=this;this.collection.fetch({success:function(){var c=localStorage.getItem("customQueries");if(c){var d=JSON.parse(c);_.each(d,function(a){b.collection.add({value:a.value,name:a.name})});var e=function(a){a?arangoHelper.arangoError("Custom Queries","Could not import old local storage queries"):localStorage.removeItem("customQueries")};b.collection.saveCollectionQueries(e)}b.updateLocalQueries(),a&&a()}})}})}(),function(){"use strict";window.ScaleView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("scaleView.ejs"),interval:1e4,knownServers:[],events:{"click #addCoord":"addCoord","click #removeCoord":"removeCoord","click #addDBs":"addDBs","click #removeDBs":"removeDBs"},setCoordSize:function(a){var b=this,c={numberOfCoordinators:a};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(c),success:function(){b.updateTable(c)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},setDBsSize:function(a){var b=this,c={numberOfDBServers:a};$.ajax({type:"PUT",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",data:JSON.stringify(c),success:function(){b.updateTable(c)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},addCoord:function(){this.setCoordSize(this.readNumberFromID("#plannedCoords",!0))},removeCoord:function(){this.setCoordSize(this.readNumberFromID("#plannedCoords",!1,!0))},addDBs:function(){this.setDBsSize(this.readNumberFromID("#plannedDBs",!0))},removeDBs:function(){this.setDBsSize(this.readNumberFromID("#plannedDBs",!1,!0))},readNumberFromID:function(a,b,c){var d=$(a).html(),e=!1;try{e=JSON.parse(d)}catch(f){}return b&&e++,c&&1!==e&&e--,e},initialize:function(a){var b=this;clearInterval(this.intervalFunction),window.App.isCluster&&(this.dbServers=a.dbServers,this.coordinators=a.coordinators,this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#sNodes"===window.location.hash&&b.coordinators.fetch({success:function(){b.dbServers.fetch({success:function(){b.continueRender(!0)}})}})},this.interval))},render:function(){var a=this,b=function(){var b=function(){a.continueRender()};this.waitForDBServers(b)}.bind(this);this.initDoneCoords?b():this.waitForCoordinators(b),window.arangoHelper.buildNodesSubNav("scale")},continueRender:function(a){var b,c,d=this;b=this.coordinators.toJSON(),c=this.dbServers.toJSON(),this.$el.html(this.template.render({runningCoords:b.length,runningDBs:c.length,plannedCoords:void 0,plannedDBs:void 0,initialized:a})),$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",processData:!1,success:function(a){d.updateTable(a)}})},updateTable:function(a){var b='scaling in progress ',c='no scaling process active';a.numberOfCoordinators&&($("#plannedCoords").html(a.numberOfCoordinators),this.coordinators.toJSON().length===a.numberOfCoordinators?$("#statusCoords").html(c):$("#statusCoords").html(b)),a.numberOfDBServers&&($("#plannedDBs").html(a.numberOfDBServers),this.dbServers.toJSON().length===a.numberOfDBServers?$("#statusDBs").html(c):$("#statusDBs").html(b))},waitForDBServers:function(a){var b=this;0===this.dbServers.length?window.setInterval(function(){b.waitForDBServers(a)},300):a()},waitForCoordinators:function(a){var b=this;window.setTimeout(function(){0===b.coordinators.length?b.waitForCoordinators(a):(b.initDoneCoords=!0,a())},200)},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.SettingsView=Backbone.View.extend({el:"#content",initialize:function(a){this.collectionName=a.collectionName,this.model=this.collection},events:{},render:function(){this.breadcrumb(),window.arangoHelper.buildCollectionSubNav(this.collectionName,"Settings"),this.renderSettings()},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},unloadCollection:function(){var a=function(a){a?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be unloaded."):void 0===a?(this.model.set("status","unloading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","unloaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" unloaded.")}.bind(this);this.model.unloadCollection(a),window.modalView.hide()},loadCollection:function(){var a=function(a){a?arangoHelper.arangoError("Collection error",this.model.get("name")+" could not be loaded."):void 0===a?(this.model.set("status","loading"),this.render()):"#collections"===window.location.hash?(this.model.set("status","loaded"),this.render()):arangoHelper.arangoNotification("Collection "+this.model.get("name")+" loaded.")}.bind(this);this.model.loadCollection(a),window.modalView.hide()},truncateCollection:function(){this.model.truncateCollection(),window.modalView.hide()},deleteCollection:function(){this.model.destroy({error:function(){arangoHelper.arangoError("Could not delete collection.")},success:function(){window.App.navigate("#collections",{trigger:!0})}})},saveModifiedCollection:function(){var a=function(a,b){if(a)arangoHelper.arangoError("Error","Could not get coordinator info");else{var c;c=b?this.model.get("name"):$("#change-collection-name").val();var d=this.model.get("status");if("loaded"===d){var e;try{e=JSON.parse(1024*$("#change-collection-size").val()*1024)}catch(f){return arangoHelper.arangoError("Please enter a valid number"),0}var g;try{if(g=JSON.parse($("#change-index-buckets").val()),1>g||parseInt(g,10)!==Math.pow(2,Math.log2(g)))throw new Error("invalid indexBuckets value")}catch(f){return arangoHelper.arangoError("Please enter a valid number of index buckets"),0}var h=function(a){a?arangoHelper.arangoError("Collection error: "+a.responseText):(arangoHelper.arangoNotification("Collection: Successfully changed."),window.App.navigate("#cSettings/"+c,{trigger:!0}))},i=function(a){if(a)arangoHelper.arangoError("Collection error: "+a.responseText);else{var b=$("#change-collection-sync").val();this.model.changeCollection(b,e,g,h)}}.bind(this);frontendConfig.isCluster===!1?this.model.renameCollection(c,i):i()}else if("unloaded"===d)if(this.model.get("name")!==c){var j=function(a,b){a?arangoHelper.arangoError("Collection"+b.responseText):(arangoHelper.arangoNotification("CollectionSuccessfully changed."),window.App.navigate("#cSettings/"+c,{trigger:!0}))};frontendConfig.isCluster===!1?this.model.renameCollection(c,j):j()}else window.modalView.hide()}}.bind(this);window.isCoordinator(a)},renderSettings:function(){var a=function(a,b){if(a)arangoHelper.arangoError("Error","Could not get coordinator info");else{var c=!1;"loaded"===this.model.get("status")&&(c=!0);var d=[],e=[];b||e.push(window.modalView.createTextEntry("change-collection-name","Name",this.model.get("name"),!1,"",!0,[{rule:Joi.string().regex(/^[a-zA-Z]/),msg:"Collection name must always start with a letter."},{rule:Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),msg:'Only Symbols "_" and "-" are allowed.'},{rule:Joi.string().required(),msg:"No collection name given."}]));var f=function(){e.push(window.modalView.createReadOnlyEntry("change-collection-id","ID",this.model.get("id"),"")),e.push(window.modalView.createReadOnlyEntry("change-collection-type","Type",this.model.get("type"),"")),e.push(window.modalView.createReadOnlyEntry("change-collection-status","Status",this.model.get("status"),"")),d.push(window.modalView.createDeleteButton("Delete",this.deleteCollection.bind(this))),d.push(window.modalView.createDeleteButton("Truncate",this.truncateCollection.bind(this))),c?d.push(window.modalView.createNotificationButton("Unload",this.unloadCollection.bind(this))):d.push(window.modalView.createNotificationButton("Load",this.loadCollection.bind(this))),d.push(window.modalView.createSuccessButton("Save",this.saveModifiedCollection.bind(this)));var a=["General","Indices"],b=["modalTable.ejs","indicesView.ejs"];window.modalView.show(b,"Modify Collection",d,e,null,null,this.events,null,a,"content"),$($("#infoTab").children()[1]).remove()}.bind(this);if(c){var g=function(a,b){if(a)arangoHelper.arangoError("Collection","Could not fetch properties");else{var c=b.journalSize/1048576,d=b.indexBuckets,g=b.waitForSync;e.push(window.modalView.createTextEntry("change-collection-size","Journal size",c,"The maximal size of a journal or datafile (in MB). Must be at least 1.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),e.push(window.modalView.createTextEntry("change-index-buckets","Index buckets",d,"The number of index buckets for this collection. Must be at least 1 and a power of 2.","",!0,[{rule:Joi.string().allow("").optional().regex(/^[1-9][0-9]*$/),msg:"Must be a number greater than 1 and a power of 2."}])),e.push(window.modalView.createSelectEntry("change-collection-sync","Wait for sync",g,"Synchronize to disk before returning from a create or update of a document.",[{value:!1,label:"No"},{value:!0,label:"Yes"}]))}f()};this.model.getProperties(g)}else f()}}.bind(this);window.isCoordinator(a)}})}(),function(){"use strict";window.ShardsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("shardsView.ejs"),interval:1e4,knownServers:[],events:{"click #shardsContent .shardLeader span":"moveShard","click #shardsContent .shardFollowers span":"moveShardFollowers","click #rebalanceShards":"rebalanceShards"},initialize:function(a){var b=this;b.dbServers=a.dbServers,clearInterval(this.intervalFunction),window.App.isCluster&&(this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#shards"===window.location.hash&&b.render(!1)},this.interval))},render:function(a){var b=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/shardDistribution"),contentType:"application/json",processData:!1,async:!0,success:function(a){var c,d=!1;b.shardDistribution=a.results,_.each(a.results,function(a,b){c=b.substring(0,1),"_"!==c&&"error"!==b&&"code"!==b&&(d=!0)}),d?b.continueRender(a.results):arangoHelper.renderEmpty("No collections and no shards available")},error:function(a){0!==a.readyState&&arangoHelper.arangoError("Cluster","Could not fetch sharding information.")}}),a!==!1&&arangoHelper.buildNodesSubNav("Shards")},moveShardFollowers:function(a){var b=$(a.currentTarget).html();this.moveShard(a,b)},moveShard:function(a,b){var c,d,e,f,g=this,h=window.App.currentDB.get("name");d=$(a.currentTarget).parent().parent().attr("collection"),e=$(a.currentTarget).parent().parent().attr("shard"),b?(f=$(a.currentTarget).parent().parent().attr("leader"),c=b):c=$(a.currentTarget).parent().parent().attr("leader");var i=[],j=[],k={},l=[];return g.dbServers[0].each(function(a){a.get("name")!==c&&(k[a.get("name")]={value:a.get("name"),label:a.get("name")})}),_.each(g.shardDistribution[d].Plan[e].followers,function(a){delete k[a]}),b&&delete k[f],_.each(k,function(a){l.push(a)}),l=l.reverse(),0===l.length?void arangoHelper.arangoMessage("Shards","No database server for moving the shard is available."):(j.push(window.modalView.createSelectEntry("toDBServer","Destination",void 0,"Please select the target databse server. The selected database server will be the new leader of the shard.",l)),i.push(window.modalView.createSuccessButton("Move",this.confirmMoveShards.bind(this,h,d,e,c))),void window.modalView.show("modalTable.ejs","Move shard: "+e,i,j))},confirmMoveShards:function(a,b,c,d){var e=this,f=$("#toDBServer").val(),g={database:a,collection:b,shard:c,fromServer:d,toServer:f};$.ajax({type:"POST",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/moveShard"),contentType:"application/json",processData:!1,data:JSON.stringify(g),async:!0,success:function(a){a===!0&&(window.setTimeout(function(){e.render(!1)},1500),arangoHelper.arangoNotification("Shard "+c+" will be moved to "+f+"."))},error:function(){arangoHelper.arangoNotification("Shard "+c+" could not be moved to "+f+".")}}),window.modalView.hide()},rebalanceShards:function(){var a=this;$.ajax({type:"POST",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/rebalanceShards"),contentType:"application/json",processData:!1,data:JSON.stringify({}),async:!0,success:function(b){b===!0&&(window.setTimeout(function(){a.render(!1)},1500),arangoHelper.arangoNotification("Started rebalance process."))},error:function(){arangoHelper.arangoNotification("Could not start rebalance process.")}}),window.modalView.hide()},continueRender:function(a){delete a.code,delete a.error,this.$el.html(this.template.render({collections:a}))},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.ShowClusterView=Backbone.View.extend({detailEl:"#modalPlaceholder",el:"#content",defaultFrame:12e5,template:templateEngine.createTemplate("showCluster.ejs"),modal:templateEngine.createTemplate("waitModal.ejs"),detailTemplate:templateEngine.createTemplate("detailView.ejs"),events:{"change #selectDB":"updateCollections","change #selectCol":"updateShards","click .dbserver.success":"dashboard","click .coordinator.success":"dashboard"},replaceSVGs:function(){$(".svgToReplace").each(function(){var a=$(this),b=a.attr("id"),c=a.attr("src");$.get(c,function(c){var d=$(c).find("svg");d.attr("id",b).attr("class","icon").removeAttr("xmlns:a"),a.replaceWith(d)},"xml")})},updateServerTime:function(){this.serverTime=(new Date).getTime()},setShowAll:function(){this.graphShowAll=!0},resetShowAll:function(){this.graphShowAll=!1,this.renderLineChart()},initialize:function(a){this.options=a,this.interval=1e4,this.isUpdating=!1,this.timer=null,this.knownServers=[],this.graph=void 0,this.graphShowAll=!1,this.updateServerTime(),this.dygraphConfig=this.options.dygraphConfig,this.dbservers=new window.ClusterServers([],{interval:this.interval}),this.coordinators=new window.ClusterCoordinators([],{interval:this.interval}),this.documentStore=new window.ArangoDocuments,this.statisticsDescription=new window.StatisticsDescription,this.statisticsDescription.fetch({async:!1}),this.dbs=new window.ClusterDatabases([],{interval:this.interval}),this.cols=new window.ClusterCollections,this.shards=new window.ClusterShards,this.startUpdating()},listByAddress:function(a){var b={},c=this;this.dbservers.byAddress(b,function(b){c.coordinators.byAddress(b,a)})},updateCollections:function(){var a=this,b=$("#selectCol"),c=$("#selectDB").find(":selected").attr("id");if(c){var d=b.find(":selected").attr("id");b.html(""),this.cols.getList(c,function(c){_.each(_.pluck(c,"name"),function(a){b.append('")});var e=$("#"+d,b);1===e.length&&e.prop("selected",!0),a.updateShards()})}},updateShards:function(){var a=$("#selectDB").find(":selected").attr("id"),b=$("#selectCol").find(":selected").attr("id");this.shards.getList(a,b,function(a){$(".shardCounter").html("0"),_.each(a,function(a){$("#"+a.server+"Shards").html(a.shards.length)})})},updateServerStatus:function(a){var b=this,c=function(a,b,c){var d,e,f=c;f=f.replace(/\./g,"-"),f=f.replace(/\:/g,"_"),e=$("#id"+f),e.length<1||(d=e.attr("class").split(/\s+/)[1],e.attr("class",a+" "+d+" "+b),"coordinator"===a&&("success"===b?$(".button-gui",e.closest(".tile")).toggleClass("button-gui-disabled",!1):$(".button-gui",e.closest(".tile")).toggleClass("button-gui-disabled",!0)))};this.coordinators.getStatuses(c.bind(this,"coordinator"),function(){b.dbservers.getStatuses(c.bind(b,"dbserver")),a()})},updateDBDetailList:function(){var a=this,b=$("#selectDB"),c=b.find(":selected").attr("id");b.html(""),this.dbs.getList(function(d){_.each(_.pluck(d,"name"),function(a){b.append('")});var e=$("#"+c,b);1===e.length&&e.prop("selected",!0),a.updateCollections()})},rerender:function(){var a=this;this.updateServerStatus(function(){a.getServerStatistics(function(){a.updateServerTime(),a.data=a.generatePieData(),a.renderPieChart(a.data),a.renderLineChart(),a.updateDBDetailList()})})},render:function(){this.knownServers=[],delete this.hist;var a=this;this.listByAddress(function(b){1===Object.keys(b).length?a.type="testPlan":a.type="other",a.updateDBDetailList(),a.dbs.getList(function(c){$(a.el).html(a.template.render({dbs:_.pluck(c,"name"),byAddress:b,type:a.type})),$(a.el).append(a.modal.render({})),a.replaceSVGs(),a.getServerStatistics(function(){a.data=a.generatePieData(),a.renderPieChart(a.data),a.renderLineChart(),a.updateDBDetailList(),a.startUpdating()})})})},generatePieData:function(){var a=[],b=this;return this.data.forEach(function(c){a.push({key:c.get("name"),value:c.get("system").virtualSize,time:b.serverTime})}),a},addStatisticsItem:function(a,b,c,d){var e=this;e.hasOwnProperty("hist")||(e.hist={}),e.hist.hasOwnProperty(a)||(e.hist[a]=[]);var f=e.hist[a],g=f.length;if(0===g)f.push({time:b,snap:d,requests:c,requestsPerSecond:0});else{var h=f[g-1].time,i=f[g-1].requests;if(c>i){var j=b-h,k=0;j>0&&(k=(c-i)/j),f.push({time:b,snap:d,requests:c,requestsPerSecond:k})}}},getServerStatistics:function(a){var b=this,c=Math.round(b.serverTime/1e3);this.data=void 0;var d=new window.ClusterStatisticsCollection,e=this.coordinators.first();this.dbservers.forEach(function(a){if("ok"===a.get("status")){-1===b.knownServers.indexOf(a.id)&&b.knownServers.push(a.id);var c=new window.Statistics({name:a.id});c.url=e.get("protocol")+"://"+e.get("address")+"/_admin/clusterStatistics?DBserver="+a.get("name"),d.add(c)}}),this.coordinators.forEach(function(a){if("ok"===a.get("status")){-1===b.knownServers.indexOf(a.id)&&b.knownServers.push(a.id);var c=new window.Statistics({name:a.id});c.url=a.get("protocol")+"://"+a.get("address")+"/_admin/statistics",d.add(c)}});var f=d.size();this.data=[];var g=function(d){f--;var e=d.get("time"),g=d.get("name"),h=d.get("http").requestsTotal;b.addStatisticsItem(g,e,h,c),b.data.push(d),0===f&&a()},h=function(){f--,0===f&&a()};d.fetch(g,h)},renderPieChart:function(a){var b=$("#clusterGraphs svg").width(),c=$("#clusterGraphs svg").height(),d=Math.min(b,c)/2,e=this.dygraphConfig.colors,f=d3.svg.arc().outerRadius(d-20).innerRadius(0),g=d3.layout.pie().sort(function(a){return a.value}).value(function(a){return a.value});d3.select("#clusterGraphs").select("svg").remove();var h=d3.select("#clusterGraphs").append("svg").attr("class","clusterChart").append("g").attr("transform","translate("+b/2+","+(c/2-10)+")"),i=d3.svg.arc().outerRadius(d-2).innerRadius(d-2),j=h.selectAll(".arc").data(g(a)).enter().append("g").attr("class","slice");j.append("path").attr("d",f).style("fill",function(a,b){return e[b%e.length]}).style("stroke",function(a,b){return e[b%e.length]}),j.append("text").attr("transform",function(a){return"translate("+f.centroid(a)+")"}).style("text-anchor","middle").text(function(a){var b=a.data.value/1024/1024/1024;return b.toFixed(2)}),j.append("text").attr("transform",function(a){return"translate("+i.centroid(a)+")"}).style("text-anchor","middle").text(function(a){return a.data.key})},renderLineChart:function(){var a,b,c,d,e,f,g=this,h=1200,i=[],j=[],k=Math.round((new Date).getTime()/1e3)-h,l=g.knownServers,m=function(){return null};for(c=0;cf||(j.hasOwnProperty(f)?a=j[f]:(e=new Date(1e3*f),a=j[f]=[e].concat(l.map(m))),a[c+1]=b[d].requestsPerSecond);i=[],Object.keys(j).sort().forEach(function(a){i.push(j[a])});var n=this.dygraphConfig.getDefaultConfig("clusterRequestsPerSecond");n.labelsDiv=$("#lineGraphLegend")[0],n.labels=["datetime"].concat(l),g.graph=new Dygraph(document.getElementById("lineGraph"),i,n)},stopUpdating:function(){window.clearTimeout(this.timer),delete this.graph,this.isUpdating=!1},startUpdating:function(){if(!this.isUpdating){this.isUpdating=!0;var a=this;this.timer=window.setInterval(function(){a.rerender()},this.interval)}},dashboard:function(a){this.stopUpdating();var b,c,d=$(a.currentTarget),e={},f=d.attr("id");f=f.replace(/\-/g,"."),f=f.replace(/\_/g,":"),f=f.substr(2),e.raw=f,e.isDBServer=d.hasClass("dbserver"),e.isDBServer?(b=this.dbservers.findWhere({address:e.raw}),c=this.coordinators.findWhere({status:"ok"}),e.endpoint=c.get("protocol")+"://"+c.get("address")):(b=this.coordinators.findWhere({address:e.raw}),e.endpoint=b.get("protocol")+"://"+b.get("address")),e.target=encodeURIComponent(b.get("name")),window.App.serverToShow=e,window.App.dashboard()},getCurrentSize:function(a){"#"!==a.substr(0,1)&&(a="#"+a);var b,c;return $(a).attr("style",""),b=$(a).height(),c=$(a).width(),{height:b,width:c}},resize:function(){var a;this.graph&&(a=this.getCurrentSize(this.graph.maindiv_.id),this.graph.resize(a.width,a.height))}})}(),function(){"use strict";window.SpotlightView=Backbone.View.extend({template:templateEngine.createTemplate("spotlightView.ejs"),el:"#spotlightPlaceholder",displayLimit:8,typeahead:null,callbackSuccess:null,callbackCancel:null,collections:{system:[],doc:[],edge:[]},events:{"focusout #spotlight .tt-input":"hide","keyup #spotlight .typeahead":"listenKey"},aqlKeywordsArray:[],aqlBuiltinFunctionsArray:[],aqlKeywords:"for|return|filter|sort|limit|let|collect|asc|desc|in|into|insert|update|remove|replace|upsert|options|with|and|or|not|distinct|graph|outbound|inbound|any|all|none|aggregate|like|count|shortest_path",hide:function(){this.typeahead=$("#spotlight .typeahead").typeahead("destroy"),$(this.el).hide()},listenKey:function(a){if(27===a.keyCode)this.callbackSuccess&&this.callbackCancel(),this.hide();else if(13===a.keyCode&&this.callbackSuccess){var b=$(this.typeahead).val();this.callbackSuccess(b),this.hide()}},substringMatcher:function(a){return function(b,c){var d,e;d=[],e=new RegExp(b,"i"),_.each(a,function(a){e.test(a)&&d.push(a)}),c(d)}},updateDatasets:function(){var a=this;this.collections={system:[],doc:[],edge:[]},window.App.arangoCollectionsStore.each(function(b){b.get("isSystem")?a.collections.system.push(b.get("name")):"document"===b.get("type")?a.collections.doc.push(b.get("name")):a.collections.edge.push(b.get("name"))})},stringToArray:function(){var a=this;_.each(this.aqlKeywords.split("|"),function(b){a.aqlKeywordsArray.push(b.toUpperCase())}),a.aqlKeywordsArray.push(!0),a.aqlKeywordsArray.push(!1),a.aqlKeywordsArray.push(null)},fetchKeywords:function(a){var b=this;$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_api/aql-builtin"),contentType:"application/json",success:function(c){b.stringToArray(),b.updateDatasets(),_.each(c.functions,function(a){b.aqlBuiltinFunctionsArray.push(a.name)}),a&&a()},error:function(){a&&a(),arangoHelper.arangoError("AQL","Could not fetch AQL function definition.")}})},show:function(a,b,c){var d=this;this.callbackSuccess=a,this.callbackCancel=b;var e=function(){var a=function(a,b,c){var d='