"),$("#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]=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)}else{var c=function(a){b.rerenderGraphs(a,!0)};b.getCoordStatHistory(c)}},this.interval))},render:function(){var a=this;this.$el.html(this.template.render({})),this.initDone||(void 0!==this.coordinators.first()?this.getServerStatistics():this.waitForCoordinators(),this.initDone=!0),this.initGraphs();var b=function(b){a.rerenderValues(b)};this.getCoordStatHistory(b)},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")){a.knownServers.indexOf(c.id)===-1&&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")){a.knownServers.indexOf(b.id)===-1&&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&&g<90&&(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,b){if(this.statsEnabled){var c,d,e=this;this.formatDataForGraph(a),_.each(e.chartsOptions,function(a){d=e.returnGraphOptions(a.id),d.length>0?_.each(d,function(b,c){a.options[c].values=b}):a.options[0].values=[],c=a.options,void 0!==b&&b!==!1||c[0].values.length>0&&e.historyInit&&e.charts[a.id]&&e.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")||"corrupted"===this.model.get("status")?($(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:"corrupted"===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()),g<1||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","Indexes"],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(),"Indexes"!==$(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),h<1)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,journalSize: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. Total number of copies of the data in the cluster","",!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,reRender:!0,reRenderDistribution:!0,isVisible:!0,distributionCharts:{totalTimeDistribution:null,dataTransferDistribution:null},residentChart:null,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]),e<0?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=this,b=function(b,c){b?arangoHelper.arangoError("DB","Could not get current db properties"):(a.currentDB=c,a.collection.fetch({success:function(){a.collection.sort(),$(a.el).html(a.template.render({collection:a.collection,searchString:"",currentDB:a.currentDB})),a.dropdownVisible===!0&&($("#dbSortDesc").attr("checked",a.collection.sortOptions.desc),$("#databaseToggle").toggleClass("activated"),$("#databaseDropdown2").show()),arangoHelper.setCheckboxStatus("#databaseDropdown"),a.replaceSVGs()}}))};return this.collection.getCurrentDatabase(b),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_-]*$/)||(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 a.get("name").indexOf(b)!==-1}),$(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(){var a=!1;_.each($(".documentsDropdown").first().children(),function(b){$(b).is(":visible")&&(a=!0)}),a?($("#docPureTable").height($(".centralRow").height()-210-57),$("#docPureTable .pure-table-body").css("max-height",$("#docPureTable").height()-47)):($("#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(){$(".upload-indicator").show()},hideSpinner:function(){$(".upload-indicator").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.hideImportModal(),this.resetView()),this.hideSpinner()}.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(1),$("#exportHeader").hide();var a=this;window.setTimeout(function(){a.resize()},50)},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(1);var a=this;window.setTimeout(function(){a.resize()},50);var b;for(b in this.filters)if(this.filters.hasOwnProperty(b))return void $("#attribute_name"+b).focus()},exportCollection:function(){$("#importCollection").removeClass("activated"),$("#filterHeader").removeClass("activated"),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),$("#exportCollection").toggleClass("activated"),this.markFilterToggle(),$("#exportHeader").slideToggle(1),$("#importHeader").hide(),$("#filterHeader").hide(),$("#editHeader").hide();var a=this;window.setTimeout(function(){a.resize()},50)},importCollection:function(){this.markFilterToggle(),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),$("#importCollection").toggleClass("activated"),$("#exportCollection").removeClass("activated"),$("#importHeader").slideToggle(1),$("#filterHeader").hide(),$("#editHeader").hide(),$("#exportHeader").hide();var a=this;window.setTimeout(function(){a.resize()},50)},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)}),a.rerender()},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;a<=b;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,d){if(b)arangoHelper.arangoError("Error",d.errorMessage);else{window.modalView.hide(),c=c._id.split("/");try{a="collection/"+c[0]+"/"+c[1],decodeURI(a)}catch(e){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,d){if(b)arangoHelper.arangoError("Error",d.errorMessage);else{window.modalView.hide(),c=c.split("/");try{a="collection/"+c[0]+"/"+c[1],decodeURI(a)}catch(e){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,b){a?arangoHelper.arangoError("Error",b.responseJSON.errorMessage):(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,b){a?arangoHelper.arangoError("Error",b.responseJSON.errorMessage):(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(''),window.modalView.hide(),$("#offlinePlaceholder").show(),$.noty.clearQueue(),$.noty.closeAll(),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===b?$(".health-state").html(b+" NODE ERROR"):$(".health-state").html(b+" 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,f;this._upgrade?(c=this.mount,e=Boolean($("#new-app-teardown").prop("checked"))):c=window.arangoHelper.escapeHtml($("#new-app-mount").val()),f=Boolean($("#zip-app-islegacy").prop("checked")),this.collection.installFromZip(b.filename,c,d.bind(this),f,e)}},l=function(){if(window.modalView.modalTestAll()){var a,b,c,e,f;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 g={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(h){return}f=Boolean($("#github-app-islegacy").prop("checked")),this.collection.installFromGithub(g,c,d.bind(this),f,e)}},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())};this.collection.generate(c,a,d.bind(this),b)}},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 #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)+"/"+encodeURIComponent(b)},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)}})},toggleSmartGraph:function(){var a,b=this;if($("#new-is_smart").is(":checked")===!0){for(a=0;a",""),arangoHelper.arangoError(d)}})},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(),ab?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.createNotificationButton("Reset display settings",this.resetDisplaySettings.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.frontendConfig.isEnterprise===!0){var l={},m=[];m.push(window.modalView.createCheckboxEntry("new-is_smart","Smart Graph",!1,"Create a Smart Graph? Edge and vertex collections will be automatically generated. They are not allowed to be present before graph creation.",!1)),m.push(window.modalView.createTextEntry("new-numberOfShards","Shards","","Number of shards the smart graph is using.","",!1,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),m.push(window.modalView.createTextEntry("new-smartGraphAttribute","SmartGraph Attribute","","The attribute name that is used to smartly shard the vertices of a graph. \nEvery vertex in this Graph has to have this attribute. \nCannot be modified later.","",!1,[{rule:Joi.string(),msg:"Must be a string."}])),l.header="Smart Graph",l.content=m,window.modalView.show("modalGraphTable.ejs",b,c,e,l,void 0,this.events)}else window.modalView.show("modalGraphTable.ejs",b,c,e,void 0,void 0,this.events);if(a){$(".modal-body table").css("border-collapse","separate");var n;for($(".modal-body .spacer").remove(),n=0;n<=this.counter;n++)$("#row_fromCollections"+n).show(),$("#row_toCollections"+n).show(),$("#row_newEdgeDefinitions"+n).addClass("first"),$("#row_fromCollections"+n).addClass("middle"),$("#row_toCollections"+n).addClass("last"),$("#row_toCollections"+n).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:"Startnode",desc:"A valid node id. If empty, a random node will be chosen.",value:2},layout:{type:"select",name:"Layout",desc:"Different graph algorithms. No overlap is very fast (more than 5000 nodes), force is slower (less than 5000 nodes) and fruchtermann is the slowest (less than 500 nodes).",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 (experimental)",val:"webgl"}},depth:{desc:"Search depth, starting from your start node.",type:"number",name:"Search Depth",value:2},limit:{desc:"Limit nodes count. If empty or zero, no limit is set.",type:"number",name:"Limit",value:250}},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:"Add Collection Name",desc:"Append collection name to the label?",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},nodeColorByCollection:{type:"select",name:"Color By Collections",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."},nodeColor:{type:"color",name:"Color",desc:"Default node color. RGB or HEX value.","default":"#2ecc71"},nodeColorAttribute:{type:"string",name:"Color Attribute",desc:"If an attribute is given, nodes will then be colorized by the attribute. This setting ignores default node color if set."},nodeSizeByEdges:{type:"select",name:"Size By Connections",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"},desc:"Should nodes be sized by their edges count? If enabled, node sizing 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:"Add Collection Name",desc:"Set label text by collection. If activated edge label attribute will be ignored.",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},edgeColorByCollection:{type:"select",name:"Color By Collections",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."},edgeColor:{type:"color",name:"Color",desc:"Default edge color. RGB or HEX value.","default":"#cccccc"},edgeColorAttribute:{type:"string",name:"Color Attribute",desc:"If an attribute is given, edges will then be colorized by the attribute. This setting ignores default edge color if set."},edgeEditable:{type:"select",hide:"true",name:"Editable",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"},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,a.noDefinedGraph&&(this.noDefinedGraph=a.noDefinedGraph)},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",'focusout #graphSettingsView input[type="text"]':"checkinput"},lastFocus:function(a){this.lastFocussed=a.currentTarget.id,this.lastFocussedValue=$(a.currentTarget).val()},checkinput:function(a){new Date-this.lastSaved>500&&a.currentTarget.id===this.lastFocussed&&this.lastFocussedValue!==$(a.currentTarget).val()&&this.saveGraphSettings()},checkEnterKey:function(a){13===a.keyCode&&this.saveGraphSettings(a)},getGraphSettings:function(a){var b=this,c=frontendConfig.db+"_"+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,e,f){var g=this,h=function(){var a=!$("#g_nodeColor").is(":disabled"),b=!$("#g_edgeColor").is(":disabled");window.App.graphViewer.updateColors(a,b,$("#g_nodeColor").val(),$("#g_edgeColor").val())};if(this.noDefinedGraph){var i;b?h():"g_layout"===a.currentTarget.id?window.App.graphViewer.rerenderAQL($("#g_layout").val(),null):"g_nodeColorByCollection"===a.currentTarget.id?(i=$("#g_nodeColorByCollection").val(),"true"===i?window.App.graphViewer.switchNodeColorByCollection(!0):window.App.graphViewer.switchNodeColorByCollection(!1)):"g_edgeColorByCollection"===a.currentTarget.id?(i=$("#g_edgeColorByCollection").val(),"true"===i?window.App.graphViewer.switchEdgeColorByCollection(!0):window.App.graphViewer.switchEdgeColorByCollection(!1)):"g_nodeSizeByEdges"===a.currentTarget.id?(i=$("#g_nodeSizeByEdges").val(),"true"===i?window.App.graphViewer.switchNodeSizeByCollection(!0):window.App.graphViewer.switchNodeSizeByCollection(!1)):"g_edgeType"===a.currentTarget.id&&window.App.graphViewer.switchEdgeType($("#g_edgeType").val())}else{g.lastSaved=new Date;var j=frontendConfig.db+"_"+this.name,k={};if(d)k[j]=d;else{var l,m={};$("#graphSettingsView select").each(function(a,b){l=b.id,m[l.substr(2,b.id.length)]=$(b).val()}),$("#graphSettingsView input").each(function(a,b){l=b.id,m[l.substr(2,b.id.length)]=$(b).val()}),k[j]=m}c&&(k[j].nodeStart=c);var n=function(){if(window.App.graphViewer){var c;if(a){if("g_layout"===a.currentTarget.id)return void window.App.graphViewer.switchLayout($("#g_layout").val());if("g_nodeColorByCollection"===a.currentTarget.id)return c=$("#g_nodeColorByCollection").val(),void("true"===c?window.App.graphViewer.switchNodeColorByCollection(!0):$("#g_nodeColorAttribute").is(":disabled")?window.App.graphViewer.switchNodeColorByCollection(!1):window.App.graphViewer.switchNodeColorByCollection(!1,!0));if("g_edgeColorByCollection"===a.currentTarget.id)return c=$("#g_edgeColorByCollection").val(),void("true"===c?window.App.graphViewer.switchEdgeColorByCollection(!0):$("#g_nodeColorAttribute").is(":disabled")?window.App.graphViewer.switchEdgeColorByCollection(!1):window.App.graphViewer.switchEdgeColorByCollection(!1,!0))}""!==b&&void 0!==b?h():window.App.graphViewer.render(g.lastFocussed)}else e||arangoHelper.arangoNotification("Graph "+this.name,"Configuration saved.");f&&f()}.bind(this);this.userConfig.setItem("graphs",k,n)}this.handleDependencies()},setDefaults:function(a,b,c){var d={layout:"force",renderer:"canvas",depth:"2",limit:"250",nodeColor:"#2ecc71",nodeColorAttribute:"",nodeColorByCollection:"true",edgeColor:"#cccccc",edgeColorAttribute:"",edgeColorByCollection:"false",nodeLabel:"_key",edgeLabel:"",edgeType:"arrow",nodeSize:"",nodeSizeByEdges:"true",edgeEditable:"true",nodeLabelByCollection:"false",edgeLabelByCollection:"false",nodeStart:"",barnesHutOptimize:!0};a===!0?b?this.saveGraphSettings(null,null,null,d,b,c):this.saveGraphSettings(null,null,null,d):(this.saveGraphSettings(null,null,null,d,null),this.render(),window.App.graphViewer.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.noDefinedGraph?this.continueRender():(this.getGraphSettings(!0),this.lastSaved=new Date)},handleDependencies:function(){"true"===$("#g_nodeSizeByEdges").val()?$("#g_nodeSize").prop("disabled",!0):$("#g_nodeSize").removeAttr("disabled"),"true"===$("#g_nodeColorByCollection").val()?($("#g_nodeColorAttribute").prop("disabled",!0),$("#g_nodeColor").prop("disabled",!0)):($("#g_nodeColorAttribute").removeAttr("disabled"),$("#g_nodeColor").removeAttr("disabled")),this.noDefinedGraph||""!==$("#g_nodeColorAttribute").val()&&$("#g_nodeColor").prop("disabled",!0),"true"===$("#g_edgeColorByCollection").val()?($("#g_edgeColorAttribute").prop("disabled",!0),$("#g_edgeColor").prop("disabled",!0)):($("#g_edgeColorAttribute").removeAttr("disabled"),$("#g_edgeColor").removeAttr("disabled")),this.noDefinedGraph||""!==$("#g_edgeColorAttribute").val()&&$("#g_edgeColor").prop("disabled",!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)}):this.noDefinedGraph?this.fitSettingsAQLMode():this.setDefaults(!0),this.handleDependencies()},fitSettingsAQLMode:function(){var a=["g_nodeStart","g_depth","g_limit","g_renderer","g_nodeLabel","g_nodeLabelByCollection","g_nodeColorAttribute","g_nodeSize","g_edgeLabel","g_edgeColorAttribute","g_edgeLabelByCollection"];_.each(a,function(a){$("#"+a).parent().prev().remove(),$("#"+a).parent().remove()}),$("#saveGraphSettings").remove(),$("#restoreGraphSettings").remove(),$("#g_nodeColorByCollection").val("false"),$("#g_edgeColorByCollection").val("false"),$("#g_nodeSizeByEdges").val("false"),$("#g_edgeType").val("arrow"),$("#g_layout").val("force")}})}(),function(){"use strict";
-window.GraphViewer=Backbone.View.extend({el:"#content",remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,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),a.noDefinedGraph&&(this.noDefinedGraph=a.noDefinedGraph,this.graphData=a.data),this.name=a.name,this.userConfig=a.userConfig,this.documentStore=a.documentStore,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"],jans:["rgba(166, 109, 161, 1)","rgba(64, 74, 83, 1)","rgba(90, 147, 189, 1)","rgba(153,63,0,1)","rgba(76,0,92,1)","rgba(25,25,25,1)","rgba(0,92,49,1)","rgba(43,206,72,1)","rgba(255,204,153,1)","rgba(128,128,128,1)","rgba(148,255,181,1)","rgba(143,124,0,1)","rgba(157,204,0,1)","rgba(194,0,136,1)","rgba(0,51,128,1)","rgba(255,164,5,1)","rgba(255,168,187,1)","rgba(66,102,0,1)","rgba(255,0,16,1)","rgba(94,241,242,1)","rgba(0,153,143,1)","rgba(224,255,102,1)","rgba(116,10,255,1)","rgba(153,0,0,1)","rgba(255,255,128,1)","rgba(255,255,0,1)","rgba(255,80,5,1)"],gv:["#68BDF6","#6DCE9E","#FF756E","#DE9BF9","#FB95AF","#FFD86E","#A5ABB6"]},activeNodes:[],selectedNodes:{},aqlMode:!1,events:{"click #downloadPNG":"downloadPNG","click #loadFullGraph":"loadFullGraphModal","click #reloadGraph":"reloadGraph","click #settingsMenu":"toggleSettings","click #toggleForce":"toggleLayout","click #selectNodes":"toggleLasso"},cursorX:0,cursorY:0,layouting:!1,model:null,viewStates:{captureMode:!1},graphConfig:null,graphSettings:null,downloadPNG:function(){var a=parseInt($("#graph-container").width(),10);sigma.plugins.image(this.currentGraph,this.currentGraph.renderers[0],{download:!0,size:a,clip:!0,labels:!0,background:"white",zoom:!1})},loadFullGraphModal:function(){var a=[],b=[];b.push(window.modalView.createReadOnlyEntry("load-full-graph-a","Caution","Really load full graph? If no limit is set, your result set could be too big.")),a.push(window.modalView.createSuccessButton("Load full graph",this.loadFullGraph.bind(this))),window.modalView.show("modalTable.ejs","Load full graph",a,b)},loadFullGraph:function(){var a=this,b={};this.graphConfig&&(b=_.clone(this.graphConfig),delete b.layout,delete b.edgeType,delete b.renderer),b.mode="all",$.ajax({type:"GET",url:arangoHelper.databaseUrl("/_admin/aardvark/graph/"+encodeURIComponent(this.name)),contentType:"application/json",data:b,success:function(b){a.killCurrentGraph(),a.renderGraph(b)},error:function(a){console.log(a),arangoHelper.arangoError("Graph","Could not load full graph.")}}),window.modalView.hide()},resize:function(){$("#graph-container").width($(".centralContent").width()),$("#graph-container").height($(".centralRow").height()-155)},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),this.initFullscreen()},initFullscreen:function(){var a=this;if(window.App.initializedFullscreen===!1||void 0===window.App.initializedFullscreen){window.App.initializedFullscreen=!0,this.isFullscreen=!1;var b=function(b){(document.webkitIsFullScreen||document.mozFullScreen||null!==document.msFullscreenElement)&&(a.isFullscreen===!1?(a.isFullscreen=!0,$("#toggleForce").css("bottom","10px"),$("#toggleForce").css("right","10px"),$("#objectCount").css("bottom","10px"),$("#objectCount").css("left","10px"),$(".nodeInfoDiv").css("top","10px"),$(".nodeInfoDiv").css("left","10px")):(a.isFullscreen=!1,$("#toggleForce").css("bottom","40px"),$("#toggleForce").css("right","40px"),$("#objectCount").css("bottom","50px"),$("#objectCount").css("left","25px"),$(".nodeInfoDiv").css("top",""),$(".nodeInfoDiv").css("left","165px")))};document.addEventListener&&(document.addEventListener("webkitfullscreenchange",b,!1),document.addEventListener("mozfullscreenchange",b,!1),document.addEventListener("fullscreenchange",b,!1),document.addEventListener("MSFullscreenChange",b,!1))}},renderAQLPreview: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);var c=!1;try{this.renderGraph(this.graphData.modified,null,!0),c=!0}catch(d){}return c},renderAQL:function(a){this.$el.html(this.template.render({})),$("#subNavigationBar .breadcrumb").html("AQL Graph"),$("#subNavigationBar .bottom").html(""),$(".queries-menu").removeClass("active"),this.resize(),this.graphData.modified=this.parseData(this.graphData.original,this.graphData.graphInfo),this.renderGraph(this.graphData.modified,null,!1),this.initFullscreen(),this.graphSettingsView=new window.GraphSettingsView({name:this.name,userConfig:void 0,saveCallback:void 0,noDefinedGraph:!0}),this.graphSettingsView.render()},killCurrentGraph:function(){for(var a in this.currentGraph.renderers)try{this.currentGraph.renderers[a].clear(),this.currentGraph.kill(a)}catch(b){}},rerenderAQL:function(a,b){this.killCurrentGraph(),this.renderGraph(this.graphData.modified,null,!1,a,"canvas"),"true"===$("#g_nodeColorByCollection").val()?this.switchNodeColorByCollection(!0):$("#g_nodeColor").is(":disabled")?this.updateColors(!0,!0,null,null,!0):this.ncolor?this.updateColors(!0,!0,this.ncolor,this.ecolor):this.updateColors(!0,!0,"#2ecc71","#2ecc71"),"true"===$("#g_edgeColorByCollection").val()?this.switchEdgeColorByCollection(!0):$("#g_edgeColor").is(":disabled")?this.updateColors(!0,!0,null,null,!0):this.ecolor?this.updateColors(!0,!0,this.ncolor,this.ecolor):this.updateColors(!0,!0,"#2ecc71","#2ecc71")},buildCollectionColors:function(){var a=this;if(!a.collectionColors){a.collectionColors={};var b=0,c={},d={};_.each(this.currentGraph.graph.nodes(),function(a){c[a.id]=void 0}),_.each(a.currentGraph.graph.edges(),function(a){d[a.id]=void 0}),_.each(c,function(c,d){void 0===a.collectionColors[d.split("/")[0]]&&(a.collectionColors[d.split("/")[0]]={color:a.colors.jans[b]},b++)}),b=0,_.each(d,function(c,d){void 0===a.collectionColors[d.split("/")[0]]&&(a.collectionColors[d.split("/")[0]]={color:a.colors.jans[b]},b++)})}},switchNodeColorByCollection:function(a,b){var c=this;c.buildCollectionColors(),a?(c.currentGraph.graph.nodes().forEach(function(a){a.color=c.collectionColors[a.id.split("/")[0]].color}),c.currentGraph.refresh()):b?this.updateColors(!0,null,null,null,b):this.ncolor?this.updateColors(!0,null,this.ncolor,this.ecolor):this.updateColors(!0,null,"#2ecc71","#2ecc71")},switchEdgeColorByCollection:function(a,b){var c=this;c.buildCollectionColors(),a?(c.currentGraph.graph.edges().forEach(function(a){a.color=c.collectionColors[a.id.split("/")[0]].color}),c.currentGraph.refresh()):b?this.updateColors(!0,null,null,null,b):this.ecolor?this.updateColors(null,!0,this.ncolor,this.ecolor):this.updateColors(null,!0,"#2ecc71","#2ecc71")},buildCollectionSizes:function(){var a=this;if(!a.nodeEdgesCount){a.nodeEdgesCount={};var b={};_.each(this.currentGraph.graph.edges(),function(c){void 0===b[c.id]&&(b[c.id]=!0,void 0===a.nodeEdgesCount[c.source]?a.nodeEdgesCount[c.source]=1:a.nodeEdgesCount[c.source]+=1,void 0===a.nodeEdgesCount[c.target]?a.nodeEdgesCount[c.target]=1:a.nodeEdgesCount[c.target]+=1)})}},switchNodeSizeByCollection:function(a){var b=this;a?(b.buildCollectionSizes(),b.currentGraph.graph.nodes().forEach(function(a){a.size=b.nodeEdgesCount[a.id]})):b.currentGraph.graph.nodes().forEach(function(a){a.size=15}),b.currentGraph.refresh()},switchEdgeType:function(a){var b={nodes:this.currentGraph.graph.nodes(),edges:this.currentGraph.graph.edges(),settings:{}};this.killCurrentGraph(),this.renderGraph(b,null,!1,null,null,a)},switchLayout:function(a){var b={nodes:this.currentGraph.graph.nodes(),edges:this.currentGraph.graph.edges(),settings:{}};this.killCurrentGraph(),this.renderGraph(b,null,!1,a),"true"===$("#g_nodeColorByCollection").val()&&this.switchNodeColorByCollection(!0),"true"===$("#g_edgeColorByCollection").val()?this.switchEdgeColorByCollection(!0):this.switchEdgeColorByCollection(!1)},parseData:function(a,b){var c={},d={},e="#2ecc71",f={nodes:[],edges:[],settings:{}};if(this.ncolor&&(e=this.ncolor),"object"===b){_.each(a,function(a){a.edges&&a.vertices&&(_.each(a.edges,function(a){null!==a&&(d[a._id]={id:a._id,source:a._from,color:"#cccccc",target:a._to})}),_.each(a.vertices,function(a){null!==a&&(c[a._id]={id:a._id,label:a._key,size:.3,color:e,x:Math.random(),y:Math.random()})}))});var g=[];_.each(c,function(a){f.nodes.push(a),g.push(a.id)}),_.each(d,function(a){g.includes(a.source)&&g.includes(a.target)&&f.edges.push(a)})}else"array"===b&&(_.each(a,function(a){c[a._from]=null,c[a._to]=null,f.edges.push({id:a._id,source:a._from,color:"#cccccc",target:a._to})}),_.each(c,function(a,b){f.nodes.push({id:b,label:b,size:.3,color:e,x:Math.random(),y:Math.random()})}));return f},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 navigate to: Graphs ViewClick the settings icon and reset the display settings.It is possible that the graph is too big to be handled by the browser.
'),g.startLayout();var q=250,r=500;a.nodes&&(q=a.nodes.length,c?q<250?q=250:q+=r:(q<=250&&(q=500),q+=r)),a.empty&&arangoHelper.arangoNotification("Graph","Your graph is empty. Click inside the white window to create your first node."),window.setTimeout(function(){g.stopLayout()},q)}else"fruchtermann"===g.algorithm&&sigma.layouts.fruchtermanReingold.start(k);"force"!==g.algorithm&&g.reInitDragListener();var s=document.getElementsByClassName("sigma-mouse")[0];s.addEventListener("mousemove",g.trackCursorPosition.bind(this),!1),b&&($("#"+b).focus(),$("#graphSettingsContent").animate({scrollTop:$("#"+b).offset().top},2e3)),$("#calculatingGraph").fadeOut("slow"),c||g.graphConfig&&"false"===g.graphConfig.nodeSizeByEdges,g.calcFinished=new Date,a.empty===!0&&$(".sigma-background").before('The graph is empty. Please right-click to add a node.'),g.graphNotInitialized===!0&&(g.updateColors(g.tmpGraphArray),g.graphNotInitialized=!1,g.tmpGraphArray=[]),"force"===g.algorithm?$("#toggleForce").fadeIn("fast"):$("#toggleForce").fadeOut("fast")},reInitDragListener:function(){var a=this;void 0!==this.dragListener&&(sigma.plugins.killDragNodes(this.currentGraph),this.dragListener={}),this.dragListener=sigma.plugins.dragNodes(this.currentGraph,this.currentGraph.renderers[0]),this.dragListener.bind("drag",function(b){a.dragging=!0}),this.dragListener.bind("drop",function(b){window.setTimeout(function(){a.dragging=!1},400)})},keyUpFunction:function(a){var b=this;switch(a.keyCode){case 76:a.altKey&&b.toggleLasso()}},toggleLayout:function(){this.layouting?this.stopLayout():this.startLayout()},startLayout:function(a,b){var c=this;this.currentGraph.settings("drawLabels",!1),this.currentGraph.settings("drawEdgeLabels",!1),sigma.plugins.killDragNodes(this.currentGraph),a===!0&&(this.currentGraph.killForceAtlas2(),window.setTimeout(function(){c.stopLayout(),b&&c.currentGraph.refresh({skipIndexation:!0})},500)),$("#toggleForce .fa").removeClass("fa-play").addClass("fa-pause"),$("#toggleForce span").html("Stop layout"),this.layouting=!0,this.aqlMode?this.currentGraph.startForceAtlas2({worker:!0}):this.currentGraph.startForceAtlas2({worker:!0})},stopLayout:function(){$("#toggleForce .fa").removeClass("fa-pause").addClass("fa-play"),$("#toggleForce span").html("Resume layout"),this.layouting=!1,this.currentGraph.stopForceAtlas2(),this.currentGraph.settings("drawLabels",!0),this.currentGraph.settings("drawEdgeLabels",!0),this.currentGraph.refresh({skipIndexation:!0}),this.reInitDragListener()}})}(),function(){"use strict";window.HelpUsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("helpUsView.ejs"),render:function(){this.$el.html(this.template.render({}))}})}(),function(){"use strict";window.IndicesView=Backbone.View.extend({el:"#content",initialize:function(a){this.collectionName=a.collectionName,this.model=this.collection},template:templateEngine.createTemplate("indicesView.ejs"),events:{},render:function(){$(this.el).html(this.template.render({model:this.model})),this.breadcrumb(),window.arangoHelper.buildCollectionSubNav(this.collectionName,"Indexes"),this.getIndex()},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},getIndex:function(){var a=function(a,b,c){a?window.arangoHelper.arangoError("Index",b.errorMessage):this.renderIndex(b,c)}.bind(this);this.model.getIndex(a)},createIndex:function(){var a,b,c,d=this,e=$("#newIndexType").val(),f={};switch(e){case"Geo":a=$("#newGeoFields").val();var g=d.checkboxToValue("#newGeoJson");f={type:"geo",fields:d.stringToArray(a),geoJson:g};break;case"Persistent":a=$("#newPersistentFields").val(),b=d.checkboxToValue("#newPersistentUnique"),c=d.checkboxToValue("#newPersistentSparse"),f={type:"persistent",fields:d.stringToArray(a),unique:b,sparse:c};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 h=parseInt($("#newFulltextMinLength").val(),10)||0;f={type:"fulltext",fields:d.stringToArray(a),minLength:h};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 i=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.toggleNewIndexView(),d.render()};this.model.createIndex(f,i)},bindIndexEvents:function(){this.unbindIndexEvents();var a=this;$("#indexEditView #addIndex").bind("click",function(){a.toggleNewIndexView(),$("#cancelIndex").unbind("click"),$("#cancelIndex").bind("click",function(){a.toggleNewIndexView(),a.render()}),$("#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(),"Indexes"!==$(a.currentTarget).html()||$(a.currentTarget).parent().hasClass("active")||($("#newIndexView").hide(),$("#indexEditView").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-danger").hide(),$("#indexHeaderContent #modal-dialog .modal-footer .button-success").hide(),$("#indexHeaderContent #modal-dialog .modal-footer .button-notification").hide()),"General"===$(a.currentTarget).html()&&!$(a.currentTarget).parent().hasClass("active")){$("#indexHeaderContent #modal-dialog .modal-footer .button-danger").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-success").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-notification").show();var b=$(".index-button-bar2")[0];$("#cancelIndex").is(":visible")&&($("#cancelIndex").detach().appendTo(b),$("#createIndex").detach().appendTo(b))}})},prepDeleteIndex:function(a){var b=this;this.lastTarget=a,this.lastId=$(this.lastTarget.currentTarget).parent().parent().first().children().first().text(),$("#content #modal-dialog .modal-footer").after('
Really delete?
'),$("#indexHeaderContent #indexConfirmDelete").unbind("click"),$("#indexHeaderContent #indexConfirmDelete").bind("click",function(){$("#indexHeaderContent #indexDeleteModal").remove(),b.deleteIndex()}),$("#indexHeaderContent #indexAbortDelete").unbind("click"),$("#indexHeaderContent #indexAbortDelete").bind("click",function(){$("#indexHeaderContent #indexDeleteModal").remove()})},unbindIndexEvents:function(){$("#indexHeaderContent #indexEditView #addIndex").unbind("click"),$("#indexHeaderContent #newIndexType").unbind("change"),$("#indexHeaderContent #infoTab a").unbind("click"),$("#indexHeaderContent .deleteIndex").unbind("click")},deleteIndex:function(){var a=function(a){a?(arangoHelper.arangoError("Could not delete index"),$("tr th:contains('"+this.lastId+"')").parent().children().last().html(''),this.model.set("locked",!1)):a||void 0===a||($("tr th:contains('"+this.lastId+"')").parent().remove(),this.model.set("locked",!1))}.bind(this);this.model.set("locked",!0),this.model.deleteIndex(this.lastId,a),$("tr th:contains('"+this.lastId+"')").parent().children().last().html('')},renderIndex:function(a,b){this.index=a;var c=function(a,c){if(a)arangoHelper.arangoError("Jobs","Could not read pending jobs.");else{var d=function(a,b,c){a?404===b.responseJSON.code?arangoHelper.deleteAardvarkJob(c):400===b.responseJSON.code?(arangoHelper.arangoError("Index creation failed",b.responseJSON.errorMessage),arangoHelper.deleteAardvarkJob(c)):204===b.responseJSON.code&&arangoHelper.arangoMessage("Index","There is at least one new index in the queue or in the process of being created."):arangoHelper.deleteAardvarkJob(c)};_.each(c,function(a){a.collection===b&&$.ajax({type:"PUT",cache:!1,url:arangoHelper.databaseUrl("/_api/job/"+a.id),contentType:"application/json",success:function(b,c,e){d(!1,b,a.id)},error:function(b){d(!0,b,a.id)}})})}};arangoHelper.getAardvarkJobs(c);var d="collectionInfoTh modal-text";if(this.index){var e="",f="";_.each(this.index.indexes,function(a){f="primary"===a.type||"edge"===a.type?'':'',void 0!==a.fields&&(e=a.fields.join(", "));var b=a.id.indexOf("/"),c=a.id.substr(b+1,a.id.length),g=a.hasOwnProperty("selectivityEstimate")?(100*a.selectivityEstimate).toFixed(2)+"%":"n/a",h=a.hasOwnProperty("sparse")?a.sparse:"n/a";$("#collectionEditIndexTable").append("
"+c+"
"+a.type+"
"+a.unique+"
"+h+"
"+g+"
"+e+"
"+f+"
")})}this.bindIndexEvents()},selectIndexType:function(){$(".newIndexClass").hide();var a=$("#newIndexType").val();$("#newIndexType"+a).show()},resetIndexForms:function(){$("#indexHeader input").val("").prop("checked",!1),$("#newIndexType").val("Geo").prop("selected",!0),this.selectIndexType()},toggleNewIndexView:function(){var a=$(".index-button-bar2")[0];$("#indexEditView").is(":visible")?($("#indexEditView").hide(),$("#newIndexView").show(),$("#cancelIndex").detach().appendTo("#indexHeaderContent #modal-dialog .modal-footer"),$("#createIndex").detach().appendTo("#indexHeaderContent #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.InfoView=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,"Info"),this.renderInfoView()},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},renderInfoView:function(){if(this.model.get("locked"))return 0;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,null,null,null,null,null,"content")}}.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)}})}(),function(){"use strict";window.LoginView=Backbone.View.extend({el:"#content",el2:".header",el3:".footer",loggedIn:!1,loginCounter:0,events:{"keyPress #loginForm input":"keyPress","click #submitLogin":"validate","submit #dbForm":"goTo","click #logout":"logout","change #loginDatabase":"renderDBS"},template:templateEngine.createTemplate("loginView.ejs"),render:function(a){var b=this;$(this.el).html(this.template.render({})),$(this.el2).hide(),$(this.el3).hide();var c=function(a,c){var d;d=a?arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(a)+"/database","_system"):arangoHelper.databaseUrl("/_api/database/user"),frontendConfig.authenticationEnabled===!1&&($("#logout").hide(),$(".login-window #databases").css("height","90px")),$("#loginForm").hide(),$(".login-window #databases").show(),$.ajax(d).success(function(a){$("#loginDatabase").html(""),_.each(a.result,function(a,b){c?$("#loginDatabase").append(""):$("#loginDatabase").append("")}),b.renderDBS()}).error(function(){c?c():console.log("could not fetch user db data")})};if(frontendConfig.authenticationEnabled&&a!==!0){var d=arangoHelper.getCurrentJwtUsername();if(null!==d&&"undefined"!==d&&void 0!==d){var e=function(){b.collection.logout(),window.setTimeout(function(){$("#loginUsername").focus()},300)};c(arangoHelper.getCurrentJwtUsername(),e)}else window.setTimeout(function(){$("#loginUsername").focus()},300)}else c();return $(".bodyWrapper").show(),b.checkVersion(),this},checkVersion:function(){var a=this;window.setTimeout(function(){var b,c=document.getElementById("loginSVG"),d=c.contentDocument;void 0!==frontendConfig.isEnterprise?(b=frontendConfig.isEnterprise?d.getElementById("logo-enterprise"):d.getElementById("logo-community"),b.setAttribute("visibility","visible")):a.checkVersion()},150)},clear:function(){$("#loginForm input").removeClass("form-error"),$(".wrong-credentials").hide()},keyPress:function(a){a.ctrlKey&&13===a.keyCode?(a.preventDefault(),this.validate()):a.metaKey&&13===a.keyCode&&(a.preventDefault(),this.validate())},validate:function(a){a.preventDefault(),this.clear();var b=$("#loginUsername").val(),c=$("#loginPassword").val();b&&this.collection.login(b,c,this.loginCallback.bind(this,b,c))},loginCallback:function(a,b,c){var d=this;if(c){if(0===d.loginCounter)return d.loginCounter++,void d.collection.login(a,b,this.loginCallback.bind(this,a));d.loginCounter=0,$(".wrong-credentials").show(),$("#loginDatabase").html(""),$("#loginDatabase").append("")}else d.renderDBSelection(a)},renderDBSelection:function(a){var b=this,c=arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(a)+"/database","_system");frontendConfig.authenticationEnabled===!1&&(c=arangoHelper.databaseUrl("/_api/database/user")),$(".wrong-credentials").hide(),b.loggedIn=!0,$.ajax(c).success(function(a){_.each(a.result,function(b,c){"rw"!==b&&delete a.result[c]}),$("#loginForm").hide(),$(".login-window #databases").show(),$("#loginDatabase").html(""),_.each(a.result,function(a,b){$("#loginDatabase").append("")}),b.renderDBS()}).error(function(){$(".wrong-credentials").show()})},renderDBS:function(){if(0===$("#loginDatabase").children().length)$("#dbForm").remove(),$(".login-window #databases").prepend('
"),a.disabled||$(b.subEl+" .bottom").children().last().bind("click",function(c){$("#subNavigationBar .breadcrumb").html(""),b.activeSubMenu=a,b.renderSubView(a,c)})})}},renderSubView:function(a,b){window.App[a.route]&&(window.App[a.route].resetState&&window.App[a.route].resetState(),window.App[a.route]()),$(this.subEl+" .bottom").children().removeClass("active"),
-$(b.currentTarget).addClass("active")},switchTab:function(a){var b=$(a.currentTarget).children().first().attr("id");return"enterprise"===b?void window.open("https://www.arangodb.com/download-arangodb-enterprise/","_blank"):void(b&&this.selectMenuItem(b+"-menu"))},selectMenuItem:function(a,b){void 0===a&&(a=window.location.hash.split("/")[0],a=a.substr(1,a.length-1)),""===a?a=window.App.isCluster?"cluster":"dashboard":"cNodes"!==a&&"dNodes"!==a||(a="nodes");try{this.renderSubMenu(a.split("-")[0])}catch(c){this.renderSubMenu(a)}$(".navlist li").removeClass("active"),"string"==typeof a&&(b?$("."+this.subViewConfig[a]+"-menu").addClass("active"):a&&($("."+a).addClass("active"),$("."+a+"-menu").addClass("active"))),arangoHelper.hideArangoNotifications()},showSubDropdown:function(a){$(a.currentTarget).find(".subBarDropdown").toggle()},showDropdown:function(a){var b=a.target||a.srcElement,c=b.id;"links"===c||"link_dropdown"===c||"links"===a.currentTarget.id?$("#link_dropdown").fadeIn(1):"tools"===c||"tools_dropdown"===c||"tools"===a.currentTarget.id?$("#tools_dropdown").fadeIn(1):"dbselection"!==c&&"dbs_dropdown"!==c&&"dbselection"!==a.currentTarget.id||$("#dbs_dropdown").fadeIn(1)},hideDropdown:function(a){$("#link_dropdown").fadeOut(1),$("#tools_dropdown").fadeOut(1),$("#dbs_dropdown").fadeOut(1)}})}(),function(){"use strict";window.NodesView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("nodesView.ejs"),interval:1e4,knownServers:[],events:{"click #nodesContent .coords-nodes .pure-table-row":"navigateToNode","click #nodesContent .coords-nodes .pure-table-row .fa-trash-o":"deleteNode","click #addCoord":"addCoord","click #removeCoord":"removeCoord","click #addDBs":"addDBs","click #removeDBs":"removeDBs","click .abortClusterPlan":"abortClusterPlanModal","keyup #plannedCoords":"checkKey","keyup #plannedDBs":"checkKey"},checkKey:function(a){if(13===a.keyCode){var b=this,c=function(a){var c;if("plannedCoords"===a.target.id)try{c=JSON.parse($("#plannedCoords").val()),"number"==typeof c?(window.modalView.hide(),b.setCoordSize(c)):arangoHelper.arangoError("Error","Invalid value. Must be a number.")}catch(a){arangoHelper.arangoError("Error","Invalid value. Must be a number.")}else if("plannedDBs"===a.target.id)try{c=JSON.parse($("#plannedCoords").val()),"number"==typeof c?(window.modalView.hide(),b.setDBsSize(c)):arangoHelper.arangoError("Error","Invalid value. Must be a number.")}catch(a){arangoHelper.arangoError("Error","Invalid value. Must be a number.")}};this.changePlanModal(c.bind(null,a))}},changePlanModal:function(a,b){var c=[],d=[];d.push(window.modalView.createReadOnlyEntry("plan-confirm-button","Caution","You are changing the cluster plan. Continue?",void 0,void 0,!1,/[<>&'"]/)),c.push(window.modalView.createSuccessButton("Yes",a.bind(this,b))),window.modalView.show("modalTable.ejs","Modify Cluster Size",c,d)},initialize:function(){var a=this;clearInterval(this.intervalFunction),window.App.isCluster&&(this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#nodes"===window.location.hash&&a.render(!1)},this.interval))},deleteNode:function(a){if(!$(a.currentTarget).hasClass("noHover")){var b=this,c=$(a.currentTarget.parentNode.parentNode).attr("node").slice(0,-5);return window.confirm("Do you want to delete this node?")&&$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_admin/cluster/removeServer"),contentType:"application/json",async:!0,data:JSON.stringify(c),success:function(a){b.render(!1)},error:function(){"#nodes"===window.location.hash&&arangoHelper.arangoError("Cluster","Could not fetch cluster information")}}),!1}},navigateToNode:function(a){if(!$(a.currentTarget).hasClass("noHover")){var b=$(a.currentTarget).attr("node").slice(0,-5);window.App.navigate("#node/"+encodeURIComponent(b),{trigger:!0})}},render:function(a){if("#nodes"===window.location.hash){var b=this;$("#content").is(":empty")&&arangoHelper.renderEmpty("Please wait. Requesting cluster information...","fa fa-spin fa-circle-o-notch"),a!==!1&&arangoHelper.buildNodesSubNav("Overview");var c=function(a){$.ajax({type:"GET",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",success:function(c){"#nodes"===window.location.hash&&b.continueRender(a,c)}})};$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,async:!0,success:function(a){"#nodes"===window.location.hash&&c(a.Health)},error:function(){"#nodes"===window.location.hash&&arangoHelper.arangoError("Cluster","Could not fetch cluster information")}})}},continueRender:function(a,b){var c={},d={},e=!1;_.each(a,function(a,b){"Coordinator"===a.Role?c[b]=a:"DBServer"===a.Role&&(d[b]=a)}),null!==b.numberOfDBServers&&null!==b.numberOfCoordinators&&(e=!0);var f=function(a){this.$el.html(this.template.render({coords:c,dbs:d,scaling:e,scaleProperties:a,plannedDBs:b.numberOfDBServers,plannedCoords:b.numberOfCoordinators})),e||($(".title").css("position","relative"),$(".title").css("top","-4px"),$(".sectionHeader .information").css("margin-top","-3px"))}.bind(this);this.renderCounts(e,f)},updatePlanned:function(a){a.numberOfCoordinators&&($("#plannedCoords").val(a.numberOfCoordinators),this.renderCounts(!0)),a.numberOfDBServers&&($("#plannedDBs").val(a.numberOfDBServers),this.renderCounts(!0))},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.updatePlanned(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.updatePlanned(c)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},abortClusterPlanModal:function(){var a=[],b=[];b.push(window.modalView.createReadOnlyEntry("plan-abort-button","Caution","You are aborting the planned cluster plan. All pending servers are going to be removed. Continue?",void 0,void 0,!1,/[<>&'"]/)),a.push(window.modalView.createSuccessButton("Yes",this.abortClusterPlan.bind(this))),window.modalView.show("modalTable.ejs","Modify Cluster Size",a,b)},abortClusterPlan:function(){window.modalView.hide();try{var a=JSON.parse($("#infoCoords > .positive > span").text()),b=JSON.parse($("#infoDBs > .positive > span").text());this.setCoordSize(a),this.setDBsSize(b)}catch(c){console.log(c),arangoHelper.arangoError("Plan","Could not abort Cluster Plan")}},renderCounts:function(a,b){var c=this,d=function(b,c,d,e){var f=''+c+'';d&&a===!0&&(f=f+''+d+''),e&&(f=f+''+e+''),$(b).html(f),a||($(".title").css("position","relative"),$(".title").css("top","-4px"))},e=function(a){var e=0,f=0,g=0,h=0,i=0,j=0;_.each(a,function(a){"Coordinator"===a.Role?"GOOD"===a.Status?f++:e++:"DBServer"===a.Role&&("GOOD"===a.Status?h++:i++)}),$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",processData:!1,success:function(a){g=Math.abs(f+e-a.numberOfCoordinators),j=Math.abs(h+i-a.numberOfDBServers),b?b({coordsPending:g,coordsOk:f,coordsErrors:e,dbsPending:j,dbsOk:h,dbsErrors:i}):(d("#infoDBs",h,j,i),d("#infoCoords",f,g,e)),c.isPlanFinished()||($(".scaleGroup").addClass("no-hover"),$("#plannedCoords").attr("disabled","disabled"),$("#plannedDBs").attr("disabled","disabled"))}})};$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,success:function(a){e(a.Health)}})},isPlanFinished:function(){var a;return a=!($("#infoDBs").find(".warning").length>0)&&!($("#infoCoords").find(".warning").length>0)},addCoord:function(){var a=function(){window.modalView.hide(),this.setCoordSize(this.readNumberFromID("#plannedCoords",!0))};this.isPlanFinished()?this.changePlanModal(a.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},removeCoord:function(){var a=function(){window.modalView.hide(),this.setCoordSize(this.readNumberFromID("#plannedCoords",!1,!0))};this.isPlanFinished()?this.changePlanModal(a.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},addDBs:function(){var a=function(){window.modalView.hide(),this.setDBsSize(this.readNumberFromID("#plannedDBs",!0))};this.isPlanFinished()?this.changePlanModal(a.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},removeDBs:function(){var a=function(){window.modalView.hide(),this.setDBsSize(this.readNumberFromID("#plannedDBs",!1,!0))};this.isPlanFinished()?this.changePlanModal(a.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},readNumberFromID:function(a,b,c){var d=$(a).val(),e=!1;try{e=JSON.parse(d)}catch(f){}return b&&e++,c&&1!==e&&e--,e},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.NodeView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("nodeView.ejs"),interval:5e3,dashboards:[],events:{},initialize:function(a){window.App.isCluster&&(this.coordinators=a.coordinators,this.dbServers=a.dbServers,this.coordname=a.coordname,this.updateServerTime())},breadcrumb:function(a){$("#subNavigationBar .breadcrumb").html("Node: "+a)},render:function(){this.$el.html(this.template.render({coords:[]}));var a=function(){this.continueRender(),this.breadcrumb(arangoHelper.getCoordinatorShortName(this.coordname)),$(window).trigger("resize")}.bind(this);this.initCoordDone||this.waitForCoordinators(),this.initDBDone?(this.coordname=window.location.hash.split("/")[1],this.coordinator=this.coordinators.findWhere({name:this.coordname}),a()):this.waitForDBServers(a)},continueRender:function(){var a=this;this.dashboards[this.coordinator.get("name")]=new window.DashboardView({dygraphConfig:window.dygraphConfig,database:window.App.arangoDatabase,serverToShow:{raw:this.coordinator.get("address"),isDBServer:!1,endpoint:this.coordinator.get("protocol")+"://"+this.coordinator.get("address"),target:this.coordinator.get("name")}}),this.dashboards[this.coordinator.get("name")].render(),window.setTimeout(function(){a.dashboards[a.coordinator.get("name")].resize()},500)},waitForCoordinators:function(a){var b=this;window.setTimeout(function(){0===b.coordinators.length?b.waitForCoordinators(a):(b.coordinator=b.coordinators.findWhere({name:b.coordname}),b.initCoordDone=!0,a&&a())},200)},waitForDBServers:function(a){var b=this;window.setTimeout(function(){0===b.dbServers[0].length?b.waitForDBServers(a):(b.initDBDone=!0,b.dbServer=b.dbServers[0],b.dbServer.each(function(a){"DBServer001"===a.get("name")&&(b.dbServer=a)}),a())},200)},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.NotificationView=Backbone.View.extend({events:{"click .navlogo #stat_hd":"toggleNotification","click .notificationItem .fa":"removeNotification","click #removeAllNotifications":"removeAllNotifications"},initialize:function(){this.collection.bind("add",this.renderNotifications.bind(this)),this.collection.bind("remove",this.renderNotifications.bind(this)),this.collection.bind("reset",this.renderNotifications.bind(this)),window.setTimeout(function(){frontendConfig.authenticationEnabled===!1&&frontendConfig.isCluster===!1&&arangoHelper.showAuthDialog()===!0&&window.arangoHelper.arangoWarning("Warning","Authentication is disabled. Do not use this setup in production mode.")},2e3)},notificationItem:templateEngine.createTemplate("notificationItem.ejs"),el:"#notificationBar",template:templateEngine.createTemplate("notificationView.ejs"),toggleNotification:function(){var a=this.collection.length;0!==a&&$("#notification_menu").toggle()},removeAllNotifications:function(){$.noty.clearQueue(),$.noty.closeAll(),this.collection.reset(),$("#notification_menu").hide()},removeNotification:function(a){var b=a.target.id;this.collection.get(b).destroy()},renderNotifications:function(a,b,c){if(c&&c.add){var d,e=this.collection.at(this.collection.length-1),f=e.get("title"),g=5e3,h=["click"];if(e.get("content")&&(f=f+": "+e.get("content")),"error"===e.get("type")?(g=!1,h=["button"],d=[{addClass:"button-danger",text:"Close",onClick:function(a){a.close()}}]):"warning"===e.get("type")&&(g=15e3,d=[{addClass:"button-warning",text:"Close",onClick:function(a){a.close()}},{addClass:"button-danger",text:"Don't show again.",onClick:function(a){a.close(),window.arangoHelper.doNotShowAgain()}}]),$.noty.clearQueue(),$.noty.closeAll(),noty({theme:"relax",text:f,template:'
"),$("#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]=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)}else{var c=function(a){b.rerenderGraphs(a,!0)};b.getCoordStatHistory(c)}},this.interval))},render:function(){var a=this;this.$el.html(this.template.render({})),this.initDone||(void 0!==this.coordinators.first()?this.getServerStatistics():this.waitForCoordinators(),this.initDone=!0),this.initGraphs();var b=function(b){a.rerenderValues(b)};this.getCoordStatHistory(b)},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")){a.knownServers.indexOf(c.id)===-1&&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")){a.knownServers.indexOf(b.id)===-1&&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&&g<90&&(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,b){if(this.statsEnabled){var c,d,e=this;this.formatDataForGraph(a),_.each(e.chartsOptions,function(a){d=e.returnGraphOptions(a.id),d.length>0?_.each(d,function(b,c){a.options[c].values=b}):a.options[0].values=[],c=a.options,void 0!==b&&b!==!1||c[0].values.length>0&&e.historyInit&&e.charts[a.id]&&e.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")||"corrupted"===this.model.get("status")?($(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:"corrupted"===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()),g<1||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","Indexes"],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(),"Indexes"!==$(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),h<1)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,journalSize: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. Total number of copies of the data in the cluster","",!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,reRender:!0,reRenderDistribution:!0,isVisible:!0,distributionCharts:{totalTimeDistribution:null,dataTransferDistribution:null},residentChart:null,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]),e<0?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=this,b=function(b,c){b?arangoHelper.arangoError("DB","Could not get current db properties"):(a.currentDB=c,a.collection.fetch({success:function(){a.collection.sort(),$(a.el).html(a.template.render({collection:a.collection,searchString:"",currentDB:a.currentDB})),a.dropdownVisible===!0&&($("#dbSortDesc").attr("checked",a.collection.sortOptions.desc),$("#databaseToggle").toggleClass("activated"),$("#databaseDropdown2").show()),arangoHelper.setCheckboxStatus("#databaseDropdown"),a.replaceSVGs()}}))};return this.collection.getCurrentDatabase(b),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_-]*$/)||(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 a.get("name").indexOf(b)!==-1}),$(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(){var a=!1;_.each($(".documentsDropdown").first().children(),function(b){$(b).is(":visible")&&(a=!0)}),a?($("#docPureTable").height($(".centralRow").height()-210-57),$("#docPureTable .pure-table-body").css("max-height",$("#docPureTable").height()-47)):($("#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(){$(".upload-indicator").show()},hideSpinner:function(){$(".upload-indicator").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.hideImportModal(),this.resetView()),this.hideSpinner()}.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(1),$("#exportHeader").hide();var a=this;window.setTimeout(function(){a.resize()},50)},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(1);var a=this;window.setTimeout(function(){a.resize()},50);var b;for(b in this.filters)if(this.filters.hasOwnProperty(b))return void $("#attribute_name"+b).focus()},exportCollection:function(){$("#importCollection").removeClass("activated"),$("#filterHeader").removeClass("activated"),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),$("#exportCollection").toggleClass("activated"),this.markFilterToggle(),$("#exportHeader").slideToggle(1),$("#importHeader").hide(),$("#filterHeader").hide(),$("#editHeader").hide();var a=this;window.setTimeout(function(){a.resize()},50)},importCollection:function(){this.markFilterToggle(),$("#markDocuments").removeClass("activated"),this.changeEditMode(!1),$("#importCollection").toggleClass("activated"),$("#exportCollection").removeClass("activated"),$("#importHeader").slideToggle(1),$("#filterHeader").hide(),$("#editHeader").hide(),$("#exportHeader").hide();var a=this;window.setTimeout(function(){a.resize()},50)},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)}),a.rerender()},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;a<=b;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,d){if(b)arangoHelper.arangoError("Error",d.errorMessage);else{window.modalView.hide(),c=c._id.split("/");try{a="collection/"+c[0]+"/"+c[1],decodeURI(a)}catch(e){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,d){if(b)arangoHelper.arangoError("Error",d.errorMessage);else{window.modalView.hide(),c=c.split("/");try{a="collection/"+c[0]+"/"+c[1],decodeURI(a)}catch(e){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,b){a?arangoHelper.arangoError("Error",b.responseJSON.errorMessage):(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,b){a?arangoHelper.arangoError("Error",b.responseJSON.errorMessage):(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(''),window.modalView.hide(),$("#offlinePlaceholder").show(),$.noty.clearQueue(),$.noty.closeAll(),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===b?$(".health-state").html(b+" NODE ERROR"):$(".health-state").html(b+" 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,f;this._upgrade?(c=this.mount,e=Boolean($("#new-app-teardown").prop("checked"))):c=window.arangoHelper.escapeHtml($("#new-app-mount").val()),f=Boolean($("#zip-app-islegacy").prop("checked")),this.collection.installFromZip(b.filename,c,d.bind(this),f,e)}},l=function(){if(window.modalView.modalTestAll()){var a,b,c,e,f;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 g={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(h){return}f=Boolean($("#github-app-islegacy").prop("checked")),this.collection.installFromGithub(g,c,d.bind(this),f,e)}},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())};this.collection.generate(c,a,d.bind(this),b)}},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 #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"),"smartGraph"===b?(this.toggleSmartGraph(),$("#createGraph").addClass("active"),this.showSmartGraphOptions()):(this.toggleSmartGraph(),this.hideSmartGraphOptions())},hideSmartGraphOptions:function(){$("#row_general-numberOfShards").show(),$("#smartGraphInfo").hide(),$("#row_new-numberOfShards").hide(),$("#row_new-smartGraphAttribute").hide()},showSmartGraphOptions:function(){$("#row_general-numberOfShards").hide(),$("#smartGraphInfo").show(),$("#row_new-numberOfShards").show(),$("#row_new-smartGraphAttribute").show()},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)+"/"+encodeURIComponent(b)},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)}})},toggleSmartGraph:function(){var a,b=this;if($("#tab-smartGraph").parent().hasClass("active")){var c=[],d=this.options.collectionCollection.models;for(d.forEach(function(a){a.get("isSystem")||c.push(a.id)}),a=0;a0&&(j.options={numberOfShards:$("#general-numberOfShards").val()});this.collection.create(j,{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)}})},createEditGraphModal:function(a,b){var c,d=[],e=[],f=[],g=this.options.collectionCollection.models,h=this,i="",j=[{collection:"",from:"",to:""}],k="",l=function(a,b){return a=a.toLowerCase(),b=b.toLowerCase(),ab?1:0};if(this.eCollList=[],this.removedECollList=[],g.forEach(function(a){a.get("isSystem")||("edge"===a.get("type")?h.eCollList.push(a.id):e.push(a.id))}),window.modalView.enableHotKeys=!1,this.counter=0,a?(c=b?"Edit Smart Graph":"Edit Graph",i=a.get("_key"),j=a.get("edgeDefinitions"),j&&0!==j.length||(j=[{collection:"",from:"",to:""}]),k=a.get("orphanCollections"),f.push(window.modalView.createReadOnlyEntry("editGraphName","Name",i,"The name to identify the graph. Has to be unique")),b&&f.push(window.modalView.createReadOnlyEntry("smartGraphAttribute","Smart Graph Attribute",a.get("smartGraphAttribute"),"The attribute name that is used to smartly shard the vertices of a graph. \nEvery vertex in this Graph has to have this attribute. \n")),a.get("numberOfShards")&&f.push(window.modalView.createReadOnlyEntry("numberOfShards","Shards",a.get("numberOfShards"),"Number of shards the graph is using.")),d.push(window.modalView.createDeleteButton("Delete",this.deleteGraph.bind(this))),d.push(window.modalView.createNotificationButton("Reset display settings",this.resetDisplaySettings.bind(this))),d.push(window.modalView.createSuccessButton("Save",this.saveEditedGraph.bind(this)))):(c="Create Graph",f.push(window.modalView.createTextEntry("createNewGraphName","Name","","The name to identify the graph. Has to be unique.","graphName",!0)),d.push(window.modalView.createSuccessButton("Create",this.createNewGraph.bind(this)))),j.forEach(function(b){frontendConfig.isEnterprise===!0&&frontendConfig.isCluster&&(f.push(window.modalView.createTextEntry("new-numberOfShards","Shards*","","Number of shards the smart graph is using.","",!1,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),f.push(window.modalView.createTextEntry("new-smartGraphAttribute","Smart Graph Attribute*","","The attribute name that is used to smartly shard the vertices of a graph. \nEvery vertex in this Graph has to have this attribute. \nCannot be modified later.","",!1,[{rule:Joi.string().allow("").optional(),msg:"Must be a string."}]))),frontendConfig.isCluster&&!a&&f.push(window.modalView.createTextEntry("general-numberOfShards","Shards","","Number of shards the graph is using.","",!1,[{rule:Joi.string().allow("").optional().regex(/^[0-9]*$/),msg:"Must be a number."}])),0===h.counter?(b.collection&&(h.removedECollList.push(b.collection),h.eCollList.splice(h.eCollList.indexOf(b.collection),1)),f.push(window.modalView.createSelect2Entry("newEdgeDefinitions"+h.counter,"Edge definitions",b.collection,"An edge definition defines a relation of the graph","Edge definitions",!0,!1,!0,1,h.eCollList.sort(l)))):f.push(window.modalView.createSelect2Entry("newEdgeDefinitions"+h.counter,"Edge definitions",b.collection,"An edge definition defines a relation of the graph","Edge definitions",!1,!0,!1,1,h.eCollList.sort(l))),f.push(window.modalView.createSelect2Entry("fromCollections"+h.counter,"fromCollections",b.from,"The collections that contain the start vertices of the relation.","fromCollections",!0,!1,!1,10,e.sort(l))),f.push(window.modalView.createSelect2Entry("toCollections"+h.counter,"toCollections",b.to,"The collections that contain the end vertices of the relation.","toCollections",!0,!1,!1,10,e.sort(l))),h.counter++}),f.push(window.modalView.createSelect2Entry("newVertexCollections","Vertex collections",k,"Collections that are part of a graph but not used in an edge definition","Vertex Collections",!1,!1,!1,10,e.sort(l))),window.modalView.show("modalGraphTable.ejs",c,d,f,void 0,void 0,this.events),$("#tab-createGraph").parent().hasClass("active")&&h.hideSmartGraphOptions(),a){$(".modal-body table").css("border-collapse","separate");var m;for($(".modal-body .spacer").remove(),m=0;m<=this.counter;m++)$("#row_fromCollections"+m).show(),$("#row_toCollections"+m).show(),$("#row_newEdgeDefinitions"+m).addClass("first"),$("#row_fromCollections"+m).addClass("middle"),$("#row_toCollections"+m).addClass("last"),$("#row_toCollections"+m).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:"Startnode",desc:"A valid node id. If empty, a random node will be chosen.",value:2},layout:{type:"select",name:"Layout",desc:"Different graph algorithms. No overlap is very fast (more than 5000 nodes), force is slower (less than 5000 nodes) and fruchtermann is the slowest (less than 500 nodes).",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 (experimental)",val:"webgl"}},depth:{desc:"Search depth, starting from your start node.",type:"number",name:"Search Depth",value:2},limit:{desc:"Limit nodes count. If empty or zero, no limit is set.",type:"number",name:"Limit",value:250}},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:"Add Collection Name",desc:"Append collection name to the label?",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},nodeColorByCollection:{type:"select",name:"Color By Collections",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."},nodeColor:{type:"color",name:"Color",desc:"Default node color. RGB or HEX value.","default":"#2ecc71"},nodeColorAttribute:{type:"string",name:"Color Attribute",desc:"If an attribute is given, nodes will then be colorized by the attribute. This setting ignores default node color if set."},nodeSizeByEdges:{type:"select",name:"Size By Connections",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"},desc:"Should nodes be sized by their edges count? If enabled, node sizing 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:"Add Collection Name",desc:"Set label text by collection. If activated edge label attribute will be ignored.",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"}},edgeColorByCollection:{type:"select",name:"Color By Collections",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."},edgeColor:{type:"color",name:"Color",desc:"Default edge color. RGB or HEX value.","default":"#cccccc"},edgeColorAttribute:{type:"string",name:"Color Attribute",desc:"If an attribute is given, edges will then be colorized by the attribute. This setting ignores default edge color if set."},edgeEditable:{type:"select",hide:"true",name:"Editable",yes:{name:"Yes",val:"true"},no:{name:"No",val:"false"},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,a.noDefinedGraph&&(this.noDefinedGraph=a.noDefinedGraph)},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",'focusout #graphSettingsView input[type="text"]':"checkinput"},lastFocus:function(a){this.lastFocussed=a.currentTarget.id,this.lastFocussedValue=$(a.currentTarget).val()},checkinput:function(a){new Date-this.lastSaved>500&&a.currentTarget.id===this.lastFocussed&&this.lastFocussedValue!==$(a.currentTarget).val()&&this.saveGraphSettings()},checkEnterKey:function(a){13===a.keyCode&&this.saveGraphSettings(a)},getGraphSettings:function(a){var b=this,c=frontendConfig.db+"_"+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,e,f){var g=this,h=function(){var a=!$("#g_nodeColor").is(":disabled"),b=!$("#g_edgeColor").is(":disabled");window.App.graphViewer.updateColors(a,b,$("#g_nodeColor").val(),$("#g_edgeColor").val())};if(this.noDefinedGraph){var i;b?h():"g_layout"===a.currentTarget.id?window.App.graphViewer.rerenderAQL($("#g_layout").val(),null):"g_nodeColorByCollection"===a.currentTarget.id?(i=$("#g_nodeColorByCollection").val(),"true"===i?window.App.graphViewer.switchNodeColorByCollection(!0):window.App.graphViewer.switchNodeColorByCollection(!1)):"g_edgeColorByCollection"===a.currentTarget.id?(i=$("#g_edgeColorByCollection").val(),"true"===i?window.App.graphViewer.switchEdgeColorByCollection(!0):window.App.graphViewer.switchEdgeColorByCollection(!1)):"g_nodeSizeByEdges"===a.currentTarget.id?(i=$("#g_nodeSizeByEdges").val(),"true"===i?window.App.graphViewer.switchNodeSizeByCollection(!0):window.App.graphViewer.switchNodeSizeByCollection(!1)):"g_edgeType"===a.currentTarget.id&&window.App.graphViewer.switchEdgeType($("#g_edgeType").val())}else{g.lastSaved=new Date;var j=frontendConfig.db+"_"+this.name,k={};if(d)k[j]=d;else{var l,m={};$("#graphSettingsView select").each(function(a,b){l=b.id,m[l.substr(2,b.id.length)]=$(b).val()}),$("#graphSettingsView input").each(function(a,b){l=b.id,m[l.substr(2,b.id.length)]=$(b).val()}),k[j]=m}c&&(k[j].nodeStart=c);var n=function(){if(window.App.graphViewer){var c;if(a){if("g_layout"===a.currentTarget.id)return void window.App.graphViewer.switchLayout($("#g_layout").val());if("g_nodeColorByCollection"===a.currentTarget.id)return c=$("#g_nodeColorByCollection").val(),void("true"===c?window.App.graphViewer.switchNodeColorByCollection(!0):$("#g_nodeColorAttribute").is(":disabled")?window.App.graphViewer.switchNodeColorByCollection(!1):window.App.graphViewer.switchNodeColorByCollection(!1,!0));if("g_edgeColorByCollection"===a.currentTarget.id)return c=$("#g_edgeColorByCollection").val(),void("true"===c?window.App.graphViewer.switchEdgeColorByCollection(!0):$("#g_nodeColorAttribute").is(":disabled")?window.App.graphViewer.switchEdgeColorByCollection(!1):window.App.graphViewer.switchEdgeColorByCollection(!1,!0))}""!==b&&void 0!==b?h():window.App.graphViewer.render(g.lastFocussed)}else e||arangoHelper.arangoNotification("Graph "+this.name,"Configuration saved.");f&&f()}.bind(this);this.userConfig.setItem("graphs",k,n)}this.handleDependencies()},setDefaults:function(a,b,c){var d={layout:"force",renderer:"canvas",depth:"2",limit:"250",nodeColor:"#2ecc71",nodeColorAttribute:"",nodeColorByCollection:"true",edgeColor:"#cccccc",edgeColorAttribute:"",edgeColorByCollection:"false",nodeLabel:"_key",edgeLabel:"",edgeType:"arrow",nodeSize:"",nodeSizeByEdges:"true",edgeEditable:"true",nodeLabelByCollection:"false",edgeLabelByCollection:"false",nodeStart:"",barnesHutOptimize:!0};a===!0?b?this.saveGraphSettings(null,null,null,d,b,c):this.saveGraphSettings(null,null,null,d):(this.saveGraphSettings(null,null,null,d,null),this.render(),window.App.graphViewer.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.noDefinedGraph?this.continueRender():(this.getGraphSettings(!0),this.lastSaved=new Date)},handleDependencies:function(){"true"===$("#g_nodeSizeByEdges").val()?$("#g_nodeSize").prop("disabled",!0):$("#g_nodeSize").removeAttr("disabled"),"true"===$("#g_nodeColorByCollection").val()?($("#g_nodeColorAttribute").prop("disabled",!0),
+$("#g_nodeColor").prop("disabled",!0)):($("#g_nodeColorAttribute").removeAttr("disabled"),$("#g_nodeColor").removeAttr("disabled")),this.noDefinedGraph||""!==$("#g_nodeColorAttribute").val()&&$("#g_nodeColor").prop("disabled",!0),"true"===$("#g_edgeColorByCollection").val()?($("#g_edgeColorAttribute").prop("disabled",!0),$("#g_edgeColor").prop("disabled",!0)):($("#g_edgeColorAttribute").removeAttr("disabled"),$("#g_edgeColor").removeAttr("disabled")),this.noDefinedGraph||""!==$("#g_edgeColorAttribute").val()&&$("#g_edgeColor").prop("disabled",!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)}):this.noDefinedGraph?this.fitSettingsAQLMode():this.setDefaults(!0),this.handleDependencies()},fitSettingsAQLMode:function(){var a=["g_nodeStart","g_depth","g_limit","g_renderer","g_nodeLabel","g_nodeLabelByCollection","g_nodeColorAttribute","g_nodeSize","g_edgeLabel","g_edgeColorAttribute","g_edgeLabelByCollection"];_.each(a,function(a){$("#"+a).parent().prev().remove(),$("#"+a).parent().remove()}),$("#saveGraphSettings").remove(),$("#restoreGraphSettings").remove(),$("#g_nodeColorByCollection").val("false"),$("#g_edgeColorByCollection").val("false"),$("#g_nodeSizeByEdges").val("false"),$("#g_edgeType").val("arrow"),$("#g_layout").val("force")}})}(),function(){"use strict";window.GraphViewer=Backbone.View.extend({el:"#content",remove:function(){return this.$el.empty().off(),this.stopListening(),this.unbind(),delete this.el,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),a.noDefinedGraph&&(this.noDefinedGraph=a.noDefinedGraph,this.graphData=a.data),this.name=a.name,this.userConfig=a.userConfig,this.documentStore=a.documentStore,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"],jans:["rgba(166, 109, 161, 1)","rgba(64, 74, 83, 1)","rgba(90, 147, 189, 1)","rgba(153,63,0,1)","rgba(76,0,92,1)","rgba(25,25,25,1)","rgba(0,92,49,1)","rgba(43,206,72,1)","rgba(255,204,153,1)","rgba(128,128,128,1)","rgba(148,255,181,1)","rgba(143,124,0,1)","rgba(157,204,0,1)","rgba(194,0,136,1)","rgba(0,51,128,1)","rgba(255,164,5,1)","rgba(255,168,187,1)","rgba(66,102,0,1)","rgba(255,0,16,1)","rgba(94,241,242,1)","rgba(0,153,143,1)","rgba(224,255,102,1)","rgba(116,10,255,1)","rgba(153,0,0,1)","rgba(255,255,128,1)","rgba(255,255,0,1)","rgba(255,80,5,1)"],gv:["#68BDF6","#6DCE9E","#FF756E","#DE9BF9","#FB95AF","#FFD86E","#A5ABB6"]},activeNodes:[],selectedNodes:{},aqlMode:!1,events:{"click #downloadPNG":"downloadPNG","click #loadFullGraph":"loadFullGraphModal","click #reloadGraph":"reloadGraph","click #settingsMenu":"toggleSettings","click #toggleForce":"toggleLayout","click #selectNodes":"toggleLasso"},cursorX:0,cursorY:0,layouting:!1,model:null,viewStates:{captureMode:!1},graphConfig:null,graphSettings:null,downloadPNG:function(){var a=parseInt($("#graph-container").width(),10);sigma.plugins.image(this.currentGraph,this.currentGraph.renderers[0],{download:!0,size:a,clip:!0,labels:!0,background:"white",zoom:!1})},loadFullGraphModal:function(){var a=[],b=[];b.push(window.modalView.createReadOnlyEntry("load-full-graph-a","Caution","Really load full graph? If no limit is set, your result set could be too big.")),a.push(window.modalView.createSuccessButton("Load full graph",this.loadFullGraph.bind(this))),window.modalView.show("modalTable.ejs","Load full graph",a,b)},loadFullGraph:function(){var a=this,b={};this.graphConfig&&(b=_.clone(this.graphConfig),delete b.layout,delete b.edgeType,delete b.renderer),b.mode="all",$.ajax({type:"GET",url:arangoHelper.databaseUrl("/_admin/aardvark/graph/"+encodeURIComponent(this.name)),contentType:"application/json",data:b,success:function(b){a.killCurrentGraph(),a.renderGraph(b)},error:function(a){console.log(a),arangoHelper.arangoError("Graph","Could not load full graph.")}}),window.modalView.hide()},resize:function(){$("#graph-container").width($(".centralContent").width()),$("#graph-container").height($(".centralRow").height()-155)},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),this.initFullscreen()},initFullscreen:function(){var a=this;if(window.App.initializedFullscreen===!1||void 0===window.App.initializedFullscreen){window.App.initializedFullscreen=!0,this.isFullscreen=!1;var b=function(b){(document.webkitIsFullScreen||document.mozFullScreen||null!==document.msFullscreenElement)&&(a.isFullscreen===!1?(a.isFullscreen=!0,$("#toggleForce").css("bottom","10px"),$("#toggleForce").css("right","10px"),$("#objectCount").css("bottom","10px"),$("#objectCount").css("left","10px"),$(".nodeInfoDiv").css("top","10px"),$(".nodeInfoDiv").css("left","10px")):(a.isFullscreen=!1,$("#toggleForce").css("bottom","40px"),$("#toggleForce").css("right","40px"),$("#objectCount").css("bottom","50px"),$("#objectCount").css("left","25px"),$(".nodeInfoDiv").css("top",""),$(".nodeInfoDiv").css("left","165px")))};document.addEventListener&&(document.addEventListener("webkitfullscreenchange",b,!1),document.addEventListener("mozfullscreenchange",b,!1),document.addEventListener("fullscreenchange",b,!1),document.addEventListener("MSFullscreenChange",b,!1))}},renderAQLPreview: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);var c=!1;try{this.renderGraph(this.graphData.modified,null,!0),c=!0}catch(d){}return c},renderAQL:function(a){this.$el.html(this.template.render({})),$("#subNavigationBar .breadcrumb").html("AQL Graph"),$("#subNavigationBar .bottom").html(""),$(".queries-menu").removeClass("active"),this.resize(),this.graphData.modified=this.parseData(this.graphData.original,this.graphData.graphInfo),this.renderGraph(this.graphData.modified,null,!1),this.initFullscreen(),this.graphSettingsView=new window.GraphSettingsView({name:this.name,userConfig:void 0,saveCallback:void 0,noDefinedGraph:!0}),this.graphSettingsView.render()},killCurrentGraph:function(){for(var a in this.currentGraph.renderers)try{this.currentGraph.renderers[a].clear(),this.currentGraph.kill(a)}catch(b){}},rerenderAQL:function(a,b){this.killCurrentGraph(),this.renderGraph(this.graphData.modified,null,!1,a,"canvas"),"true"===$("#g_nodeColorByCollection").val()?this.switchNodeColorByCollection(!0):$("#g_nodeColor").is(":disabled")?this.updateColors(!0,!0,null,null,!0):this.ncolor?this.updateColors(!0,!0,this.ncolor,this.ecolor):this.updateColors(!0,!0,"#2ecc71","#2ecc71"),"true"===$("#g_edgeColorByCollection").val()?this.switchEdgeColorByCollection(!0):$("#g_edgeColor").is(":disabled")?this.updateColors(!0,!0,null,null,!0):this.ecolor?this.updateColors(!0,!0,this.ncolor,this.ecolor):this.updateColors(!0,!0,"#2ecc71","#2ecc71")},buildCollectionColors:function(){var a=this;if(!a.collectionColors){a.collectionColors={};var b=0,c={},d={};_.each(this.currentGraph.graph.nodes(),function(a){c[a.id]=void 0}),_.each(a.currentGraph.graph.edges(),function(a){d[a.id]=void 0}),_.each(c,function(c,d){void 0===a.collectionColors[d.split("/")[0]]&&(a.collectionColors[d.split("/")[0]]={color:a.colors.jans[b]},b++)}),b=0,_.each(d,function(c,d){void 0===a.collectionColors[d.split("/")[0]]&&(a.collectionColors[d.split("/")[0]]={color:a.colors.jans[b]},b++)})}},switchNodeColorByCollection:function(a,b){var c=this;c.buildCollectionColors(),a?(c.currentGraph.graph.nodes().forEach(function(a){a.color=c.collectionColors[a.id.split("/")[0]].color}),c.currentGraph.refresh()):b?this.updateColors(!0,null,null,null,b):this.ncolor?this.updateColors(!0,null,this.ncolor,this.ecolor):this.updateColors(!0,null,"#2ecc71","#2ecc71")},switchEdgeColorByCollection:function(a,b){var c=this;c.buildCollectionColors(),a?(c.currentGraph.graph.edges().forEach(function(a){a.color=c.collectionColors[a.id.split("/")[0]].color}),c.currentGraph.refresh()):b?this.updateColors(!0,null,null,null,b):this.ecolor?this.updateColors(null,!0,this.ncolor,this.ecolor):this.updateColors(null,!0,"#2ecc71","#2ecc71")},buildCollectionSizes:function(){var a=this;if(!a.nodeEdgesCount){a.nodeEdgesCount={};var b={};_.each(this.currentGraph.graph.edges(),function(c){void 0===b[c.id]&&(b[c.id]=!0,void 0===a.nodeEdgesCount[c.source]?a.nodeEdgesCount[c.source]=1:a.nodeEdgesCount[c.source]+=1,void 0===a.nodeEdgesCount[c.target]?a.nodeEdgesCount[c.target]=1:a.nodeEdgesCount[c.target]+=1)})}},switchNodeSizeByCollection:function(a){var b=this;a?(b.buildCollectionSizes(),b.currentGraph.graph.nodes().forEach(function(a){a.size=b.nodeEdgesCount[a.id]})):b.currentGraph.graph.nodes().forEach(function(a){a.size=15}),b.currentGraph.refresh()},switchEdgeType:function(a){var b={nodes:this.currentGraph.graph.nodes(),edges:this.currentGraph.graph.edges(),settings:{}};this.killCurrentGraph(),this.renderGraph(b,null,!1,null,null,a)},switchLayout:function(a){var b={nodes:this.currentGraph.graph.nodes(),edges:this.currentGraph.graph.edges(),settings:{}};this.killCurrentGraph(),this.renderGraph(b,null,!1,a),"true"===$("#g_nodeColorByCollection").val()&&this.switchNodeColorByCollection(!0),"true"===$("#g_edgeColorByCollection").val()?this.switchEdgeColorByCollection(!0):this.switchEdgeColorByCollection(!1)},parseData:function(a,b){var c={},d={},e="#2ecc71",f={nodes:[],edges:[],settings:{}};if(this.ncolor&&(e=this.ncolor),"object"===b){_.each(a,function(a){a.edges&&a.vertices&&(_.each(a.edges,function(a){null!==a&&(d[a._id]={id:a._id,source:a._from,color:"#cccccc",target:a._to})}),_.each(a.vertices,function(a){null!==a&&(c[a._id]={id:a._id,label:a._key,size:.3,color:e,x:Math.random(),y:Math.random()})}))});var g=[];_.each(c,function(a){f.nodes.push(a),g.push(a.id)}),_.each(d,function(a){g.includes(a.source)&&g.includes(a.target)&&f.edges.push(a)})}else"array"===b&&(_.each(a,function(a){c[a._from]=null,c[a._to]=null,f.edges.push({id:a._id,source:a._from,color:"#cccccc",target:a._to})}),_.each(c,function(a,b){f.nodes.push({id:b,label:b,size:.3,color:e,x:Math.random(),y:Math.random()})}));return f},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 navigate to: Graphs ViewClick the settings icon and reset the display settings.It is possible that the graph is too big to be handled by the browser.
'),g.startLayout();var q=250,r=500;a.nodes&&(q=a.nodes.length,c?q<250?q=250:q+=r:(q<=250&&(q=500),q+=r)),a.empty&&arangoHelper.arangoNotification("Graph","Your graph is empty. Click inside the white window to create your first node."),window.setTimeout(function(){g.stopLayout()},q)}else"fruchtermann"===g.algorithm&&sigma.layouts.fruchtermanReingold.start(k);"force"!==g.algorithm&&g.reInitDragListener();var s=document.getElementsByClassName("sigma-mouse")[0];s.addEventListener("mousemove",g.trackCursorPosition.bind(this),!1),b&&($("#"+b).focus(),$("#graphSettingsContent").animate({scrollTop:$("#"+b).offset().top},2e3)),$("#calculatingGraph").fadeOut("slow"),c||g.graphConfig&&"false"===g.graphConfig.nodeSizeByEdges,g.calcFinished=new Date,a.empty===!0&&$(".sigma-background").before('The graph is empty. Please right-click to add a node.'),g.graphNotInitialized===!0&&(g.updateColors(g.tmpGraphArray),g.graphNotInitialized=!1,g.tmpGraphArray=[]),"force"===g.algorithm?$("#toggleForce").fadeIn("fast"):$("#toggleForce").fadeOut("fast")},reInitDragListener:function(){var a=this;void 0!==this.dragListener&&(sigma.plugins.killDragNodes(this.currentGraph),this.dragListener={}),this.dragListener=sigma.plugins.dragNodes(this.currentGraph,this.currentGraph.renderers[0]),this.dragListener.bind("drag",function(b){a.dragging=!0}),this.dragListener.bind("drop",function(b){window.setTimeout(function(){a.dragging=!1},400)})},keyUpFunction:function(a){var b=this;switch(a.keyCode){case 76:a.altKey&&b.toggleLasso()}},toggleLayout:function(){this.layouting?this.stopLayout():this.startLayout()},startLayout:function(a,b){var c=this;this.currentGraph.settings("drawLabels",!1),this.currentGraph.settings("drawEdgeLabels",!1),sigma.plugins.killDragNodes(this.currentGraph),a===!0&&(this.currentGraph.killForceAtlas2(),window.setTimeout(function(){c.stopLayout(),b&&c.currentGraph.refresh({skipIndexation:!0})},500)),$("#toggleForce .fa").removeClass("fa-play").addClass("fa-pause"),$("#toggleForce span").html("Stop layout"),this.layouting=!0,this.aqlMode?this.currentGraph.startForceAtlas2({worker:!0}):this.currentGraph.startForceAtlas2({worker:!0})},stopLayout:function(){$("#toggleForce .fa").removeClass("fa-pause").addClass("fa-play"),$("#toggleForce span").html("Resume layout"),this.layouting=!1,this.currentGraph.stopForceAtlas2(),this.currentGraph.settings("drawLabels",!0),this.currentGraph.settings("drawEdgeLabels",!0),this.currentGraph.refresh({skipIndexation:!0}),this.reInitDragListener()}})}(),function(){"use strict";window.HelpUsView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("helpUsView.ejs"),render:function(){this.$el.html(this.template.render({}))}})}(),function(){"use strict";window.IndicesView=Backbone.View.extend({el:"#content",initialize:function(a){this.collectionName=a.collectionName,this.model=this.collection},template:templateEngine.createTemplate("indicesView.ejs"),events:{},render:function(){$(this.el).html(this.template.render({model:this.model})),this.breadcrumb(),window.arangoHelper.buildCollectionSubNav(this.collectionName,"Indexes"),this.getIndex()},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},getIndex:function(){var a=function(a,b,c){a?window.arangoHelper.arangoError("Index",b.errorMessage):this.renderIndex(b,c)}.bind(this);this.model.getIndex(a)},createIndex:function(){var a,b,c,d=this,e=$("#newIndexType").val(),f={};switch(e){case"Geo":a=$("#newGeoFields").val();var g=d.checkboxToValue("#newGeoJson");f={type:"geo",fields:d.stringToArray(a),geoJson:g};break;case"Persistent":a=$("#newPersistentFields").val(),b=d.checkboxToValue("#newPersistentUnique"),c=d.checkboxToValue("#newPersistentSparse"),f={type:"persistent",fields:d.stringToArray(a),unique:b,sparse:c};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 h=parseInt($("#newFulltextMinLength").val(),10)||0;f={type:"fulltext",fields:d.stringToArray(a),minLength:h};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 i=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.toggleNewIndexView(),d.render()};this.model.createIndex(f,i)},bindIndexEvents:function(){this.unbindIndexEvents();var a=this;$("#indexEditView #addIndex").bind("click",function(){a.toggleNewIndexView(),$("#cancelIndex").unbind("click"),$("#cancelIndex").bind("click",function(){a.toggleNewIndexView(),a.render()}),$("#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(),"Indexes"!==$(a.currentTarget).html()||$(a.currentTarget).parent().hasClass("active")||($("#newIndexView").hide(),$("#indexEditView").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-danger").hide(),$("#indexHeaderContent #modal-dialog .modal-footer .button-success").hide(),$("#indexHeaderContent #modal-dialog .modal-footer .button-notification").hide()),"General"===$(a.currentTarget).html()&&!$(a.currentTarget).parent().hasClass("active")){$("#indexHeaderContent #modal-dialog .modal-footer .button-danger").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-success").show(),$("#indexHeaderContent #modal-dialog .modal-footer .button-notification").show();var b=$(".index-button-bar2")[0];$("#cancelIndex").is(":visible")&&($("#cancelIndex").detach().appendTo(b),$("#createIndex").detach().appendTo(b))}})},prepDeleteIndex:function(a){var b=this;this.lastTarget=a,this.lastId=$(this.lastTarget.currentTarget).parent().parent().first().children().first().text(),$("#content #modal-dialog .modal-footer").after('
Really delete?
'),$("#indexHeaderContent #indexConfirmDelete").unbind("click"),$("#indexHeaderContent #indexConfirmDelete").bind("click",function(){$("#indexHeaderContent #indexDeleteModal").remove(),b.deleteIndex()}),$("#indexHeaderContent #indexAbortDelete").unbind("click"),$("#indexHeaderContent #indexAbortDelete").bind("click",function(){$("#indexHeaderContent #indexDeleteModal").remove()})},unbindIndexEvents:function(){$("#indexHeaderContent #indexEditView #addIndex").unbind("click"),$("#indexHeaderContent #newIndexType").unbind("change"),$("#indexHeaderContent #infoTab a").unbind("click"),$("#indexHeaderContent .deleteIndex").unbind("click")},deleteIndex:function(){var a=function(a){a?(arangoHelper.arangoError("Could not delete index"),$("tr th:contains('"+this.lastId+"')").parent().children().last().html(''),this.model.set("locked",!1)):a||void 0===a||($("tr th:contains('"+this.lastId+"')").parent().remove(),this.model.set("locked",!1))}.bind(this);this.model.set("locked",!0),this.model.deleteIndex(this.lastId,a),$("tr th:contains('"+this.lastId+"')").parent().children().last().html('')},renderIndex:function(a,b){this.index=a;var c=function(a,c){if(a)arangoHelper.arangoError("Jobs","Could not read pending jobs.");else{var d=function(a,b,c){a?404===b.responseJSON.code?arangoHelper.deleteAardvarkJob(c):400===b.responseJSON.code?(arangoHelper.arangoError("Index creation failed",b.responseJSON.errorMessage),arangoHelper.deleteAardvarkJob(c)):204===b.responseJSON.code&&arangoHelper.arangoMessage("Index","There is at least one new index in the queue or in the process of being created."):arangoHelper.deleteAardvarkJob(c)};_.each(c,function(a){a.collection===b&&$.ajax({type:"PUT",cache:!1,url:arangoHelper.databaseUrl("/_api/job/"+a.id),contentType:"application/json",success:function(b,c,e){d(!1,b,a.id)},error:function(b){d(!0,b,a.id)}})})}};arangoHelper.getAardvarkJobs(c);var d="collectionInfoTh modal-text";if(this.index){var e="",f="";_.each(this.index.indexes,function(a){f="primary"===a.type||"edge"===a.type?'':'',void 0!==a.fields&&(e=a.fields.join(", "));var b=a.id.indexOf("/"),c=a.id.substr(b+1,a.id.length),g=a.hasOwnProperty("selectivityEstimate")?(100*a.selectivityEstimate).toFixed(2)+"%":"n/a",h=a.hasOwnProperty("sparse")?a.sparse:"n/a";$("#collectionEditIndexTable").append("
"+c+"
"+a.type+"
"+a.unique+"
"+h+"
"+g+"
"+e+"
"+f+"
")})}this.bindIndexEvents()},selectIndexType:function(){$(".newIndexClass").hide();var a=$("#newIndexType").val();$("#newIndexType"+a).show()},resetIndexForms:function(){$("#indexHeader input").val("").prop("checked",!1),$("#newIndexType").val("Geo").prop("selected",!0),this.selectIndexType()},toggleNewIndexView:function(){var a=$(".index-button-bar2")[0];$("#indexEditView").is(":visible")?($("#indexEditView").hide(),$("#newIndexView").show(),$("#cancelIndex").detach().appendTo("#indexHeaderContent #modal-dialog .modal-footer"),$("#createIndex").detach().appendTo("#indexHeaderContent #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.InfoView=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,"Info"),this.renderInfoView()},breadcrumb:function(){$("#subNavigationBar .breadcrumb").html("Collection: "+this.collectionName)},renderInfoView:function(){if(this.model.get("locked"))return 0;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,null,null,null,null,null,"content")}}.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)}})}(),function(){"use strict";window.LoginView=Backbone.View.extend({el:"#content",el2:".header",el3:".footer",loggedIn:!1,loginCounter:0,events:{"keyPress #loginForm input":"keyPress","click #submitLogin":"validate","submit #dbForm":"goTo","click #logout":"logout","change #loginDatabase":"renderDBS"},template:templateEngine.createTemplate("loginView.ejs"),render:function(a){var b=this;$(this.el).html(this.template.render({})),$(this.el2).hide(),$(this.el3).hide();var c=function(a,c){var d;d=a?arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(a)+"/database","_system"):arangoHelper.databaseUrl("/_api/database/user"),frontendConfig.authenticationEnabled===!1&&($("#logout").hide(),$(".login-window #databases").css("height","90px")),$("#loginForm").hide(),$(".login-window #databases").show(),$.ajax(d).success(function(a){$("#loginDatabase").html(""),_.each(a.result,function(a,b){c?$("#loginDatabase").append(""):$("#loginDatabase").append("")}),b.renderDBS()}).error(function(){c?c():console.log("could not fetch user db data")})};if(frontendConfig.authenticationEnabled&&a!==!0){var d=arangoHelper.getCurrentJwtUsername();if(null!==d&&"undefined"!==d&&void 0!==d){var e=function(){b.collection.logout(),window.setTimeout(function(){$("#loginUsername").focus()},300)};c(arangoHelper.getCurrentJwtUsername(),e)}else window.setTimeout(function(){$("#loginUsername").focus()},300)}else c();return $(".bodyWrapper").show(),b.checkVersion(),this},checkVersion:function(){var a=this;window.setTimeout(function(){var b,c=document.getElementById("loginSVG"),d=c.contentDocument;void 0!==frontendConfig.isEnterprise?(b=frontendConfig.isEnterprise?d.getElementById("logo-enterprise"):d.getElementById("logo-community"),b.setAttribute("visibility","visible")):a.checkVersion()},150)},clear:function(){$("#loginForm input").removeClass("form-error"),$(".wrong-credentials").hide()},keyPress:function(a){a.ctrlKey&&13===a.keyCode?(a.preventDefault(),this.validate()):a.metaKey&&13===a.keyCode&&(a.preventDefault(),this.validate())},validate:function(a){a.preventDefault(),this.clear();var b=$("#loginUsername").val(),c=$("#loginPassword").val();b&&this.collection.login(b,c,this.loginCallback.bind(this,b,c))},loginCallback:function(a,b,c){var d=this;if(c){if(0===d.loginCounter)return d.loginCounter++,void d.collection.login(a,b,this.loginCallback.bind(this,a));d.loginCounter=0,$(".wrong-credentials").show(),$("#loginDatabase").html(""),$("#loginDatabase").append("")}else d.renderDBSelection(a)},renderDBSelection:function(a){var b=this,c=arangoHelper.databaseUrl("/_api/user/"+encodeURIComponent(a)+"/database","_system");frontendConfig.authenticationEnabled===!1&&(c=arangoHelper.databaseUrl("/_api/database/user")),$(".wrong-credentials").hide(),b.loggedIn=!0,$.ajax(c).success(function(a){_.each(a.result,function(b,c){"rw"!==b&&delete a.result[c]}),$("#loginForm").hide(),$(".login-window #databases").show(),$("#loginDatabase").html(""),_.each(a.result,function(a,b){$("#loginDatabase").append("")}),b.renderDBS()}).error(function(){$(".wrong-credentials").show()})},renderDBS:function(){if(0===$("#loginDatabase").children().length)$("#dbForm").remove(),$(".login-window #databases").prepend('
"),a.disabled||$(b.subEl+" .bottom").children().last().bind("click",function(c){$("#subNavigationBar .breadcrumb").html(""),b.activeSubMenu=a,b.renderSubView(a,c)})})}},renderSubView:function(a,b){window.App[a.route]&&(window.App[a.route].resetState&&window.App[a.route].resetState(),window.App[a.route]()),$(this.subEl+" .bottom").children().removeClass("active"),$(b.currentTarget).addClass("active")},switchTab:function(a){var b=$(a.currentTarget).children().first().attr("id");return"enterprise"===b?void window.open("https://www.arangodb.com/download-arangodb-enterprise/","_blank"):void(b&&this.selectMenuItem(b+"-menu"))},selectMenuItem:function(a,b){void 0===a&&(a=window.location.hash.split("/")[0],a=a.substr(1,a.length-1)),""===a?a=window.App.isCluster?"cluster":"dashboard":"cNodes"!==a&&"dNodes"!==a||(a="nodes");try{this.renderSubMenu(a.split("-")[0])}catch(c){this.renderSubMenu(a)}$(".navlist li").removeClass("active"),"string"==typeof a&&(b?$("."+this.subViewConfig[a]+"-menu").addClass("active"):a&&($("."+a).addClass("active"),$("."+a+"-menu").addClass("active"))),arangoHelper.hideArangoNotifications()},showSubDropdown:function(a){$(a.currentTarget).find(".subBarDropdown").toggle()},showDropdown:function(a){var b=a.target||a.srcElement,c=b.id;"links"===c||"link_dropdown"===c||"links"===a.currentTarget.id?$("#link_dropdown").fadeIn(1):"tools"===c||"tools_dropdown"===c||"tools"===a.currentTarget.id?$("#tools_dropdown").fadeIn(1):"dbselection"!==c&&"dbs_dropdown"!==c&&"dbselection"!==a.currentTarget.id||$("#dbs_dropdown").fadeIn(1)},hideDropdown:function(a){$("#link_dropdown").fadeOut(1),$("#tools_dropdown").fadeOut(1),$("#dbs_dropdown").fadeOut(1)}})}(),function(){"use strict";window.NodesView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("nodesView.ejs"),interval:1e4,knownServers:[],events:{"click #nodesContent .coords-nodes .pure-table-row":"navigateToNode","click #nodesContent .coords-nodes .pure-table-row .fa-trash-o":"deleteNode","click #addCoord":"addCoord","click #removeCoord":"removeCoord","click #addDBs":"addDBs","click #removeDBs":"removeDBs","click .abortClusterPlan":"abortClusterPlanModal","keyup #plannedCoords":"checkKey","keyup #plannedDBs":"checkKey"},checkKey:function(a){if(13===a.keyCode){var b=this,c=function(a){var c;if("plannedCoords"===a.target.id)try{c=JSON.parse($("#plannedCoords").val()),"number"==typeof c?(window.modalView.hide(),b.setCoordSize(c)):arangoHelper.arangoError("Error","Invalid value. Must be a number.")}catch(a){arangoHelper.arangoError("Error","Invalid value. Must be a number.")}else if("plannedDBs"===a.target.id)try{c=JSON.parse($("#plannedCoords").val()),"number"==typeof c?(window.modalView.hide(),b.setDBsSize(c)):arangoHelper.arangoError("Error","Invalid value. Must be a number.")}catch(a){arangoHelper.arangoError("Error","Invalid value. Must be a number.")}};this.changePlanModal(c.bind(null,a))}},changePlanModal:function(a,b){var c=[],d=[];d.push(window.modalView.createReadOnlyEntry("plan-confirm-button","Caution","You are changing the cluster plan. Continue?",void 0,void 0,!1,/[<>&'"]/)),c.push(window.modalView.createSuccessButton("Yes",a.bind(this,b))),window.modalView.show("modalTable.ejs","Modify Cluster Size",c,d)},initialize:function(){var a=this;clearInterval(this.intervalFunction),window.App.isCluster&&(this.updateServerTime(),this.intervalFunction=window.setInterval(function(){"#nodes"===window.location.hash&&a.render(!1)},this.interval))},deleteNode:function(a){if(!$(a.currentTarget).hasClass("noHover")){var b=this,c=$(a.currentTarget.parentNode.parentNode).attr("node").slice(0,-5);return window.confirm("Do you want to delete this node?")&&$.ajax({type:"POST",url:arangoHelper.databaseUrl("/_admin/cluster/removeServer"),contentType:"application/json",async:!0,data:JSON.stringify(c),success:function(a){b.render(!1)},error:function(){"#nodes"===window.location.hash&&arangoHelper.arangoError("Cluster","Could not fetch cluster information")}}),!1}},navigateToNode:function(a){if(!$(a.currentTarget).hasClass("noHover")){var b=$(a.currentTarget).attr("node").slice(0,-5);window.App.navigate("#node/"+encodeURIComponent(b),{trigger:!0})}},render:function(a){if("#nodes"===window.location.hash){var b=this;$("#content").is(":empty")&&arangoHelper.renderEmpty("Please wait. Requesting cluster information...","fa fa-spin fa-circle-o-notch"),a!==!1&&arangoHelper.buildNodesSubNav("Overview");var c=function(a){$.ajax({type:"GET",url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",success:function(c){"#nodes"===window.location.hash&&b.continueRender(a,c)}})};$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,async:!0,success:function(a){"#nodes"===window.location.hash&&c(a.Health)},error:function(){"#nodes"===window.location.hash&&arangoHelper.arangoError("Cluster","Could not fetch cluster information")}})}},continueRender:function(a,b){var c={},d={},e=!1;_.each(a,function(a,b){"Coordinator"===a.Role?c[b]=a:"DBServer"===a.Role&&(d[b]=a)}),null!==b.numberOfDBServers&&null!==b.numberOfCoordinators&&(e=!0);var f=function(a){this.$el.html(this.template.render({coords:c,dbs:d,scaling:e,scaleProperties:a,plannedDBs:b.numberOfDBServers,plannedCoords:b.numberOfCoordinators})),e||($(".title").css("position","relative"),$(".title").css("top","-4px"),$(".sectionHeader .information").css("margin-top","-3px"))}.bind(this);this.renderCounts(e,f)},updatePlanned:function(a){a.numberOfCoordinators&&($("#plannedCoords").val(a.numberOfCoordinators),this.renderCounts(!0)),a.numberOfDBServers&&($("#plannedDBs").val(a.numberOfDBServers),this.renderCounts(!0))},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.updatePlanned(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.updatePlanned(c)},error:function(){arangoHelper.arangoError("Scale","Could not set coordinator size.")}})},abortClusterPlanModal:function(){var a=[],b=[];b.push(window.modalView.createReadOnlyEntry("plan-abort-button","Caution","You are aborting the planned cluster plan. All pending servers are going to be removed. Continue?",void 0,void 0,!1,/[<>&'"]/)),a.push(window.modalView.createSuccessButton("Yes",this.abortClusterPlan.bind(this))),window.modalView.show("modalTable.ejs","Modify Cluster Size",a,b)},abortClusterPlan:function(){window.modalView.hide();try{var a=JSON.parse($("#infoCoords > .positive > span").text()),b=JSON.parse($("#infoDBs > .positive > span").text());this.setCoordSize(a),this.setDBsSize(b)}catch(c){console.log(c),arangoHelper.arangoError("Plan","Could not abort Cluster Plan")}},renderCounts:function(a,b){var c=this,d=function(b,c,d,e){var f=''+c+'';d&&a===!0&&(f=f+''+d+''),e&&(f=f+''+e+''),$(b).html(f),a||($(".title").css("position","relative"),$(".title").css("top","-4px"))},e=function(a){var e=0,f=0,g=0,h=0,i=0,j=0;_.each(a,function(a){"Coordinator"===a.Role?"GOOD"===a.Status?f++:e++:"DBServer"===a.Role&&("GOOD"===a.Status?h++:i++)}),$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/numberOfServers"),contentType:"application/json",processData:!1,success:function(a){g=Math.abs(f+e-a.numberOfCoordinators),j=Math.abs(h+i-a.numberOfDBServers),b?b({coordsPending:g,coordsOk:f,coordsErrors:e,dbsPending:j,dbsOk:h,dbsErrors:i}):(d("#infoDBs",h,j,i),d("#infoCoords",f,g,e)),c.isPlanFinished()||($(".scaleGroup").addClass("no-hover"),$("#plannedCoords").attr("disabled","disabled"),$("#plannedDBs").attr("disabled","disabled"))}})};$.ajax({type:"GET",cache:!1,url:arangoHelper.databaseUrl("/_admin/cluster/health"),contentType:"application/json",processData:!1,success:function(a){e(a.Health)}})},isPlanFinished:function(){var a;return a=!($("#infoDBs").find(".warning").length>0)&&!($("#infoCoords").find(".warning").length>0)},addCoord:function(){var a=function(){window.modalView.hide(),this.setCoordSize(this.readNumberFromID("#plannedCoords",!0))};this.isPlanFinished()?this.changePlanModal(a.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},removeCoord:function(){var a=function(){window.modalView.hide(),this.setCoordSize(this.readNumberFromID("#plannedCoords",!1,!0))};this.isPlanFinished()?this.changePlanModal(a.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},addDBs:function(){var a=function(){window.modalView.hide(),this.setDBsSize(this.readNumberFromID("#plannedDBs",!0))};this.isPlanFinished()?this.changePlanModal(a.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},removeDBs:function(){var a=function(){window.modalView.hide(),this.setDBsSize(this.readNumberFromID("#plannedDBs",!1,!0))};this.isPlanFinished()?this.changePlanModal(a.bind(this)):(arangoHelper.arangoNotification("Cluster Plan","Planned state not yet finished."),$(".noty_buttons .button-danger").remove())},readNumberFromID:function(a,b,c){var d=$(a).val(),e=!1;try{e=JSON.parse(d)}catch(f){}return b&&e++,c&&1!==e&&e--,e},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.NodeView=Backbone.View.extend({el:"#content",template:templateEngine.createTemplate("nodeView.ejs"),interval:5e3,dashboards:[],events:{},initialize:function(a){window.App.isCluster&&(this.coordinators=a.coordinators,this.dbServers=a.dbServers,this.coordname=a.coordname,this.updateServerTime())},breadcrumb:function(a){$("#subNavigationBar .breadcrumb").html("Node: "+a)},render:function(){this.$el.html(this.template.render({coords:[]}));var a=function(){this.continueRender(),this.breadcrumb(arangoHelper.getCoordinatorShortName(this.coordname)),$(window).trigger("resize")}.bind(this);this.initCoordDone||this.waitForCoordinators(),this.initDBDone?(this.coordname=window.location.hash.split("/")[1],this.coordinator=this.coordinators.findWhere({name:this.coordname}),a()):this.waitForDBServers(a)},continueRender:function(){var a=this;this.dashboards[this.coordinator.get("name")]=new window.DashboardView({dygraphConfig:window.dygraphConfig,database:window.App.arangoDatabase,serverToShow:{raw:this.coordinator.get("address"),isDBServer:!1,endpoint:this.coordinator.get("protocol")+"://"+this.coordinator.get("address"),target:this.coordinator.get("name")}}),this.dashboards[this.coordinator.get("name")].render(),window.setTimeout(function(){a.dashboards[a.coordinator.get("name")].resize()},500)},waitForCoordinators:function(a){var b=this;window.setTimeout(function(){0===b.coordinators.length?b.waitForCoordinators(a):(b.coordinator=b.coordinators.findWhere({name:b.coordname}),b.initCoordDone=!0,a&&a())},200)},waitForDBServers:function(a){var b=this;window.setTimeout(function(){0===b.dbServers[0].length?b.waitForDBServers(a):(b.initDBDone=!0,b.dbServer=b.dbServers[0],b.dbServer.each(function(a){"DBServer001"===a.get("name")&&(b.dbServer=a)}),a())},200)},updateServerTime:function(){this.serverTime=(new Date).getTime()}})}(),function(){"use strict";window.NotificationView=Backbone.View.extend({events:{"click .navlogo #stat_hd":"toggleNotification","click .notificationItem .fa":"removeNotification","click #removeAllNotifications":"removeAllNotifications"},initialize:function(){this.collection.bind("add",this.renderNotifications.bind(this)),this.collection.bind("remove",this.renderNotifications.bind(this)),this.collection.bind("reset",this.renderNotifications.bind(this)),window.setTimeout(function(){frontendConfig.authenticationEnabled===!1&&frontendConfig.isCluster===!1&&arangoHelper.showAuthDialog()===!0&&window.arangoHelper.arangoWarning("Warning","Authentication is disabled. Do not use this setup in production mode.")},2e3)},notificationItem:templateEngine.createTemplate("notificationItem.ejs"),el:"#notificationBar",template:templateEngine.createTemplate("notificationView.ejs"),toggleNotification:function(){var a=this.collection.length;0!==a&&$("#notification_menu").toggle()},removeAllNotifications:function(){$.noty.clearQueue(),$.noty.closeAll(),this.collection.reset(),$("#notification_menu").hide()},removeNotification:function(a){var b=a.target.id;this.collection.get(b).destroy()},renderNotifications:function(a,b,c){if(c&&c.add){var d,e=this.collection.at(this.collection.length-1),f=e.get("title"),g=5e3,h=["click"];if(e.get("content")&&(f=f+": "+e.get("content")),"error"===e.get("type")?(g=!1,h=["button"],d=[{addClass:"button-danger",text:"Close",onClick:function(a){a.close()}}]):"warning"===e.get("type")&&(g=15e3,d=[{addClass:"button-warning",text:"Close",onClick:function(a){a.close()}},{addClass:"button-danger",text:"Don't show again.",onClick:function(a){a.close(),window.arangoHelper.doNotShowAgain()}}]),$.noty.clearQueue(),$.noty.closeAll(),noty({theme:"relax",text:f,template:'