function Check_Version(){var n=-1,t,i;return navigator.appName=="Microsoft Internet Explorer"?(t=navigator.userAgent,i=new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})"),i.exec(t)!==null&&(n=parseFloat(RegExp.$1))):navigator.appName=="Netscape"&&(n=navigator.appVersion.indexOf("Trident")===-1?12:11),n}function FeedHeaderViewModel(){var n=this;n.selectedMode=ko.observable("Feed");n.priorMode=ko.observable("");n.showBack=ko.computed(function(){return n.selectedMode()=="Back"});n.itemSelected=function(){var n=portal.feed.headerVM.selectedMode();n!="Back"&&portal.feed.headerVM.priorMode(n);portal.feed.headerVM.selectedMode("Back")};n.back=function(){portal.feed.vm.selectedItem({});portal.feed.headerVM.selectedMode(portal.feed.headerVM.priorMode())};n.loadItems=function(){portal.feed.vm.selectedMode(n.selectedMode());n.selectedMode()=="Feed"?(portal.feed.vm.items.removeAll(),portal.ajax.prevAjaxParams=null,portal.feed.scrollAtEnd=!1,portal.feed.isScrolling=!1,portal.feed.vm.load()):n.loadArchived()};n.loadTeam=function(){portal.feed.vm.selectedMode(n.selectedMode());portal.ajax.prevAjaxParams=null;portal.feed.vm.loadTeam()};n.loadArchived=function(){portal.feed.vm.archivedItems.removeAll();portal.ajax.prevAjaxParams=null;portal.feed.vm.archivedLastUpdated((new Date).toLocaleTimeString());portal.feed.scrollAtEnd=!1;portal.feed.isScrolling=!1;portal.feed.vm.load()}}function FeedViewModel(){var n=this;n.archivedItems=ko.observableArray();n.teamItems=ko.observableArray();n.presence=ko.observable(!0);n.selectedMode=ko.observable("Feed");n.items=ko.observableArray();n.selectedItem=ko.observable({});n.selectedItemComments=ko.observableArray();n.quickReplies=ko.observableArray();n.quickAcks=ko.observableArray();n.isLoading=ko.observable(!1);n.archivedLastUpdated=ko.observable("");n.replyText=ko.observable("");n.ackText=ko.observable("");n.expiry=ko.observable("NotExpired");n.hasSelectedItem=ko.computed(function(){var t=n.selectedItem().FeedItemKey>0;return t&&portal.feed.headerVM.itemSelected(),t});n.recallVisibility=ko.computed(function(){var t=n.selectedItem();return portal.opts&&t.OriginUserUID!=portal.opts.uid?"hidden":t.ItemType=="Event"||t.ItemType=="Task"?"hidden":""});n.injectHotLinks=function(n){return n.ItemContentOriginal=n.ItemContent,n.ItemType=="Event"?n.ItemContent.replace(n.EventItemName,"<a href=\"javascript:void(0)\" onclick=\"$X('get/locator/history', { itemType: 'NonStaff', portalItemID: '"+n.EventItemID+"' })\">"+n.EventItemName+"<\/a>").replace(n.EventLocationName,"<a href=\"javascript:void(0)\" onclick=\"$X('get/locator/history', { itemType: 'Location', portalItemID: 'L:"+n.EventLocationUID+"' })\">"+n.EventLocationName+"<\/a>"):n.ItemType=="Task"?n.ItemContent.replace(n.TaskItemName,"<a href=\"javascript:void(0)\" onclick=\"$X('get/locator/history', { itemType: 'NonStaff', portalItemID: '"+n.TaskItemID+"' })\">"+n.TaskItemName+"<\/a>").replace(n.TaskLocationName,"<a href=\"javascript:void(0)\" onclick=\"$X('get/locator/history', { itemType: 'Location', portalItemID: 'L:"+n.TaskLocationUID+"' })\">"+n.TaskLocationName+"<\/a>").replace("CURRENTLOCATION",'<a href="javascript:void(0)" class="live-update" data-k="'+n.TaskItemID+"\" onclick=\"$X('get/locator/history', { itemType: 'Location', portalItemID: 'L:"+n.TaskCurrentLocationUID+"' })\">"+n.TaskCurrentLocationName+"<\/a>").replace("DUEDATECOLOR","#000000").replace("DUEDATE",n.DueDateDisplay):n.ItemContent};n.handleTask=function(n){n.ActionTitle=="Cancel Task"?portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/CancelTask/"+n.EntityKey+"/"+n.FeedItemKey+(n.TaskItemKey?"/"+n.TaskItemKey:""),null,function(){portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/reply/"+n.FeedItemKey,{ReplyText:"Task has been cancelled!"},null,{post:!0})},{post:!0}):n.ActionTitle=="Mark Complete"?portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/CompleteTask/"+n.EntityKey+(n.TaskItemKey?"/"+n.TaskItemKey:""),null,function(){portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/reply/"+n.FeedItemKey,{ReplyText:"Task has been completed!"},null,{post:!0})},{post:!0}):n.ActionTitle=="Claim"?portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/ClaimTask/"+n.EntityKey+(n.TaskItemKey?"/"+n.TaskItemKey:""),null,function(){portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/reply/"+n.FeedItemKey,{ReplyText:"Task has been claimed!"},null,{post:!0})},{post:!0}):alert("not implemented")};n.setSelectedItem=function(t,i){i&&i.target&&$(i.target).is("a")||(t.ItemType=="Task"&&i==undefined&&t.ActionTitle!="Reply"?n.handleTask(t):(n.selectedItemComments([]),n.selectedItem(t),colorizeItem(t),n.quickReplies([]),n.quickAcks([]),portal.feed.serverCall("/quick-responses/"+portal.site.SiteUID+"/"+t.ItemType+"/Reply",{},function(t){n.quickReplies(t)}),t.ItemType=="Event"&&portal.feed.serverCall("/quick-responses/"+portal.site.SiteUID+"/"+t.ItemType+"/Ack",{},function(t){n.quickAcks(t)}),portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/item/"+t.FeedItemKey,{},function(t){n.selectedItemComments(t.Comments)})))};n.sendReply=function(){var t=n.replyText();t!=""&&(n.replyText(""),portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/reply/"+n.selectedItem().FeedItemKey,{ReplyText:t},null,{post:!0}))};n.sendAck=function(){var t=n.ackText();t!=""&&(n.ackText(""),portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/acknowledge/"+n.selectedItem().FeedItemKey,{AckText:t},null,{post:!0}))};n.recallMessage=function(){$("#feedItemConfirmRecallModal").modal({show:!0}).off("hidden.bs.modal").on("hidden.bs.modal",function(){portal.chat.ui.confirmRecall&&portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/recall/"+n.selectedItem().FeedItemKey);portal.feed.headerVM.back()})};n.sendQuickReplyCommand=function(t){n.replyText(t.Title);n.sendReply()};n.sendQuickAckCommand=function(t){n.ackText(t.Title);n.sendAck()};n.initPageSize=function(){var n=portal.feed.scrollable,t;portal.feed.pageSize=20;n&&n.length>0&&(t=Math.round(n.height()/115)*2,t>20&&(portal.feed.pageSize=t))};n.load=function(t){n.selectedMode()=="Feed"?portal.feed.scrollAtEnd?t&&t():(n.isLoading(!0),portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/list/"+n.items().length+"/"+portal.feed.pageSize+"/false",{},function(i){n.items.pushAll(i);n.isLoading(!1);n.items().forEach(function(n){n.ItemType=="Task"&&colorizeItem(n)});i.length<portal.feed.pageSize&&(portal.feed.scrollAtEnd=!0);t&&t(i)})):portal.feed.scrollAtEnd?t&&t():(n.isLoading(!0),portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/list/"+n.archivedItems().length+"/"+portal.feed.pageSize+"/true",{},function(i){n.archivedItems.pushAll(i);n.isLoading(!1);i.length<portal.feed.pageSize&&(portal.feed.scrollAtEnd=!0);t&&t(i)}))};n.loadTeam=function(){n.isLoading(!0);n.teamItems.removeAll();portal.feed.serverCall("/team/"+portal.site.SiteUID,{},function(t){n.teamItems.pushAll(t);n.isLoading(!1)})};n.teamMemberSelected=function(n){portal.chat.ui.getComposeModal(n)};n.actionCommand=function(t){t.ItemType=="PrivateMessage"||t.ItemType=="GroupMessage"||t.ItemType=="BroadcastMessage"||t.ItemType=="Event"||t.ItemType=="Task"?n.setSelectedItem(t):alert("not implemented")};n.dismissCommand=function(n){portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/dismiss/"+n.FeedItemKey,{},function(){})};n.unarchiveCommand=function(t){portal.feed.serverCall("/feed/"+portal.site.SiteUID+"/unarchive/"+t.FeedItemKey,{},function(){n.archivedItems.remove(t)})}}var portal,$X,colorizeItem,colorizeInner;(function(n){var r=n.History,t=n.jQuery,i=n.document;if(!r.enabled)return!1;t(function(){var o=".canvas:last",u=t(o).filter(":first"),h=u.get(0),l=t("#menu,#nav,nav:first,.nav:first").filter(":first"),c=t(n),f=t(i.body),e=r.getRootUrl(),s;u.length===0&&(u=f);t.expr[":"].internal=function(n){var r=t(n),i=r.attr("href")||"";return i!="#"&&i!="javascript:void(0)"&&(i.substring(0,e.length)===e||i.indexOf(":")===-1)};s=function(n){var i=String(n).replace(/<\!DOCTYPE[^>]*>/i,"").replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2').replace(/<\/(html|head|body|title|meta|script)\>/gi,"<\/div>");return t.trim(i)};t.fn.ajaxify=function(){var n=t(this),i;if(!(t("#error404Container").length>0))return i=n.find("a:internal:not(.no-ajaxy)"),i.click(function(n){var i=t(this),u=i.attr("href"),f=i.attr("title")||null;return n.which==2||n.metaKey?!0:(r.pushState(null,f,u),n.preventDefault(),!1)}),n};f.ajaxify();c.bind("statechange",function(){var l=r.getState(),c=l.url,a=c.replace(e,"");t(".open").removeClass("open");t(".dropdown-menu:visible").addClass("hide");t(".hide-on-teardown").hide();t(".show-on-teardown").show();t(".tooltip").remove();portal.ajaxUnload();t.cookie("PortalDevice",portal.getDevice());t.ajax({type:n.postForm||"GET",data:n.postData||null,url:n.postUrl||c,cache:!1,headers:{"X-Alt-Referer":portal.referrer},success:function(data){var submitButton,response,scope,scripts;if(t(".remove-on-teardown").remove(),t(".tooltip").remove(),n.postForm=null,n.postData=null,n.postUrl=null,portal.referrer=n.location.href,data.length>5&&data.substring(1,7)=="script"){eval(t(data).text());return}if(data.length>50&&data.substring(0,50).indexOf('<div class="modal')>0){submitButton=t("form").find("button[type=submit]");submitButton.length>0&&submitButton.attr("data-beforetext")&&submitButton.html(submitButton.attr("data-beforetext")).prop("disabled",!1).removeClass("disabled");response=t(data);response.on("shown.bs.modal",function(){portal.load(response)});response.modal("show");return}t(".modal-static.fade.in").modal("hide");!(typeof angular=="undefined")&&t(".angular-app").length>0&&(scope=angular.element(t(".angular-app")).scope(),scope&&scope.$destroy());var $data=t(s(data)),$dataBody=$data.find(".document-body:first"),$dataContent=$dataBody.find(o).filter(":first"),$menuChildren,contentHtml,$scripts;if($scripts=$dataContent.find(".document-script"),$scripts.length&&$scripts.detach(),contentHtml=$dataContent.html()||$data.html(),!contentHtml)return i.location.href=c,!1;if(contentHtml.indexOf("Login<\/button>")>0){n.location.href=n.location.href;return}u.html(contentHtml).ajaxify();i.title=$data.find(".document-title:first").text();portal.chat.ui.originalTitle=i.title;try{i.getElementsByTagName("title")[0].innerHTML=i.title.replace("<","&lt;").replace(">","&gt;").replace(" & "," &amp; ")}catch(Exception){}t("#page-title-override").length>0?t("#page-title").html(t("#page-title-override").html()):t("#page-title").text(t.trim(i.title.split("|")[0]));scripts=[];$scripts.each(function(){t(this).attr("src")&&scripts.push(t(this).attr("src"))});$LAB.setOptions({AlwaysPreserveOrder:!0}).script(scripts).wait(function(){$scripts.each(function(){if(!t(this).attr("src")){var r=t(this),u=r.text(),n=i.createElement("script");n.appendChild(i.createTextNode(u));h.appendChild(n)}});portal.load(f);n.ga&&ga("send","pageview",n.location.pathname+n.location.search);setTimeout(function(){portal.reveal()},1e3)})},error:function(t,r,u){return n.postForm=null,n.postData=null,n.postUrl=null,console.log(u),i.location.href=c,!1}})})})})(window);ko.bindingHandlers.select2={after:["options","value"],init:function(n,t){$(n).select2(ko.unwrap(t()));ko.utils.domNodeDisposal.addDisposeCallback(n,function(){$(n).select2("destroy")})},update:function(n,t,i){var u=i(),f=$(n).data("select2"),r;"value"in u&&(r=""+ko.unwrap(u.value),(u.select2.multiple||n.multiple)&&r.constructor!==Array?f.val([r.split(",")]):f.val([r]))}};portal=portal||{};portal.logError=function(n,t){var r,i;n!=null&&(r=n.fileName!=null?n.fileName:document.location,t==null&&n.stack!=null&&(t=n.stack),i=n.message!=null?n.name+": "+n.message:n,i+=": at document path '"+r+"'.",t!=null&&(i+="\n  at "+t.join("\n  at ")),$.ajax({type:"POST",url:"/error/LogJavaScriptError",data:{message:i}}))};portal.logErrorRefresh=function(n,t){var r,i;n!=null&&(r=n.fileName!=null?n.fileName:document.location,t==null&&n.stack!=null&&(t=n.stack),i=n.message!=null?n.name+": "+n.message:n,i+=": at document path '"+r+"'.",i+="\n  at "+t,$.ajax({type:"POST",url:"/error/LogJavaScriptError",data:{message:i}}).done(function(){portal.goto("/error/js?exception="+escape(i))}))};Function.prototype.trace=function(){for(var t=[],n=this;n;)t.push(n.signature()),n=n.caller;return t};Function.prototype.signature=function(){var t={name:this.getName(),params:[],toString:function(){var n=this.params.length>0?"'"+this.params.join("', '")+"'":"";return this.name+"("+n+")"}},n;if(this.arguments)for(n=0;n<this.arguments.length;n++)t.params.push(this.arguments[n]);return t};Function.prototype.getName=function(){if(this.name)return this.name;var n=this.toString().split("\n")[0],t=/^function ([^\s(]+).+/;return t.test(n)?n.split("\n")[0].replace(t,"$1")||"anonymous":"anonymous"};window.onerror=function(n){arguments!=null&&arguments.callee!=null&&arguments.callee.trace&&portal.logError(n,arguments.callee.trace())};portal.events={};portal.events.disableEvent=function(n,t){$X("get/settings/DisableEvent",{eventDefId:n,confirmed:t},function(){t===!0&&($("div.disable-event-confirmation-modal").modal("hide"),$("#enable-event-"+n).addClass("fa-square-o").removeClass("fa-check-square"),$("#enable-event-"+n).show(),$("#disable-event-"+n).hide())})};portal.events.cancelEventDisable=function(n){$("#enable-event-"+n).hide();$("#disable-event-"+n).removeClass("fa-square-o").addClass("fa-check-square");$("#disable-event-"+n).show()};portal.events.search=function(n){$(".no-matching").remove();$("tbody.open-font .lh-check.portal-blue:not(.enabledisable)").click();$(".toggle-all.portal-blue")&&portal.toggleCheck($(".toggle-all"),!1);n=n.toLowerCase();var t=0;$.trim(n)==""?$("#events tbody tr").show():$("#events tbody tr").each(function(){var i=$(this),r="";$.map(i.find("td"),function(n){r+=$(n).text().toLowerCase()});r.toLowerCase().indexOf(n)>=0?(t++,i.show()):i.hide()});t==0&&n!=""&&$("#events tbody tr").length>0&&$("#events tbody").append('<tr class="no-matching"><td colspan="7">No events found matching "'+n+'".<\/td><\/tr>')};portal.events.enableEvent=function(n){$X("get/settings/EnableEvent",{eventDefId:n},function(){$("#enable-event-"+n).hide();$("#disable-event-"+n).removeClass("fa-square-o").addClass("fa-check-square portal-blue");$("#disable-event-"+n).show()})};portal.events.alertGroupPopup=function(n){$X("get/settings/AlertGroupPopup",{id:n})};portal.events.openQAEditor=function(n,t){$X("get/settings/EditQuickAlerts",{id:n,portalItemIds:t.ItemList},function(){$("#msltLocations").select2({width:"100%"}).on("select2:selecting",function(n){n.params.args.data&&$("#LocationsError").addClass("hidden")});$("#msltItems").select2({allowClear:!0,width:"100%"});n==0&&t.Items==null&&$("#msltItems").val(null).trigger("change.select2");setTimeout(function(){portal.loadTooltips($(this));setTimeout(function(){portal.events.subscribersHelper(t,!1)},0)},0)})};portal.events.subscribersHelper=function(n,t){if(n.AlertSubscribers!=null){n.AlertSubscribers.length==0&&t?$("#alertSubscriberError").removeClass("hidden"):$("#alertSubscriberError").addClass("hidden");$("#InApp").empty();$("#Email").empty();$("#SMS").empty();var i="",r="",u="";n.AlertSubscribers.forEach(function(n){if($.trim(n.FullName)!=""){var t="";t=n.IsAlertGroup?'<a href="javascript:void(0)" onclick="portal.events.alertGroupPopup('+n.AlertGroupKey+')">'+n.FullName+"<\/a>":n.FullName;n.NotifyInApp&&(i=i+t+", ");n.NotifyEmail&&(r=r+t+", ");n.NotifySMS&&(u=u+t+", ")}});var i=i.substring(0,i.length-2),r=r.substring(0,r.length-2),u=u.substring(0,u.length-2);return $("#InApp").append(i),$("#Email").append(r),$("#SMS").append(u),setTimeout(function(){portal.loadTooltips($(".modal"))},0),n}};portal.events.alertSubscribers={$editModal:null,editSubscribersViewModel:null,onEditSubscribersModalAcceptChanges:null,openEditSubscribersModal:function(n,t){var i=this;this.onEditSubscribersModalAcceptChanges=t;this.editSubscribersViewModel.reset();n.forEach(function(n){var t=new portal.events.alertSubscribers.SubscriberViewModel(n);i.editSubscribersViewModel.addSubscriber(t)});this.$editModal.modal("show")}};portal.events.alertSubscribers.SubscriberViewModel=function(n){var i=this,t;this.__objType="portal.events.alertSubscribers.SubscriberViewModel";t={Id:0,AlertGroupKey:null,UserId:null,FullName:null,NotifyInApp:!0,NotifyEmail:!1,NotifySMS:!1,OnlyAvailable:!1};n&&(n.__objType&&n.__objType===this.__objType?(t.Id=n.id(),t.AlertGroupKey=n.alertGroupKey(),t.UserId=n.userId(),t.FullName=n.name(),t.NotifyInApp=n.notifyInApp(),t.NotifyEmail=n.notifyEmail(),t.NotifySMS=n.notifySms(),t.OnlyAvailable=n.onlyAvailable()):$.extend(t,n));this.id=ko.observable(t.Id);this.alertGroupKey=ko.observable(t.AlertGroupKey);this.userId=ko.observable(t.UserId);this.name=ko.observable(t.FullName);this.notifyInApp=ko.observable(t.NotifyInApp);this.notifyEmail=ko.observable(t.NotifyEmail);this.notifySms=ko.observable(t.NotifySMS);this.onlyAvailable=ko.observable(t.OnlyAvailable);this.isAlertGroup=ko.pureComputed(function(){return i.alertGroupKey()!=null});this.isUser=ko.pureComputed(function(){return i.userId!=null})};portal.events.alertSubscribers.EditSubscribersViewModel=function(){var n=this;this.selectedSubscribers=ko.observableArray();this.clearSelectedSubscribers=function(){n.selectedSubscribers.removeAll()};this.removeSubscriber=function(t){n.selectedSubscribers.remove(t)};this.onInAppClicked=function(n,t){var i=$(t.target);i.prop("checked",!0);portal.alert("Required","In-App is the default messaging method and cannot be changed")};this.reset=function(){n.clearSelectedSubscribers()};this.addSubscriber=function(t){var i=t.isUser(),r=t.userId(),u=t.alertGroupKey();_.find(n.selectedSubscribers(),function(n){return i&&n.userId()==r||!i&&n.alertGroupKey()==u})||n.selectedSubscribers.push(t)}};portal.events.location={$editModal:null,modelToSubmit:null,showEditEventModal:function(n){this.modelToSubmit=n;var t=n,i=portal.events.location.$editModal;portal.events.subscribersHelper(t);t.SelectedLocations="";t.SelectedItems="";$("#btnSubscribers").off("click").on("click",function(){portal.events.alertSubscribers.openEditSubscribersModal(t.AlertSubscribers,function(n){t.AlertSubscribers=[];n.selectedSubscribers().forEach(function(n){t.AlertSubscribers.push({EventDefinitionFK:t.Id,IsAlertGroup:n.isAlertGroup(),IsUser:n.isUser(),AlertGroupKey:n.alertGroupKey(),UserId:n.userId(),FullName:n.name(),NotifyInApp:n.notifyInApp(),NotifyEmail:n.notifyEmail(),NotifySMS:n.notifySms(),OnlyAvailable:n.onlyAvailable(),CurrentFlag:!0})});portal.events.subscribersHelper(t)})});i.modal({show:!0}).off("shown").on("shown.bs.modal",function(){var n,r,u;portal.loadTooltips($(this));$("#msltLocations").css({border:"#aaa solid 1px"});$("#textEventName").css({border:"#aaa solid 1px"});$("#msltItems").css({border:"#aaa solid 1px"});$("#EventNameError").addClass("hidden");$("#ItemsError").addClass("hidden");$("#LocationPathError").addClass("hidden");$("#msltItems").select2({width:"100%"});$("#msltItems").off("select2:selecting").on("select2:selecting",function(n){n.params.args.data&&($("#ItemsError").addClass("hidden"),$("#msltItems").css({border:"#aaa solid 1px"}))});$("#textEventName").off("keyup").on("keyup",function(){$("#EventNameError").addClass("hidden");$("#textEventName").css({border:"#aaa solid 1px"})});$("#msltItems option").each(function(n,i){t.Items.forEach(function(n){(n.ItemID==i.value||n.ItemCategoryID==i.value)&&n.IsVisible&&(i.selected=!0,t.SelectedItems=i.value+","+t.SelectedItems,t.SelectedItemsDescription=i.text+"|"+t.SelectedItemsDescription)})});$(".event-modal-location-count-value",i).text("0");n=$(".event-modal-location-picker .location-picker",i).attr("data-lp-id");r=$(".event-modal-location-path-picker .location-path-picker",i).attr("data-lp-id");portal.locationPicker.clear(n);portal.locationPicker.onSelectLocation(n,function(){var t=portal.locationPicker.getLocationCount(n)+portal.locationPathPicker.getSelectedPathCount(r);$(".event-modal-location-count-value",i).text(t);$("#LocationPathError").addClass("hidden")});portal.locationPicker.onRemoveLocation(n,function(){var t=portal.locationPicker.getLocationCount(n)+portal.locationPathPicker.getSelectedPathCount(r);$(".event-modal-location-count-value",i).text(t)});t.Locations.forEach(function(t){portal.locationPicker.selectLocation(t.LocationID,n,!1)});u=portal.locationPathPicker.load(r);portal.locationPathPicker.onAddPath(r,function(){var t=portal.locationPicker.getLocationCount(n)+portal.locationPathPicker.getSelectedPathCount(r);$(".event-modal-location-count-value",i).text(t);$("#LocationPathError").addClass("hidden")});portal.locationPathPicker.onRemovePath(r,function(){var t=portal.locationPicker.getLocationCount(n)+portal.locationPathPicker.getSelectedPathCount(r);$(".event-modal-location-count-value",i).text(t)});t.Paths&&t.Paths.forEach(function(n){var t={steps:[]};n.Locations.forEach(function(n){var i={locId:n.LocationUID,name:n.LocationName};t.steps.push(i)});portal.locationPathPicker.addUpdatePath(u,t,null)});$("#textSendAlert").off("change").on("change",function(){$("#textSendAlert").val()=="true"?($("#btnSubscribers").removeClass("disabled"),t.Validate=!0):($("#btnSubscribers").addClass("disabled"),t.Validate=!1);portal.events.subscribersHelper(t)});$("[id=dropDownAction]",i).val(t.Action).trigger("change");$("#textDuration").val(t.Duration);$("#textPriority").val(t.Priority);$("#textEventName").val(t.Name);$("#textPriority").trigger("change");$("#textSendAlert").val(t.SendAlert?"true":"false");$("#textSendAlert").trigger("change");$("#textRequiresAcknoledgment").val(t.RequiresAcknowledgement==null?2:t.RequiresAcknowledgement?1:0);$("#textRequiresAcknoledgment").trigger("change");$("#textReevaluationMinutes").val(t.ReevaluationMinutes);$("#textLimitOccurrences").val(t.LimitOccurrences?1:0);$("#textLimitOccurPeriodUnit").val(t.LimitOccurPeriodUnit);$("#textLimitOccurPeriodLength").val(t.LimitOccurPeriodLength);$("#textLimitOccurMaxOccurrences").val(t.LimitOccurMaxOccurrences);$("#msltItems").trigger("change");$("#msltLocations").trigger("change")}).on("hidden",function(n){n.preventDefault();t.SelectedLocations="";t.SelectedItems="";t.SelectedItemsDescription="";t.SelectedLocationsDescription="";$("#msltItems").val("").trigger("change");$("#msltLocations").val("").trigger("change")})}};portal.events.system={actions:[],filters:[],items:[],vehicleTypes:[],homeLocations:[],priorities:[{id:0,name:"Critical"},{id:1,name:"High"},{id:2,name:"Medium"},{id:3,name:"Low"}],$editModal:null,editSystemEventKvm:null,onEditSystemEventModalAcceptChanges:null,openEditEventModal:function(n,t){var i=this;this.onEditSystemEventModalAcceptChanges=t;this.editSystemEventKvm.loadEvent(n);this.$editModal.modal("show");portal.loadTooltips();$("select",this.$editModal).trigger("change")},getFilterAvailableValues:function(n){var t=[];switch(n.Id){case 1:t=this.items.map(function(t){return{Id:0,EventDefinitionFilterId:n.Id,ValueId:null,ValueUid:t.ItemID,ValueCode:null,ValueName:t.ItemName}});break;case 2:t=this.vehicleTypes.map(function(t){return{Id:0,EventDefinitionFilterId:n.Id,ValueId:null,ValueUid:null,ValueCode:t,ValueName:t}});break;case 3:t=this.homeLocations.map(function(t){return{Id:0,EventDefinitionFilterId:n.Id,ValueId:t.HomeLocationKey,ValueUid:null,ValueCode:null,ValueName:t.HomeLocationText}})}return t},enableEvent:function(n){$X("get/settings/EnableSystemEvent",{eventDefId:n},function(){$("#enable-system-event-"+n).hide();$("#disable-system-event-"+n).removeClass("fa-square-o").addClass("fa-check-square portal-blue");$("#disable-system-event-"+n).show()})},disableEvent:function(n,t){$X("get/settings/DisableSystemEvent",{eventDefId:n,confirmed:t},function(){t===!0&&($("div.disable-system-event-confirmation-modal").modal("hide"),$("#enable-system-event-"+n).addClass("fa-square-o").removeClass("fa-check-square"),$("#enable-system-event-"+n).show(),$("#disable-system-event-"+n).hide())})},cancelEventDisable:function(n){$("#enable-system-event-"+n).hide();$("#disable-system-event-"+n).removeClass("fa-square-o").addClass("fa-check-square");$("#disable-system-event-"+n).show()}};portal.events.system.EditSystemEventViewModel=function(){var n=this;this.availableActions=portal.events.system.actions;this.availableFilters=portal.events.system.filters;this.availablePriorities=portal.events.system.priorities;this.availableSendAlertOptions=[{id:!1,name:"No"},{id:!0,name:"Yes"}];this.eventName=ko.observable("");this.action=ko.observable();this.actionFilters=ko.observableArray();this.filters=ko.observableArray();this.priority=ko.observable();this.sendAlert=ko.observable();this.subscribers=ko.observableArray();this.isChooseSubscribersEnabled=ko.pureComputed(function(){return n.sendAlert().id==!0});this.inAppSubscribers=ko.pureComputed(function(){var t="",i=_.filter(n.subscribers(),function(n){return n.notifyInApp()});return _.sortBy(i,function(n){return n.name()}).forEach(function(n){t+=n.name()+", "}),t.endsWith(", ")&&(t=t.substr(0,t.length-2)),t});this.emailSubscribers=ko.pureComputed(function(){var t="",i=_.filter(n.subscribers(),function(n){return n.notifyEmail()});return _.sortBy(i,function(n){return n.name()}).forEach(function(n){t+=n.name()+", "}),t.endsWith(", ")&&(t=t.substr(0,t.length-2)),t});this.smsSubscribers=ko.pureComputed(function(){var t="",i=_.filter(n.subscribers(),function(n){return n.notifySms()});return _.sortBy(i,function(n){return n.name()}).forEach(function(n){t+=n.name()+", "}),t.endsWith(", ")&&(t=t.substr(0,t.length-2)),t});this.action.subscribe(function(t){n.actionFilters.removeAll();t.Filters.forEach(function(t){n.actionFilters.push(t)})});this.reset=function(){n.eventName("");n.action(n.availableActions[0]);n.filters.removeAll();n.priority(n.availablePriorities[0]);n.sendAlert(n.availableSendAlertOptions[0]);n.subscribers.removeAll()};this.loadEvent=function(t){n.reset();console.log(t);var i=_.find(n.availableActions,function(n){return n.Id==t.ActionId})||n.availableActions[0],r=_.find(n.availablePriorities,function(n){return n.id==t.Priority})||n.availablePriorities[0],u=_.find(n.availableSendAlertOptions,function(n){return n.id==t.SendAlert})||n.availableSendAlertOptions[0];n.eventName(t.Name);n.action(i);n.priority(r);n.sendAlert(u);t.Filters.forEach(function(t){var r=_.find(n.availableFilters,function(n){return n.Id==t.EventFilterId}),i=n.addFilter(r);i.id(t.Id);t.Values.forEach(function(n){i.addValue(n)})});t.AlertSubscribers.forEach(function(t){var i=new portal.events.alertSubscribers.SubscriberViewModel(t);n.subscribers.push(i)})};this.addFilter=function(t){var i=_.find(n.filters(),function(n){return n.filter.Id==t.Id});return i||(i=new portal.events.system.FilterViewModel(t),n.filters.push(i)),i};this.removeFilter=function(t){n.filters.remove(t)};this.addSubscriber=function(t){var i=t.isUser(),r=t.userId(),u=t.alertGroupKey();_.find(n.subscribers(),function(n){return i&&n.userId()==r||!i&&n.alertGroupKey()==u})||n.subscribers.push(t)};this.clearSubscribers=function(){n.subscribers.removeAll()}};portal.events.system.FilterViewModel=function(n){var t=this;this.filter=n;this.availableValues=portal.events.system.getFilterAvailableValues(this.filter);this.$select=null;this.id=ko.observable(0);this.name=ko.observable("");this.type=ko.observable("");this.values=ko.observableArray();this.templateName=ko.pureComputed(function(){return"system-event-"+t.filter.Type+"-filter-template"});this.onAfterRender=function(n){t.$select=$(n).find("select").first()};this.addValue=function(n){_.find(t.values(),function(t){return t.ValueId==n.ValueId&&t.ValueUid==n.ValueUid&&t.ValueCode==n.ValueCode})||t.values.push(_.find(t.availableValues,function(t){return t.ValueId==n.ValueId&&t.ValueUid==n.ValueUid&&t.ValueCode==n.ValueCode}))};this.id(0);this.name(this.filter.Name);this.type(this.filter.Type)};portal=portal||{};portal.pageInit=function(){portal.isInternalPage()&&portal.showProgress("progressInit","One Moment","Initializing...");$("html").removeClass("show-bg")};portal.isInitializing=!0;portal.ajaxLoader={requests:[],init:function(){var n=this;$(document).off("ajaxSend").off("ajaxComplete");$(document).on("ajaxSend",function(t,i,r){(portal.inactivityChecker(),r.url.indexOf("nowait=true")>=0||r.data!=null&&(r.data.nowait!=null||r.data.indexOf!=null&&r.data.indexOf("nowait=true&")>=0))||n.isRequestPending(i)||(n.addRequest(i),portal.toggleLoading(!0))}).on("ajaxComplete",function(t,i){n.isRequestPending(i)&&(n.removeRequest(i),portal.ajaxTimeout=window.setTimeout(function(){portal.toggleLoading(!1)},1e3))})},isRequestPending:function(n){for(var i=!1,t=0;t<this.requests.length;++t)if(this.requests[t]==n){i=!0;break}return i},addRequest:function(n){this.requests.push(n)},removeRequest:function(n){for(var i=-1,t=0;t<this.requests.length;++t)if(this.requests[t]==n){i=t;break}i>-1&&this.requests.splice(i,1)}};portal.pageLoad=function(){$.cookie("PortalDevice",portal.getDevice());portal.isInternalPage()&&(portal.inactivityChecker(),portal.initHubs(),portal.chat.ui.init(),portal.feed.init(),portal.width=$(window).width(),$(window).resize($.debounce(200,!0,function(){var n=$(window).width();portal.width!=n&&(portal.width=n,portal.gridster!=null&&(portal.conceal(),portal.gridster.destroy(),portal.refresh()));portal.ajaxAwareResize()})));portal.ajaxLoader.init();portal.load($(document));portal.isInitializing=!1};portal.windowLoad=function(){portal.isInternalPage()&&setTimeout(function(){portal.reveal()},600)};portal.isConnectedToServer=function(){return portal.hasRetrievedLocations&&portal.hasRetrievedThingLocations};portal.updateUnknownLocations=function(){portal.isConnectedToServer()&&ko.utils.arrayFirst(portal.vm.searchResults(),function(n){ko.utils.arrayFirst(n.Children(),function(n){n.LastKnownLocationName().charAt("0")=="<"&&n.ReloadLastKnownLocationName.notifySubscribers()})})};portal.updateTasksCurrentLocations=function(n){var t=$(".live-update").filter(function(){return $(this).attr("data-k").toLowerCase().indexOf(n.toLowerCase())>-1});t.each(function(n,t){var i=$(t);$X("post/locator/getCurrentLocation",{thingUid:i.attr("data-k"),json:!0},function(n){if(n&&n.locationName){var t=$(".live-update").filter(function(){return $(this).attr("data-k").toLowerCase().indexOf(i.attr("data-k").toLowerCase())>-1});t.attr("onclick","$X('get/locator/history', { itemType: 'Location', portalItemID: 'L:"+n.locationUid+"' })");t.text(n.locationName)}})})};portal.logout=function(n){portal.isInitializing=!0;portal.showProgress("logoutInit","One Moment","Logging out...",{bgColor:"#606a73"});n||portal.feed.setUserStatus("Unavailable",!0);setTimeout(function(){window.location.href="/logout?m=1"},2e3)};portal.initHubs=function(){if(portal.portalHub=$.connection.portalHub,portal.portalHub==null||portal.portalHub.client==null){alert("Socket connection with the server has been lost.  Certain features may be limited.  Please refresh your page at your earliest convenience.");return}portal.portalHub.client.afterDemoReset=function(){window.location.href="/home/expire"};portal.portalHub.client.renderThingLocations=function(n){_.forEach(n,function(n){var t=portal.vm.util.isLocationOffProperty(n.LocationUID);(!t||portal.security.isOffPropertyGpsAccessible)&&(t||portal.security.isOnPropertyGpsAccessible)||(n.LastSeenPointLatitude=null,n.LastSeenPointLongitude=null)});portal.hasRetrievedThingLocations=!0;console.log("Loaded "+n.length+" ThingLocations...");portal.vm.thingLocations(n);portal.updateUnknownLocations()};portal.portalHub.client.renderLocations=function(n){portal.hasRetrievedLocations=!0;console.log("Loaded "+n.length+" Locations...");portal.vm.locations(n);portal.updateUnknownLocations()};portal.portalHub.client.renderThingLocation=function(n,t){var i,r;console.log((new Date).getTime()+" - "+n.ThingUID+" - "+n.LocationUID);i=portal.vm.util.getThingLocation(n.ThingUID);i!=null?portal.vm.thingLocations.replace(i,n):portal.vm.thingLocations.push(n);t&&(r=$('.search-group-item[data-itemid="'+t.PortalItemID+'"][data-selected="true"]'),r.length>0&&(portal.noMapCenter=!0,r.trigger("click",{fromSignalR:!0}).trigger("click",{fromSignalR:!0})),$("#InventoryPod").length>0&&$X("get/home/WidgetQuickLinks",{},function(n){$("#InventoryPod").replaceWith(n);portal.load($("#InventoryPod"),{fromSignalR:!0})}),portal.updateTasksCurrentLocations(t.PortalItemID))};portal.portalHub.client.feedItemInsert=function(n){portal.feed.feedItemInsertImpl(n)};portal.portalHub.client.feedItemDelete=function(n){portal.feed.feedItemDeleteImpl(n)};portal.portalHub.client.feedItemUpdate=function(n){portal.feed.feedItemUpdateImpl(n)};portal.portalHub.client.userStatusChange=function(n){portal.feed.userStatusChangeImpl(n)};portal.portalHub.client.siteChangeLogout=function(n){portal.feed.siteChangeLogoutImpl(n)};portal.portalHub.client.renderUsers=function(n){console.log("Loaded "+n.length+" Users...");portal.vm.users(n)};portal.portalHub.client.pushToLiveView=function(){};$.connection.hub.qs={bearer_token:$.cookie("PortalToken")};$.connection.hub.error(function(n){console.log("SignalR error: "+n)});$.connection.hub.start().done(function(){console.log("Connected to server...");portal.hubInitialized=!0})};portal.whenHubReady=function(n){portal.hubInitialized?n(portal.portalHub):setTimeout(function(){portal.whenHubReady(n)},500)};portal.isInternalPage=function(){return $(".login").length==0&&!__isExternalPage};portal.inactivityChecker=function(){window.clearTimeout(window.inactivityInterval);window.clearTimeout(window.inactivityCountdown);window.inactivityInterval=window.setTimeout(function(){portal.popup("Inactivity",'You will be logged out in <span id="LogoutSeconds" style="font-weight: bold">30<\/span> seconds.  Would you like to stay logged in?','<a href="javascript:void(0)" onclick="portal.logout()" class="no-ajaxy btn btn-default pull-left">Logout Now<\/a><button type="button" class="btn btn-primary pull-right" onclick="$(\'#ModalInactivity\').modal(\'hide\'); portal.inactivityChecker()">Stay Logged In<\/button>',{id:"ModalInactivity",static:!0});window.inactivityCountdown=window.setInterval(function(){var n=parseInt($("#LogoutSeconds").text())-1;n<0&&(n=0);$("#LogoutSeconds").text(n);n==0&&portal.logout()},1e3);window.clearTimeout(window.inactivityInterval)},36e5)};portal.toggleCount=0;portal.toggleLoading=function(n){n?portal.toggleCount++:portal.toggleCount--;portal.toggleCount===1?($("#loading1").show().find("i").addClass("fa-spin"),$("#loading1").animateWithCss({opacity:1},1e3,"cubic-bezier")):portal.toggleCount===0&&$("#loading1").animateWithCss({opacity:0},1e3,"cubic-bezier",function(){$("#loading1").hide().find(".fa-spin").removeClass("fa-spin")})};portal.reveal=function(){$("#progressInit").hide();$(".page-wrap").css("visibility","visible")};portal.conceal=function(){portal.showProgress("progressInit","Initializing","One Moment");$(".page-wrap").css("visibility","hidden")};portal.loadTooltips=function(n){$(".tip",n).tooltip({html:!0,delay:{show:100},container:"body"})};portal.load=function(n,t){(t=t||{},$("html").css("overflow-y",$("#page-noscroll").length>0?"hidden":"scroll"),$("#lnav-menu .selected").removeClass("selected"),portal.opts!=null&&portal.opts.topSik&&$("#lnav-menu li[data-sik="+portal.opts.topSik+"]").addClass("selected"),portal.loadTooltips(n),portal.isInternalPage()&&portal.initGridster(),t.fromModal)||(portal.ajaxLoad(),portal.resize(),portal.ajaxAwareResize(),$.cookie("st")?(portal.scrollTo($.cookie("st")),$.removeCookie("st")):t.fromSignalR||portal.scrollTo(0))};portal.initGridster=function(){var i=$(".gridster").parent().width(),n=portal.getDevice(),t=n=="lg"?3:n=="md"?2:1,r=(i-20)/t-20;portal.gridster=$(".gridster > ul").gridster({widget_margins:[10,10],widget_base_dimensions:[r,50],min_cols:1,max_cols:t,autogrow_cols:!0,avoid_overlapped_widgets:!0,draggable:{handle:".gs-move-handle-both, .gs-move-handle-both i"},resize:{enabled:!0,stop:function(){portal.resize();portal.ajaxAwareResize()}}}).data("gridster")};portal.persistScroll=function(n){n?$.cookie("st",null):$.cookie("st",$(window).scrollTop())};portal.ajaxLoad=function(n,t){var i=t||$(".page").attr("id");if(n)$(window).off("lxaload."+i).on("lxaload."+i,function(){if($("#"+i).length==0){$(window).off("lxaload."+i);return}n()});else $(window).trigger("lxaload")};portal.detachAjaxLoad=function(n){var t=n||$(".page").attr("id");$(window).off("lxaload."+t)};portal.ajaxUnload=function(n,t){var i=t||$(".page").attr("id");if(n)$(window).off("lxaunload."+i).on("lxaunload."+i,function(){if($("#"+i).length==0){$(window).off("lxaunload."+i);return}n()});else $(window).trigger("lxaunload")};portal.ajaxAwareResize=function(n,t){var i=t||$(".page").attr("id");if(n)$(window).off("resizex."+i).on("resizex."+i,function(){if($("#"+i).length==0){$(window).off("resizex."+i);return}n()});else $(window).trigger("resizex")};portal.JSON2CSV=function(n,t){var r=typeof n!="object"?JSON.parse(n):n,o="",i="",s=r[0],f,e,u;if($("#quote").is(":checked"))for(u in r[0])e=u+"",i+='"'+e.replace(/"/g,'""')+'",';else for(u in r[0])i+=u+",";for(i=i.slice(0,-1),o+=i+"\r\n",f=0;f<r.length;f++){if(i="",t==!0)for(u in r[f])e=r[f][u]+"",i+='"'+e.replace(/"/g,'""')+'",';else for(u in r[f])i+=r[f][u]+",";i=i.slice(0,-1);o+=i+"\r\n"}return o};portal.ExportToCsv=function(n,t){if(navigator.msSaveBlob)return navigator.msSaveBlob(new Blob(["﻿",t],{type:"text/csv"}),n+".csv");if(navigator.userAgent.search("Trident")>=0)window.CsvExpFrame.document.open("text/csv","replace"),window.CsvExpFrame.document.write(t),window.CsvExpFrame.document.close(),window.CsvExpFrame.focus(),window.CsvExpFrame.document.execCommand("SaveAs",!0,n+".csv");else{var r="data:text/csv;charset=utf-8,"+escape(t),i=document.createElement("a");i.href=r;i.download=n+".csv";document.body.appendChild(i);i.click();document.body.removeChild(i)}};portal.ajax={XHR:null,short:function(n,t,i,r){if(n){var u=n.split("/"),f=u[0],e=u[1].replace("-","/"),o=u[2];portal.ajax.go(f,e,o,t||{},i,r)}},go:function(n,t,i,r,u,f){f||(f={doNotThrottle:!1});var o=function(n){f.addBearerToken&&n.setRequestHeader("Authorization","Bearer "+$.cookie("PortalToken"))},e={type:n,url:f.url?f.url:"/"+t.replace("-","/").replace("|","-")+"/"+i,data:r,cache:!1,dataType:portal.isJSON(r)?"json":r.json?"json":f.dataType?f.dataType:"html",beforeSend:o};!f.doNotThrottle&&portal.ajax.prevAjaxParams&&portal.ajax.prevAjaxTime>(new Date).getTime()-3e3&&JSON.stringify(e)==JSON.stringify(portal.ajax.prevAjaxParams)||(portal.ajax.prevAjaxParams=e,portal.ajax.prevAjaxTime=(new Date).getTime(),typeof f.contentType!="undefined"&&(e.contentType=f.contentType),typeof f.processData!="undefined"&&(e.processData=f.processData),portal.ajax.XHR=$.ajax(e).complete(function(n){var i,s,t;if(n.responseText.indexOf("Server Error")>0&&(i=window.open("","ErrorWindow","width=1100,height=800"),i.document.open(),i.document.write(n.responseText),i.document.close()),portal.ajax.buffer=null,n.responseText.indexOf('class="modal')>0){var t=$(n.responseText),h=t.attr("id"),o=$("#"+h);if(o.length>0)o.find(".modal-body").html(t.find(".modal-body").html()),o.find(".modal-footer").html(t.find(".modal-footer").html());else{t.on("shown.bs.modal",function(){portal.load(t,{fromModal:!0});$(window).trigger("resize."+t.first().attr("id"))});t.first().modal("show");u&&u!=null&&u(n.responseText)}}else if(u&&u!=null)if(f.delayScript)u(n.responseText);else if(r.json||f.dataType=="json")if(n.responseText=="")console.log("Empty content response from "+e.url);else try{s=$.parseJSON(n.responseText);u(s)}catch(c){console.log(e.url);console.log(c.stack);u(null)}else t=$("<div>"+(n&&n.responseText?n.responseText:"")+"<\/div>"),t.find("script[type*=javascript]").each(function(){eval($(this).text())}),u($.parseHTML(n.responseText,document,!1));else portal.ajax.buffer=n.responseText}))}};$X=portal.ajax.short;portal.scrollTo=function(n,t){$("html, body").animate({scrollTop:n-(t||0)},"fast")};portal.scrollToElement=function(n,t){portal.scrollTo(n.offset().top-n.outerHeight(),t)};portal.decodeHtmlTags=function(n){return n.replace(/\{/gi,"<").replace(/\}/gi,">")};portal.toggleCheck=function(n,t){t?(n.removeClass("fa-square-o portal-blue"),n.addClass("fa-check-square portal-blue")):(n.removeClass("fa-check-square portal-blue"),n.addClass("fa-square-o"))};portal.debounce=function(n,t,i){var r=n+"Timeout";window.clearTimeout(window[r]);window[r]=window.setTimeout(function(){i();window.clearTimeout(window[r])},t)};portal.isJSON=function(n){try{return JSON.parse(n),!0}catch(t){return!1}};portal.parseJson=function(n){try{return JSON.parse(portal.decodeHtml(n))}catch(t){return{}}};portal.resize=function(){$(".pod",".gridster").each(function(){var n=$(this),t=n.height()-n.find(".pod-title").height()-9;$(".pod-body",n).css("min-height",t).css("height",t)})};portal.fullRefresh=function(){window.location.href=window.location.href};portal.qs=function(n){var i=[];for(var t in n)n.hasOwnProperty(t)&&i.push(encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return i.join("&")};portal.goto=function(n,t){n&&n!=""&&(window.History&&window.History.enabled?!t&&location.href.indexOf(n)>0?$(window).trigger("statechange"):History.pushState(null,null,n):window.location.href=n)};portal.addOption=function(n,t,i){var r=$("<option><\/option>").attr("selected","selected").val(t).text(i);n.append(r)};portal.decodeHtml=function(n){return $("<div/>").html(n).text()};portal.refresh=function(n){n?portal.persistScroll():portal.persistScroll(!0);$.cookie("PortalDevice",portal.getDevice());window.History&&window.History.enabled?$(window).trigger("statechange"):portal.fullRefresh()};portal.formSubmit=function(n,t){var i=$("form:first",n||$("#p"));t?i.submit():i[0].submit()};portal.getDevice=function(){var i=["xs","sm","md","lg"],n,t;for($el=$("<div>"),$el.appendTo($("body")),n=i.length-1;n>=0;n--)if(t=i[n],$el.addClass("hidden-"+t),$el.is(":hidden"))return $el.remove(),t};portal.util={getDateTimeParamString:function(n,t,i,r){var u=n.getDate(),f=n.getMonth()+1,e=n.getFullYear();return u<10&&(u="0"+u),f<10&&(f="0"+f),t=parseInt(t),i=parseInt(i),t<10&&(t="0"+t),i<10&&(i="0"+i),f+"/"+u+"/"+e+" "+t+":"+i+" "+r.toUpperCase()},browserCheck:{isIE:function(){return!1||!!document.documentMode},isEdge:function(){return!portal.util.browserCheck.isIE()&&!!window.StyleMedia}}};portal.modal={};portal.modal.success=function(n,t){$("#"+n).off("modal.success").on("modal.success",t)};portal.modal.failure=function(n,t){$("#"+n).off("modal.failure").on("modal.failure",t)};portal.showProgress=function(n,t,i,r){if(r=r||{},r.zIndex||(r.zIndex=3),$("#"+n).length>0){$("#"+n).show();return}var u='<div id="'+n+'" class="loading-wrap inset-shadow" style="'+(!r.zIndex||"z-index: "+r.zIndex+";")+";"+(!r.bgColor||"background: "+r.bgColor)+'"><div class="loading-header bold">'+t+'<\/div><div class="loading"><div><i class="fa fa-spin fa-refresh"><\/i><\/div><h3 class="light">'+i+"<\/h3><\/div><\/div>";$(document.body).prepend(u)};portal.hideAllProgress=function(){$(".loading-wrap").remove()};portal.popup=function(n,t,i,r){r=r||{};var u=r.id||"portalconfirm";return $("#"+u).remove(),$("body").append('<div id="'+u+'" class="modal'+(r.static?" modal-static":"")+" fade"+(r.modalClass?" "+r.modalClass:"")+'" tabindex="-1" data-width="'+(r.width||"400")+'"'+(r.static?' data-keyboard="false" data-backdrop="static"':"")+'><div class="modal-header">'+(r.static?"":'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;<\/button>')+'<h4 class="modal-title">'+n+'<\/h4><\/div><div class="modal-body">'+t+"<\/div>"+(i?'<div class="modal-footer">'+i+"<\/div>":"")+"<\/div>"),$("#"+u).modal("show")};portal.alert=function(n,t,i){portal.popup(n,t,'<button type="button" class="btn btn-default pull-right" data-dismiss="modal">OK<\/button>',i)};portal.confirm=function(n,t,i,r){r=r||{};portal.popup(n,t.replace(/\{/gi,"<").replace(/\}/gi,">"),'<button type="button" class="btn btn-danger pull-left" style="width: auto">Yes, '+n+'<\/button><button type="button" class="btn btn-default pull-right" data-dismiss="modal">Cancel<\/button>',r);var u=r.id||"portalconfirm";if(i)$("#"+u+" .btn-danger").off("click").on("click",function(){i();$("#"+u).modal("hide")})};portal.resetPageLayout=function(){portal.cancelPageLayout(!0);$X("post/widget/clear",{sik:portal.opts.sik},function(){portal.refresh()})};portal.cancelPageLayout=function(n){$(".gridster").removeClass("gridster-editable");$(".cancel-layout, .save-layout, .reset-layout").parent().hide();$(".edit-layout").parent().show();$(".hide-on-edit-layout").show();n||portal.refresh()};portal.showPageLayout=function(){$(".gridster").addClass("gridster-editable");$(".cancel-layout, .save-layout, .reset-layout").parent().show();$(".edit-layout").parent().hide();$(".hide-on-edit-layout").hide()};portal.savePageLayout=function(){portal.cancelPageLayout(!0);var n=[],t=portal.getDevice();$(".gridster > ul > li").each(function(){var t=$(this);n.push({WidgetInstanceDeviceKey:t.attr("data-instance-device-key"),GridRow:t.attr("data-row"),GridColumn:t.attr("data-col"),GridHeight:t.attr("data-sizey"),GridWidth:t.attr("data-sizex")})});$X("post/widget/PersistPosition",{items:JSON.stringify(n),nowait:!0},function(){portal.refresh(!0)})};portal.removedWidget=function(n){var t=n.closest("li");$X("post/widget/remove",{widgetInstanceKey:t.attr("data-instance-key")})};portal.print={};portal.print.openLabelPrintDialog=function(n,t,i){$X("get/print/printlabels",{vcdb:n,homeLocationKey:t,regVehicleKey:i},function(){})};portal.print.printLabels=function(n,t,i,r){var h=portal.util.browserCheck.isIE(),c=portal.util.browserCheck.isEdge(),f={content:[],pageSize:{width:288,height:96},pageOrientation:"landscape",pageMargins:[15,15,15,0]},s,u,e,o;for(r&&(f.background={margin:[0,8,5,0],alignment:"right",fit:[28,28],image:"data:image/png;base64,iVBORw0KGgoAAA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BlYHLA4sEPKaQ8CNwCXyIU6RQxiE3BfAPBC9Yynax56GBgc4PxEYL9laeqoFAuWxiCJjVKGi+wb5bbAWs3DdwEDA5arlokXtAHyo5gcS2iHEaToudfgWQcGfM5I4EPJDoJc4P0Y40QnNg+fnLdRw+wHvE5dUBqG92nqTp9LrIw5TnQuebl0t0ENG6TYaUNdgJvwGthrxCQ0AH9FoMJB1Xk2EdMUzk4kqCL9WkP90I+6irkYIuHN4AjvoVLn2P6oxUOY5/o24jXOi52yCxCz42Z+jyZGzA4PFuF9A1LMNAR4rFDMRwQwyPvl1+1LStoYb3WAsOAQ8JI4jQ4pbOdSa8lYjhBsSn4r8AxwO974SHnSAShz9JyrJYYaa3GmQczAj5K+HRBpPYlX5d5eihI5Hm9Qp2S+qIyC2kvgvZ6zH7fYrlWpdfTMw3DgRcx/ICeOXDjx1F0cxxK8gc5jLUWFywrAs1yqOAMkI+iLNwlWAZwvay3upgsipf8GALHo6rs7h6iGAAAAAElFTkSuQmCC"}),s=0,u=0;u<i;u++)e={columns:[{width:80,qr:n.toString(),foreground:"black",fit:83,margin:s},{width:"*",margin:[0,-5,0,0],stack:[{text:"ID: "+n.toString()+"\n",fontSize:22},{text:t.replace("\\n","\n")}]}]},u<i-1&&(e.pageBreak="after"),f.content.push(e);o=pdfMake.createPdf(f);h||c?o.download(n+".pdf"):o.print()};portal.chat={};portal.chat.ui={};portal.chat.ui.link=null;portal.chat.ui.container=null;portal.chat.ui.body=null;portal.chat.hasLoadedItems=!1;portal.chat.ui.init=function(){var n,t;ko.dataFor($("#chat")[0])||(n=$.jStorage.get("selectedMessageType"),n==null&&(n="Private"));portal.chat.ui.confirmRecall=!1;portal.chat.ui.container=$(".chat");portal.chat.ui.body=portal.chat.ui.container.find(".pod-body");portal.chat.ui.content=portal.chat.ui.container.find(".chat-content");portal.chat.ui.recipient=portal.chat.ui.container.find(".pod-footer .btn-recipients");portal.chat.ui.important=portal.chat.ui.container.find(".msg-important");portal.chat.ui.textbox=portal.chat.ui.container.find('input[type="text"]');portal.chat.ui.filterDropdown=portal.chat.ui.container.find(".pod-title .dropdown-menu");portal.chat.ui.initializeTaskInputs=function(){portal.chat.ui.relocateTask=$(".relocate");portal.chat.ui.genericTask=$(".generic");portal.chat.ui.compose=$(".compose");$(".taskicon").off("mouseenter mouseleave").hover(function(){var n=$(".plus");n.removeClass("fa-plus").addClass("fa-pencil")},function(){var n=$(".plus");n.removeClass("fa-pencil").addClass("fa-plus")});portal.chat.ui.relocateTask.off("click").on("click",function(){t("Relocate")});portal.chat.ui.genericTask.off("click").on("click",function(){t("Generic")});portal.chat.ui.compose.off("click").on("click",function(){portal.chat.ui.getComposeModal(null)})};portal.chat.ui.initializeTaskInputs();portal.chat.ui.updateDueDatePick=function(n,t){$("#DueDatePick").val(t);$(".pick").removeClass("active");$(n).addClass("active");t=="Custom"?($("#DueDateCustom").parent().show(),$("#DueDateCustom").focus()):$("#DueDateCustom").parent().hide()};portal.chat.ui.showDueDatePick=function(){$(".picktoggle").removeClass("hidden")};portal.chat.ui.hideDueDatePick=function(){$(".picktoggle").removeClass("hidden");$(".picktoggle").addClass("hidden")};t=function(n){$X("get/tasks/Task",{type:n},function(){$("#msltItems, .select2").select2({width:"100%",minimumResultsForSearch:Infinity});$("#searchUsers").val(null).trigger("Dchange");$("#searchUsers").select2({ajax:{width:"100%",url:"/Settings/SearchUser",dataType:"json",delay:250,data:function(n){return{term:n.term,getAlertGroups:!0,onlyAvailable:!0}},processResults:function(n){var t=$.map(n.Groups,function(n){return{text:n.GroupName,id:n.GroupKey,userId:null,alertGroupKey:n.GroupKey,firstname:null,lastname:null,isUser:!1,isGroup:!0}}),i=$.map(n.Users,function(n){return{text:n.FirstName+" "+n.LastName,id:n.UserId,userId:n.UserId,alertGroupKey:null,firstname:n.FirstName,lastname:n.LastName,isUser:!0,isGroup:!1}});return{results:i.concat(t)}},cache:!1,placeholder:"Search Users and Alert Groups"},escapeMarkup:function(n){return n},minimumInputLength:1})})};portal.chat.ui.getComposeModal=function(n){$X("get/messaging/compose",{},function(){var t,i,r;portal.chat.ui.compose.onlyAvailable=!1;portal.chat.ui.compose.isImportant=!1;$(".alert-group-info").hide();$(".available-only-container").hide();$("#msltItems, .select2").select2({width:"100%",minimumResultsForSearch:Infinity});$(".msg-important").off("click").on("click",function(){$(this).toggleClass("msg-important-on");portal.chat.ui.compose.isImportant=$(this).hasClass("msg-important-on")});$(".available-only").off("click").on("click",function(){$(".available-only>i").toggleClass("portal-blue");$(".available-only>i").toggleClass("fa-check-square");$(".available-only>i").toggleClass("fa-square-o");portal.chat.ui.compose.onlyAvailable=$(".available-only>i").hasClass("portal-blue")});$(".btn-send-message").off("click").on("click",function(){portal.chat.ui.sendMessage()});portal.chat.ui.composeTo=portal.chat.ui.container.find('input[type="text"]');t="/Settings/SearchUser";$("#searchUsers").val(null).trigger("Dchange");$("#searchUsers").select2({ajax:{width:"100%",url:t,dataType:"json",delay:250,data:function(n){return{term:n.term,getAlertGroups:!0,onlyAvailable:!1}},processResults:function(n){var t=$.map(n.Groups,function(n){return{text:n.GroupName,id:n.GroupKey,userId:null,alertGroupKey:n.GroupKey,firstname:null,lastname:null,isUser:!1,isGroup:!0}}),i=$.map(n.Users,function(n){return{text:n.FirstName+" "+n.LastName,id:n.UserId,userId:n.UserId,alertGroupKey:null,firstname:n.FirstName,lastname:n.LastName,isUser:!0,isGroup:!1}});return{results:i.concat(t)}},cache:!1,placeholder:"Search Users and Alert Groups"},escapeMarkup:function(n){return n},minimumInputLength:1},n);$("#searchUsers").on("select2:select",function(n){var t=n.params;t&&t.data&&t.data.isGroup?($(".alert-group-info").show(),$(".available-only-container").show(),$("#searchUsers + .select2").css("width","96%"),$(".alert-group-info").attr("data-k",t.data.alertGroupKey),$(".alert-group-info").attr("data-n",t.data.text)):($(".alert-group-info").hide(),$(".available-only-container").hide(),portal.chat.ui.compose.onlyAvailable&&$(".available-only").trigger("click"),$("#searchUsers + .select2").css("width","100%"),$(".alert-group-info").attr("data-k",t.data.userId),$(".alert-group-info").attr("data-n",t.data.text));portal.chat.ui.compose.recipient=t.data});n!=null&&(i=$("#searchUsers"),r=$("<option selected>"+n.FirstName+" "+n.LastName+"<\/option>").val(n.UserUID),i.append(r).trigger("change"),portal.chat.ui.compose.recipient={text:n.FirstName+" "+n.LastName,id:n.UserUID,userId:n.UserUID,alertGroupKey:null,firstname:n.FirstName,lastname:n.LastName,isUser:!0,isGroup:!1});$(".alert-group-info").off("click").on("click",function(n){n.stopImmediatePropagation();var t=$(this).attr("data-k");portal.events.alertGroupPopup(t)})})};portal.chat.ui.link=$('li[data-sik="9"] a');portal.chat.ui.link.off("click").click(function(n){return portal.chat.ui.toggle(),$(".small-menu-dropdown.dropdown.open .dropdown-toggle").dropdown("toggle"),n.stopImmediatePropagation(),n.preventDefault(),!1});portal.chat.ui.important.off("click").click(function(){$(this).toggleClass("msg-important-on")});portal.chat.ui.filterDropdown.find("a").off("click").click(function(){portal.chat.ui.filterDropdown.find("i").remove();$(this).append('<i class="glyphicon glyphicon-ok-circle"><\/i>');portal.chat.ui.reloadMessages()});portal.chat.ui.textbox.off("keypress").keypress(function(n){n.which==13&&portal.chat.ui.send()});portal.chat.ui.recipient.off("click").click(function(){$("#chat-recipient-list").remove();portal.chat.ui.content.append('<div id="chat-recipient-list" class="chat-recipient-list y-scrollbar"><p class="text-center" style="margin-top: 20px">Loading recipients, one moment...<\/p><\/div>');var n=portal.chat.ui.container.find(".pod-body");$("#chat-recipient-list").height(n.height());$X("get/messaging/recipients",{_:(new Date).getTime()},function(n){portal.chat.ui.content.find("#chat-recipient-list").html(n);portal.chat.ui.content.find(".chat-recipient-list-inner").off("click",".list-group-item").on("click",".list-group-item",function(){var t=$(this).attr("data-k"),n=$(this).attr("data-n");portal.chat.ui.recipient.find(".btn-label").attr("data-k",t).attr("data-n",n).text(n).attr("title",n);portal.chat.ui.textbox.css("padding-right",portal.chat.ui.recipient.outerWidth()+15);$("#chat-recipient-list").remove();portal.chat.ui.textbox.focus()});portal.chat.ui.content.find(".chat-recipient-list-inner").off("click",".list-group-item a.alert-group-info").on("click",".list-group-item a.alert-group-info",function(n){n.stopImmediatePropagation();var t=$(this).attr("data-k");portal.events.alertGroupPopup(t)})})})};portal.chat.ui.originalTitle=document.title;portal.chat.ui.send=function(){var n=$.trim(portal.chat.ui.textbox.val());if(n=="")portal.alert("Message Required","Please enter a message before sending.");else if(portal.chat.ui.compose.recipient==null)portal.alert("Recipient Required","Please select a recipient before sending.");else{var t=portal.chat.ui.recipient,i=t.find(".btn-label").attr("data-k"),r=t.find(".btn-label").attr("data-n");portal.chat.ui.textbox.val("").focus();$X("post/messaging/send",{toUserId:i,toUserName:r,messageText:n,json:!0,important:portal.chat.ui.important.hasClass("msg-important-on")},function(n){n.success||portal.alert("Message Not Sent","We are sorry, but this message could not be sent.  Please try again later.")})}};portal.chat.ui.clearRecipient=function(){portal.chat.ui.compose.recipient=null};portal.chat.ui.sendMessage=function(){var t=$.trim($("#message").val());if(t=="")portal.alert("Message Required","Please enter a message before sending.");else if(portal.chat.ui.compose.recipient==null)portal.alert("Recipient Required","Please select a recipient before sending.");else{var n=portal.chat.ui.compose.recipient,i=n.isGroup?n.alertGroupKey:n.userId,r=n.text,u=$("#textPriority").val();portal.chat.ui.textbox.val("").focus();$X("post/messaging/send",{toUserId:i,toUserName:r,messageText:t,json:!0,important:u,onlyAvailable:portal.chat.ui.compose.onlyAvailable},function(n){n.success?$(".modal").modal("hide"):portal.alert("Message Not Sent","We are sorry, but this message could not be sent.  Please try again later.")})}};portal.chat.ui.toggle=function(){if(portal.chat.ui.container.hasClass("chat-show")){if(portal.chat.ui.isDocked){portal.chat.ui.container.removeAttr("style");var n=portal.chat.ui.container.find(".pod-body");n.height(300);$("#expand>i").removeClass("fa-compress");$("#expand>i").addClass("fa-expand");portal.chat.ui.isDocked=!1}portal.chat.ui.container.removeClass("chat-show")}else portal.chat.ui.container.addClass("chat-show"),document.title=portal.chat.ui.originalTitle,setTimeout(function(){portal.chat.ui.container.hasClass("chat-show")&&portal.chat.ui.container.find("input:first").focus()},600)};portal.chat.ui.isDocked=!1;portal.chat.ui.toggleDock=function(){var n;if(portal.chat.ui.isDocked)portal.chat.ui.container.removeAttr("style"),n=portal.chat.ui.container.find(".pod-body"),n.height(300),$("#chat-recipient-list").height(n.height()),$("#expand>i").removeClass("fa-compress"),$("#expand>i").addClass("fa-expand"),portal.chat.ui.isDocked=!1;else{var i=window.navigator.userAgent,t=0,r=i.indexOf("MSIE ");(r>0||!!navigator.userAgent.match(/Trident.*rv\:11\./)||navigator.userAgent.includes("Edge"))&&(t=16,Check_Version()==12&&(t=11));portal.chat.ui.container.css({position:"fixed",right:t,top:40,bottom:0});n=portal.chat.ui.container.find(".pod-body");n.height(portal.chat.ui.container.height()-61);$("#chat-recipient-list").height(n.height());$("#expand>i").removeClass("fa-expand");$("#expand>i").addClass("fa-compress");portal.chat.ui.isDocked=!0}portal.chat.ui.body.scrollTop(99999)};$(window).resize(function(){if(portal.chat.ui.isDocked){var n=portal.chat.ui.container.find(".pod-body");n.height(portal.chat.ui.container.height()-94)}});portal.feed={};portal.feed.seededData=!1;portal.feed.isScrolling=!1;portal.feed.setPresenceToAvailable=!0;portal.feed.setUserStatus=function(n,t){portal.feed.vm.presence(n=="Available");$(".switch-wrap input").prop("checked",n=="Available");t&&$(".switch-wrap input:first").change()};portal.feed.init=function(){var u,t,i,r,n,f;portal.feed.vm.initPageSize();$(document).off("change.presence").on("change.presence",".switch-wrap input",function(){var n=$(this),t,i;portal.isInitializing||n.parent().attr("data-canchange")!="false"?(i=n.prop("checked")?"Available":"Unavailable",portal.feed.serverCall("/user-status/"+i+"/"+portal.site.SiteUID+"/Desktop",{},null,{rootUrl:"global"})):(t=n.prop("checked"),n.prop("checked",!t),portal.alert("No Access","You do not have permission to change your status."))});for(portal.feed.setPresenceToAvailable&&(portal.feed.setUserStatus("Available",!0),portal.feed.vm.presence(!0),portal.feed.setPresenceToAvailable=!1),setTimeout(function(){$(".switch-wrap input").prop("checked",portal.feed.vm.presence())},1e3),u=!1,t=$(".feed"),n=0;n<t.length;n++)$(t[n]).hasClass("initialized")||(u=!0,$(t[n]).addClass("initialized"),ko.cleanNode(t[n]),ko.applyBindings(portal.feed.vm,t[n]));for(i=$(".feed-header"),n=0;n<i.length;n++)$(i[n]).hasClass("initialized")||($(i[n]).addClass("initialized"),ko.cleanNode(i[n]),ko.applyBindings(portal.feed.headerVM,i[n]));for(r=$(".feed-scrollable"),n=0;n<r.length;n++)if(!$(r[n]).hasClass("initialized")){f=function(n){n.stopPropagation();var t=$(n.currentTarget);portal.feed.scrollId!=t.attr("data-scrollid")&&(portal.feed.scrollId=t.attr("data-scrollid"),portal.feed.scrollable=t,portal.feed.vm.initPageSize());(t[0].scrollHeight-t.scrollTop()==t.outerHeight()||t[0].scrollHeight-t.scrollTop()<=t.outerHeight()+50&&t[0].scrollHeight-t.scrollTop()>=t.outerHeight()-50)&&(portal.feed.vm.isLoading()||(n.stopPropagation(),portal.feed.vm.load(function(){portal.feed.isScrolling=!1})))};portal.feed.scrollable||(portal.feed.scrollable=$(r[n]));$(r[n]).off("scroll").on("scroll",f);$(r[n]).addClass("initialized")}u&&(portal.feed.vm.initPageSize(),portal.feed.seededData||(portal.feed.vm.load(),portal.feed.seededData=!0));portal.feed.vm.items().forEach(function(n){n.ItemType=="Task"&&colorizeItem(n)})};colorizeItem=function(n){n.interval&&window.clearTimeout(n.interval);colorizeInner(n);var t=setInterval(function(){colorizeInner(n,t)},3e4);n.interval=t};colorizeInner=function(n,t){$('span[id="'+n.EntityKey+'"]').each(function(){var i=$(this),f=i.attr("data-time-value"),u=i.attr("data-time"),e=new Date,o=new Date(f),s=o-e,r=Math.floor(s/6e4);n.TaskStatus=="Completed"||n.TaskStatus=="Cancelled"?(i.css("color","black"),r<0&&i.text(u),window.clearTimeout(t)):r<=15&&r>=5?i.css("color","#DAA520"):r<5&&(i.css("color","#FF0033"),r<0&&i.text(u))})};portal.feed.feedItemInsertImpl=function(n){if(n.SiteUID==portal.site.SiteUID){var t=portal.feed.vm;t.items().push(n);t.items().sort(function(n,t){return n.Sequence>t.Sequence?1:-1});t.items.valueHasMutated();colorizeItem(n)}};portal.feed.feedItemDeleteImpl=function(n){var t=portal.feed.vm,i=ko.utils.arrayFirst(t.items(),function(t){return t.FeedItemKey===n.FeedItemKey});t.items.remove(i);t.items.valueHasMutated()};portal.feed.siteChangeLogoutImpl=function(){portal.logout(!0)};portal.feed.userStatusChangeImpl=function(n){var i=portal.feed.vm,t=ko.utils.arrayFirst(i.teamItems(),function(t){return t.UserUID===n.UserUID});portal.opts.uid!=null&&n.UserUID==portal.opts.uid&&portal.feed.setUserStatus(n.Status);t!=null&&(n.FirstName=t.FirstName,n.LastName=t.LastName,i.teamItems.replace(t,n),i.teamItems.valueHasMutated())};portal.feed.feedItemUpdateImpl=function(n){var t=portal.feed.vm,i=ko.utils.arrayFirst(t.items(),function(t){return t.FeedItemKey===n.FeedItemKey});t.selectedItem().FeedItemKey==n.FeedItemKey&&(n.CommentCount!=t.selectedItem().CommentCount&&t.selectedItemComments(n.Comments),t.selectedItem(n));t.items.replace(i,n);t.items().sort(function(n,t){return n.Sequence>t.Sequence?1:-1});t.items.valueHasMutated();colorizeItem(n)};portal.feed.serverCall=function(n,t,i,r){t=t||{};t.json=!0;$X((r&&r.post?"post":"get")+"/controller/method",t,function(n){i&&i(n)},{addBearerToken:!0,url:"/api-v1/"+(r&&r.rootUrl?r.rootUrl:"messenger")+n})};ko.observableArray.fn.pushAll=function(n){var t=this();return this.valueWillMutate(),ko.utils.arrayPushAll(t,n),this.valueHasMutated(),this};portal.feed.vm=new FeedViewModel;portal.feed.headerVM=new FeedHeaderViewModel;ko.bindingHandlers.enterKey={init:function(n,t,i,r){var u=t();$(n).keypress(function(n){var t=n.which?n.which:n.keyCode;return t===13?(u.call(r),!1):!0})}};portal.liveView={};portal.liveView.init=function(){};portal.liveView.addPortalItem=function(n){$X("post/liveView/addPortalItem",{portalItemId:n},function(){})};portal.liveView.removePortalItem=function(n,t){$X("post/liveView/removePortalItem",{portalItemId:n},t)};portal.liveView.removeAllPortalItems=function(){$X("post/liveView/removeAllPortalItems",{},function(){})};portal.locationPicker={};portal.locationPicker.onSelectLocationHandlers={};portal.locationPicker.onRemoveLocationHandlers={};portal.locationPicker.load=function(n,t){var i=$('.location-picker[data-lp-id="'+n+'"]'),r=i.find(".location-picker-search"),u=i.find(".location-picker-list"),f=i.find(".location-picker-box");f.hide();i.off("focusin").on("focusin",function(){f.show();$(document).bind("click.hideLocList",function(n){i.is(n.target)||i.has(n.target).length!==0||(f.hide(),$(document).unbind("click.hideLocList"))})});r.off("keyup").on("keyup",function(){var n=this.value.toLowerCase();u.children().show();portal.locationPicker.searchBox(u.children('[data-depth="0"]'),n)});u.find("li").off("click").click(function(){portal.locationPicker.toggleLocation($(this),n,t);t?($(".location-picker-search").val(""),$(document).trigger("click.hideLocList")):(r.val(""),r.focus())})};portal.locationPicker.searchBox=function(n,t){n.each(function(){if($(this).text().toLowerCase().indexOf(t)===-1)if($(this).hasClass("loc-select-parent")){var n=$(this).attr("value"),i=$(this).parents(".location-picker-list");portal.locationPicker.searchBox(i.children('[data-parent="'+n+'"]'),t);i.children(':visible[data-parent="'+n+'"]').length==0&&$(this).hide()}else $(this).hide();else $(this).show()})};portal.locationPicker.toggleLocation=function(n,t,i){var o=n.text(),u=$('.location-picker-count[data-lp-id="'+t+'"]'),f=u.find(".location-picker-count-value"),s=parseInt(f.text()),h=n.attr("value"),e=!1,r;n.hasClass("loc-selected")?i||portal.locationPicker.removeLocation(n,t):(i?portal.locationPicker.clear(t):(u.show(),f.text(s+1)),e=!0,n.addClass("loc-selected"),n.prepend('<i class="fa fa-check-circle-o pull-right"><\/i>'),portal.locationPicker.addNameToList(o,h,t,i));e&&(r=portal.locationPicker.onSelectLocationHandlers[t],r&&r())};portal.locationPicker.addNameToList=function(n,t,i,r){r&&$('.location-picker-select-list[data-lp-id="'+i+'"]').html("");$('.location-picker-select-list[data-lp-id="'+i+'"]').show();var u='<span class="location-picker-selected-name" value="'+t+'">';r||(u=u+'<i class="fa fa-times location-picker-selected-name-x" onclick="portal.locationPicker.removeLocationFromUid(\''+t+"', '"+i+"')\"><\/i>");u=u+n+"<\/span>";$('.location-picker-select-list[data-lp-id="'+i+'"]').append(u)};portal.locationPicker.removeNameFromList=function(n,t){$('.location-picker-select-list[data-lp-id="'+t+'"]').find('span[value="'+n+'"]').remove()};portal.locationPicker.removeLocation=function(n,t){var f=n.attr("value"),i,u,r;n.removeClass("loc-selected");n.find("i").remove();i=$('.location-picker-count-value[data-lp-id="'+t+'"]');u=parseInt(i.text());i.text(u-1);portal.locationPicker.removeNameFromList(f,t);r=portal.locationPicker.onRemoveLocationHandlers[t];r&&r()};portal.locationPicker.removeLocationFromUid=function(n,t){var i=$('.location-picker-list[data-lp-id="'+t+'"] li[value="'+n+'"]');portal.locationPicker.removeLocation(i,t)};portal.locationPicker.selectLocation=function(n,t,i){var r=$('ul[data-lp-id="'+t+'"] li[value="'+n+'"]');portal.locationPicker.toggleLocation(r,t,i)};portal.locationPicker.getLocations=function(n){var t="";return $('.location-picker[data-lp-id="'+n+'"]').find(".loc-selected").each(function(){t!=""&&(t=t+",");t=t+$(this).attr("value")}),t};portal.locationPicker.getLocationCount=function(n){return $('.location-picker[data-lp-id="'+n+'"] .loc-selected').length};portal.locationPicker.validateLocations=function(n){return portal.locationPicker.getLocations(n)==""?($('.location-picker-error[data-lp-id="'+n+'"]').removeClass("hidden"),!1):($('.location-picker-error[data-lp-id="'+n+'"]').addClass("hidden"),!0)};portal.locationPicker.clear=function(n){$('.location-picker-list[data-lp-id="'+n+'"] .loc-selected').each(function(){portal.locationPicker.removeLocation($(this),n)});portal.locationPicker.onSelectLocationHandlers[n]=null;portal.locationPicker.onRemoveLocationHandlers[n]=null};portal.locationPicker.onSelectLocation=function(n,t){portal.locationPicker.onSelectLocationHandlers[n]=t};portal.locationPicker.onRemoveLocation=function(n,t){portal.locationPicker.onRemoveLocationHandlers[n]=t};portal.locationPathPicker={onAddPathHandlers:{},onRemovePathHandlers:{},load:function(n){var t={locationPathPickerId:n,$selectedPathList:$('.location-path-picker-select-list[data-lp-id="'+n+'"]'),$count:$('.location-path-picker-count[data-lp-id="'+n+'"]'),$countValueBox:$('.location-path-picker-count-value[data-lp-id="'+n+'"]'),$modal:$('div.modal[data-lp-id="'+n+'"]')};t.$selectedPathList.empty();t.$count.hide();portal.locationPathPicker.onAddPathHandlers[n]=null;portal.locationPathPicker.onRemovePathHandlers[n]=null;$('.location-path-picker[data-lp-id="'+n+'"] .location-path-add').off("click").on("click",function(){portal.locationPathPicker.modal.load(t,{steps:[]},null);t.$modal.modal({show:!0})});t.$selectedPathList.off("click",".location-path-picker-selected-path-x").on("click",".location-path-picker-selected-path-x",function(){portal.locationPathPicker.removePath(t,$(this).closest(".location-path-picker-selected-path"))});t.$selectedPathList.off("click",".location-path-picker-selected-path-e").on("click",".location-path-picker-selected-path-e",function(){var n=$(this).closest(".location-path-picker-selected-path"),i=n.data("path");portal.locationPathPicker.modal.load(t,i,n);t.$modal.modal({show:!0})});return t},addUpdatePath:function(n,t,i){for(var f,e,o,r='<span class="location-path-picker-selected-path"><i class="fa fa-times location-path-picker-selected-path-x"><\/i>',u=0;u<t.steps.length;++u)r+=t.steps[u].name,u<t.steps.length-1&&(r+='<i class="fa fa-caret-right location-path-picker-selected-path-s"><\/i>');r+='<i class="fa fa-edit location-path-picker-selected-path-e"><\/i><\/span>';f=$(r);f.data("path",t);e=!1;i!=null?i.replaceWith(f):(e=!0,n.$selectedPathList.append(f));n.$selectedPathList.show();portal.locationPathPicker.updateSelectedCount(n);e&&(o=portal.locationPathPicker.onAddPathHandlers[n.locationPathPickerId],o&&o())},removePath:function(n,t){t.remove();portal.locationPathPicker.updateSelectedCount(n);var i=portal.locationPathPicker.onRemovePathHandlers[n.locationPathPickerId];i&&i()},updateSelectedCount:function(n){var t=n.$selectedPathList.find(".location-path-picker-selected-path");n.$countValueBox.text(t.length);n.$count.show()},onAddPath:function(n,t){portal.locationPathPicker.onAddPathHandlers[n]=t},onRemovePath:function(n,t){portal.locationPathPicker.onRemovePathHandlers[n]=t},getSelectedPaths:function(n){var t=[],i=$('.location-path-picker-select-list[data-lp-id="'+n+'"]');return i.find(".location-path-picker-selected-path").each(function(){for(var u,f=$(this),i=f.data("path"),r={Locations:[]},n=0;n<i.steps.length;++n)u={LocationId:i.steps[n].locId,Sequence:n+1},r.Locations.push(u);t.push(r)}),t},getSelectedPathCount:function(n){return $('.location-path-picker-select-list[data-lp-id="'+n+'"] .location-path-picker-selected-path').length}};portal.locationPathPicker.modal={load:function(n,t,i){var u=$('.location-picker[data-lp-id="'+n.locationPathPickerId+'"]'),r={pickerContext:n,path:t,$pathItem:i,locationPathPickerId:n.locationPathPickerId,$modal:n.$modal,$picker:u,$searchBox:u.find(".location-picker-search"),$list:u.find(".location-picker-list"),$box:u.find(".location-picker-box"),$pathTable:n.$modal.find("table.location-path-steps")},f;for(r.$box.hide(),portal.locationPathPicker.modal.clearSteps(r),f=0;f<t.steps.length;++f)portal.locationPathPicker.modal.addLocation(r,t.steps[f]);u.off("focusin").on("focusin",function(){r.$box.show();$(document).bind("click.hideLocList",function(n){r.$picker.is(n.target)||r.$picker.has(n.target).length!==0||(r.$box.hide(),$(document).unbind("click.hideLocList"))})});r.$searchBox.off("keyup").on("keyup",function(){var n=this.value.toLowerCase();r.$list.children().show();portal.locationPicker.searchBox(r.$list.children('[data-depth="0"]'),n)});r.$list.find("li").off("click").click(function(){portal.locationPathPicker.modal.selectLocation(r,$(this))});r.$pathTable.find("a.loc-path-step-removeall").off("click").on("click",function(){portal.locationPathPicker.modal.clearSteps(r)});r.$pathTable.off("click",".loc-path-step-remove").on("click",".loc-path-step-remove",function(){$(this).closest("tr").remove()});r.$pathTable.off("click",".loc-path-step-moveup").on("click",".loc-path-step-moveup",function(){var n=$(this).closest("tr"),t=n.prev();t.length>0&&n.insertBefore(t)});r.$pathTable.off("click",".loc-path-step-movedown").on("click",".loc-path-step-movedown",function(){var n=$(this).closest("tr"),t=n.next();t.length>0&&n.insertAfter(t)});r.$modal.find(".modal-footer .btn-primary").off("click").on("click",function(){portal.locationPathPicker.modal.acceptChanges(r)});r.$modal.find(".modal-footer .btn-default").off("click").on("click",function(){portal.locationPathPicker.modal.cancelChanges(r)})},selectLocation:function(n,t){var i={locId:t.attr("value"),name:t.text()};portal.locationPathPicker.modal.addLocation(n,i);n.$searchBox.val("");n.$box.hide()},addLocation:function(n,t){var i=n.$pathTable.find(".loc-path-step-template").clone(!0);i.removeClass("loc-path-step-template");i.data("location",t);i.find(".loc-path-step-name").text(t.name);n.$pathTable.find("tbody").append(i);i.show()},clearSteps:function(n){n.$pathTable.find("tbody tr").remove()},acceptChanges:function(n){var t={steps:[]};n.$pathTable.find("tbody tr").each(function(){var n=$(this);t.steps.push(n.data("location"))});portal.locationPathPicker.addUpdatePath(n.pickerContext,t,n.$pathItem);n.$modal.modal("hide")},cancelChanges:function(n){n.$modal.modal("hide")}};portal.register={$resetBatterySocModal:null,resetBatterySocKvm:null,onResetBatterySocModalAcceptChanges:null,openResetBatterySocModal:function(n,t){var i=this;this.onResetBatterySocModalAcceptChanges=t;this.resetBatterySocKvm.reset(n);this.$resetBatterySocModal.modal("show");portal.loadTooltips()}};portal.register.ResetBatterySocViewModel=function(){var n=this;this.availableTags=ko.observableArray();this.tag=ko.observable();this.resetDate=ko.observable("");this.tagName=ko.pureComputed(function(){var t="";return n.tag()&&n.tag().hasOwnProperty("Value")&&(t=n.tag().Value),t});this.isTagSelectionEnabled=ko.pureComputed(function(){return n.availableTags().length>1});this.reset=function(t){n.tag(null);n.availableTags.removeAll();var i=new Date;n.resetDate(""+(i.getMonth()+1)+"/"+i.getDate()+"/"+i.getFullYear());t&&(t.forEach(function(t){n.availableTags.push(t)}),t.length>0&&n.tag(t[0]))}};portal.reports={};portal.reports.custom={allFields:[],dateFilterTypes:[{id:"lastknown",text:"Last Known"},{id:"day",text:"Yesterday"},{id:"week",text:"Past Week"},{id:"month",text:"Past Month"},{id:"range",text:"Date Range"}],timespanUnits:[{id:"minute",text:"Minutes"},{id:"hour",text:"Hours"},{id:"day",text:"Days"}],$editModal:null,editCustomReportKvm:null,onEditCustomReportModalAcceptChanges:null,openEditReportModal:function(n,t){var i=this;this.onEditCustomReportModalAcceptChanges=t;this.editCustomReportKvm.loadReport(n);this.$editModal.modal("show");$(".nav-tabs a",this.$editModal).first().click();portal.loadTooltips();$("select",this.$editModal).trigger("change")},editCustomReport:function(n,t){this.openEditReportModal(n,function(i){if(i.validate()){n.Name=i.reportName();n.Columns=[];_.forEach(i.columns(),function(t){var i={Id:t.id,ReportId:n.ID,ReportFieldId:t.reportFieldId,DisplaySequence:t.displaySequence(),IsFiltered:t.isFiltered(),FilterJson:JSON.stringify(t.getFilterData()),IsSorted:t.isSorted(),SortSequence:t.isSorted()?t.sortSequence():null,SortDirection:t.isSorted()?t.sortDirection().id:null};n.Columns.push(i)});var r={url:"/report/SaveCustomReport",type:"post",data:n};$.ajax(r).done(function(){portal.reports.custom.$editModal.modal("hide");t&&t()}).fail(function(){portal.alert("Unable to save changes.")})}})},deleteCustomReport:function(n,t){portal.confirm("Remove Report",'Are you sure you want to remove the report "'+t+'"?',function(){var t={url:"/report/DeleteCustomReport",type:"post",data:{reportId:n}};$.ajax(t).done(function(){window.location.href="/report/list"}).fail(function(){})},{id:"removeCustomReportConfirm"})}};portal.reports.custom.EditCustomReportViewModel=function(){var n=this;this.allFields=_.map(portal.reports.custom.allFields,function(n){return new portal.reports.custom.FieldViewModel(n)});this.reportName=ko.observable("");this.availableFields=ko.observableArray();this.columns=ko.observableArray();this.hasValidationRun=ko.observable(!1);this.isNameValid=ko.computed(function(){var t=n.reportName();return t&&t.length>0});this.isColumnSelectionValid=ko.computed(function(){return n.columns().length>0});this.isNameValMessageVisible=ko.computed(function(){return n.hasValidationRun()&&!n.isNameValid()});this.isColumnSelectionValMessageVisible=ko.computed(function(){return n.hasValidationRun()&&!n.isColumnSelectionValid()});this.isFilterSelectionValIndicatorVisible=ko.computed(function(){return n.hasValidationRun()&&!_.every(n.columns(),function(n){return n.isFilterDataValid()})});this.sortedAvailableFields=ko.computed(function(){var t=n.availableFields();return _.sortByAll(t,["categoryDisplaySequence","displaySequence","displayName"])});this.availableSortColumns=ko.computed(function(){var t=_.filter(n.columns(),function(n){return!n.isSorted()});return _.sortBy(t,function(n){return n.displaySequence()})});this.sortColumns=ko.computed(function(){var t=_.filter(n.columns(),function(n){return n.isSorted()});return _.sortBy(t,function(n){return n.sortSequence()})});this.isMoveReportColumnUpEnabled=ko.computed(function(){var t=0,i=null;return _.forEach(n.columns(),function(n){n.isSelectedColumnTabOrder()&&(t++,i=n)}),t==1&&i.displaySequence()>1});this.isMoveReportColumnDownEnabled=ko.computed(function(){var t=0,i=null;return _.forEach(n.columns(),function(n){n.isSelectedColumnTabOrder()&&(t++,i=n)}),t==1&&i.displaySequence()<n.columns().length});this.isMoveSortColumnUpEnabled=ko.computed(function(){var t=0,i=null;return _.forEach(n.sortColumns(),function(n){n.isSelectedSortingTabOrder()&&(t++,i=n)}),t==1&&i.sortSequence()>1});this.isMoveSortColumnDownEnabled=ko.computed(function(){var t=0,i=null;return _.forEach(n.sortColumns(),function(n){n.isSelectedSortingTabOrder()&&(t++,i=n)}),t==1&&i.sortSequence()<n.sortColumns().length});this.reset=function(){n.hasValidationRun(!1);n.reportName("");n.availableFields.removeAll();n.columns.removeAll();n.allFields.forEach(function(t){n.availableFields.push(t)})};this.loadReport=function(t){n.reset();n.reportName(t.Name);_.forEach(t.Columns,function(t){var i=_.find(n.allFields,function(n){return n.id===t.ReportFieldId}),r;i&&(r=new portal.reports.custom.ReportColumnViewModel(n,i.model,t),n.addReportColumn(i,r))});n.sortReportColumns()};this.sortReportColumns=function(){n.columns.sort(function(n,t){var i=n.displaySequence(),r=t.displaySequence();return i<r?-1:i>r?1:0})};this.addReportColumn=function(t,i){n.availableFields.remove(t);i||(i=new portal.reports.custom.ReportColumnViewModel(n,t.model),i.displaySequence(n.columns().length+1));n.columns.push(i);n.sortReportColumns()};this.removeReportColumn=function(t){var r=_.filter(n.columns(),function(n){return n.displaySequence()>t.displaySequence()}),i;n.columns.remove(t);_.forEach(r,function(n){n.displaySequence(n.displaySequence()-1)});n.sortReportColumns();i=new portal.reports.custom.FieldViewModel(t.fieldModel);n.availableFields.push(i)};this.moveReportColumnUp=function(){var i=_.find(n.columns(),function(n){return n.isSelectedColumnTabOrder()}),t,r;if(i){if(t=i.displaySequence()-1,t===0)return;r=_.find(n.columns(),function(n){return n.displaySequence()===t});r.displaySequence(t+1);i.displaySequence(t);n.sortReportColumns()}};this.moveReportColumnDown=function(){var i=_.find(n.columns(),function(n){return n.isSelectedColumnTabOrder()}),t,r;if(i){if(t=i.displaySequence()+1,t>n.columns().length)return;r=_.find(n.columns(),function(n){return n.displaySequence()===t});r.displaySequence(t-1);i.displaySequence(t);n.sortReportColumns()}};this.addSortColumn=function(t){t.isSorted(!0);t.sortSequence(n.sortColumns().length)};this.removeSortColumn=function(t){var i=_.filter(n.sortColumns(),function(n){return n.sortSequence()>t.sortSequence()});t.isSorted(!1);_.forEach(i,function(n){n.sortSequence(n.sortSequence()-1)})};this.moveSortColumnUp=function(){var i=_.find(n.columns(),function(n){return n.isSelectedSortingTabOrder()}),t,r;if(i){if(t=i.sortSequence()-1,t===0)return;r=_.find(n.sortColumns(),function(n){return n.sortSequence()===t});r.sortSequence(t+1);i.sortSequence(t)}};this.moveSortColumnDown=function(){var i=_.find(n.columns(),function(n){return n.isSelectedSortingTabOrder()}),t,r;if(i){if(t=i.sortSequence()+1,t>n.sortColumns().length)return;r=_.find(n.sortColumns(),function(n){return n.sortSequence()===t});r.sortSequence(t-1);i.sortSequence(t)}};this.selectColInColumnTabOrder=function(t){var i=!t.isSelectedColumnTabOrder();n.columns().forEach(function(n){n.isSelectedColumnTabOrder(!1)});t.isSelectedColumnTabOrder(i)};this.selectColInSortingTabOrder=function(t){var i=!t.isSelectedSortingTabOrder();n.columns().forEach(function(n){n.isSelectedSortingTabOrder(!1)});t.isSelectedSortingTabOrder(i)};this.validate=function(){return n.hasValidationRun(!0),n.isNameValid()&&n.isColumnSelectionValid()&&_.every(n.columns(),function(n){return n.isFilterDataValid()})};this.reset()};portal.reports.custom.FieldViewModel=function(n){var t=this;this.model=n;this.id=n.Id;this.categoryName=this.model.CategoryName;this.categoryDisplaySequence=this.model.CategoryDisplaySequence;this.name=this.model.Name;this.filterTypeCode=n.FilterTypeCode;this.displaySequence=n.DisplaySequence;this.displayName=this.model.CategoryName+" : "+this.model.Name};portal.reports.custom.ReportColumnViewModel=function(n,t,i){var r=this,u,f,e,o,s;this.editReportViewModel=n;this.fieldModel=t;this.categoryName=t.CategoryName;this.name=t.Name;this.displayName=t.CategoryName+" : "+t.Name;this.filterTemplate="custom-report-filter-"+this.fieldModel.FilterTypeCode+"-template";this.id=0;this.reportFieldId=t.Id;this.displaySequence=ko.observable(0);this.isFiltered=ko.observable(!1);this.multiselectInitialFilterValues=[];this.multiselectFilterValues=ko.observableArray();this.dateFilterType=ko.observable();this.dateFilterDate1=ko.observable();this.dateFilterDate2=ko.observable();this.numberFilterMin=ko.observable();this.numberFilterMax=ko.observable();this.timespanFilterUnit1=ko.observable();this.timespanFilterQuantity1=ko.observable();this.timespanFilterUnit2=ko.observable();this.timespanFilterQuantity2=ko.observable();this.freetextFilterText=ko.observable("");this.isSorted=ko.observable(!1);this.sortSequence=ko.observable(0);this.sortDirections=[{id:1,text:{datetime:"Old to New",decimal:"Small to Large",int:"Small to Large",string:"A to Z",timespan:"Small to Large"}},{id:-1,text:{datetime:"New to Old",decimal:"Large to Small",int:"Large to Small",string:"Z to A",timespan:"Large to Small"}}];this.sortDirection=ko.observable();this.isSelectedColumnTabOrder=ko.observable(!1);this.isSelectedSortingTabOrder=ko.observable(!1);this.isDateFilterRangeVisible=ko.computed(function(){var n=r.dateFilterType();return n&&n.id==="range"});this.isFilterDataValid=ko.computed(function(){var n,t,i,u,f,e,o;return r.isFiltered()?r.fieldModel.FilterTypeCode==="multiselect"?r.multiselectFilterValues().length>0:r.fieldModel.FilterTypeCode==="daterange"?(n=r.dateFilterType(),!n)?!1:n.id==="range"?(t=r.dateFilterDate1(),i=r.dateFilterDate2(),t&&i&&t.length>0&&i.length>0):!0:r.fieldModel.FilterTypeCode==="numberrange"?(u=r.numberFilterMin(),f=r.numberFilterMax(),u!=null&&f!=null&&u.length>0&&f.length>0):r.fieldModel.FilterTypeCode==="timespanrange"?(e=/^[0-9]+$/,e.test(r.timespanFilterQuantity1())&&e.test(r.timespanFilterQuantity2())):r.fieldModel.FilterTypeCode==="freetext"?(o=r.freetextFilterText(),o!=null&&o.trim().length>0):!0:!0});this.isFilterValMessageVisible=ko.computed(function(){return r.editReportViewModel.hasValidationRun()&&!r.isFilterDataValid()});this.toggleFiltered=function(){r.isFiltered(!r.isFiltered())};this.getFilterData=function(){var n={};return r.fieldModel.FilterTypeCode==="multiselect"?(n.multiselect=[],r.multiselectFilterValues().forEach(function(t){n.multiselect.push(t)})):r.fieldModel.FilterTypeCode==="daterange"?n.daterange={dateTypeCode:r.dateFilterType().id,rangeDate1:r.dateFilterDate1(),rangeDate2:r.dateFilterDate2()}:r.fieldModel.FilterTypeCode==="numberrange"?n.numberrange={min:r.numberFilterMin(),max:r.numberFilterMax()}:r.fieldModel.FilterTypeCode==="timespanrange"?n.timespanrange={unitCode1:r.timespanFilterUnit1().id,quantity1:r.timespanFilterQuantity1(),unitCode2:r.timespanFilterUnit2().id,quantity2:r.timespanFilterQuantity2()}:r.fieldModel.FilterTypeCode==="freetext"&&(n.freetext=r.freetextFilterText()),n};this.onAfterFilterRender=function(n){var t=$(n);$(".datetime",t).datetimepicker({timeFormat:"h:mm TT"})};i&&(this.id=i.Id,this.reportFieldId=i.ReportFieldId,this.displaySequence(i.DisplaySequence),this.isFiltered(i.IsFiltered),this.isSorted(i.IsSorted),this.isFiltered()&&(u=JSON.parse(i.FilterJson),this.fieldModel.FilterTypeCode==="multiselect"?u.multiselect.forEach(function(n){r.multiselectInitialFilterValues.push(n);r.multiselectFilterValues.push(n)}):this.fieldModel.FilterTypeCode==="daterange"?(f=_.find(portal.reports.custom.dateFilterTypes,function(n){return n.id===u.daterange.dateTypeCode}),r.dateFilterType(f),r.dateFilterDate1(u.daterange.rangeDate1),r.dateFilterDate2(u.daterange.rangeDate2)):this.fieldModel.FilterTypeCode==="numberrange"?(r.numberFilterMin(u.numberrange.min),r.numberFilterMax(u.numberrange.max)):this.fieldModel.FilterTypeCode==="timespanrange"?(e=_.find(portal.reports.custom.timespanUnits,function(n){return n.id===u.timespanrange.unitCode1}),o=_.find(portal.reports.custom.timespanUnits,function(n){return n.id===u.timespanrange.unitCode2}),r.timespanFilterUnit1(e),r.timespanFilterQuantity1(u.timespanrange.quantity1),r.timespanFilterUnit2(o),r.timespanFilterQuantity2(u.timespanrange.quantity2)):this.fieldModel.FilterTypeCode==="freetext"&&r.freetextFilterText(u.freetext)),this.isSorted()&&(this.sortSequence(i.SortSequence),s=_.find(this.sortDirections,function(n){return n.id===i.SortDirection}),this.sortDirection(s)))}